0

我已经pandasQTableView.

在表中的一列中,我有 URL。

如何使 URL 变为蓝色,检测双击它们并在默认浏览器中打开它们?

4

1 回答 1

0

这是使用示例 pandas 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_())
于 2020-09-02T16:27:21.523 回答