如何解决QTableView-将链接设置为蓝色,检测其是否单击并在默认浏览器中将其打开
我在pandas
中实现了QTableView
表。
在表的一列中,我有URL。
如何将网址设置为蓝色,检测到双击并在默认浏览器中将其打开?
解决方法
以下是完整的复制粘贴示例,其中包含使用示例熊猫DataFrame构建的模型。
请注意,双击仍然在模型的数据功能中实现,并且双击时会强制将所有非URL单元强制转换为“编辑”模式。
import webbrowser
from PyQt5 import QtGui,QtWidgets,QtCore
from PyQt5.QtCore import Qt
import sys
import pandas as pd
class MainWindow(QtWidgets.QMainWindow):
def __init__(self,*args,obj=None,**kwargs):
super(MainWindow,self).__init__(*args,**kwargs)
self.centralwidget = QtWidgets.QWidget(self)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding,QtWidgets.QSizePolicy.Fixed)
self.centralwidget.setSizePolicy(sizePolicy)
self.pdtable = QtWidgets.QTableView(self.centralwidget)
sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding,QtWidgets.QSizePolicy.Fixed)
self.pdtable.setSizePolicy(sizePolicy)
dataPD = [['https://www.example.com',10.0],['nick',15.0],['juli',14.0]]
self.df = pd.DataFrame(dataPD,columns=['Name','Age'])
self.model = PandasTableModel(self.df)
self.pdtable.setModel(self.model)
self.pdtable.doubleClicked.connect(self.OpenLink)
self.setCentralWidget(self.centralwidget)
def OpenLink(self,item):
for index in self.pdtable.selectionModel().selectedIndexes():
value = str(self.df.iloc[index.row()][index.column()])
if value.startswith("http://") or value.startswith("https://"):
webbrowser.open(value)
class PandasTableModel(QtGui.QStandardItemModel):
def __init__(self,data,parent=None):
QtGui.QStandardItemModel.__init__(self,parent)
self._data = data
for row in data.values.tolist():
data_row = [ QtGui.QStandardItem("{}".format(x)) for x in row ]
self.appendRow(data_row)
return
def rowCount(self,parent=None):
return len(self._data.values)
def columnCount(self,parent=None):
return self._data.columns.size
def headerData(self,x,orientation,role):
if orientation == Qt.Horizontal and role == Qt.DisplayRole:
return self._data.columns[x]
if orientation == Qt.Vertical and role == Qt.DisplayRole:
return self._data.index[x]
return None
def data(self,index,role):
if role == Qt.ForegroundRole:
value = str(self._data.iloc[index.row()][index.column()])
if value.startswith("https://") or value.startswith("http://"):
return QtGui.QColor("blue")
elif role == Qt.DisplayRole:
return str(self._data.iloc[index.row(),index.column()])
elif role == Qt.EditRole:
return str(self._data.iloc[index.row(),index.column()])
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
app.setStyle("Fusion")
main = MainWindow()
main.show()
main.resize(600,400)
sys.exit(app.exec_())
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。