paw*_*asz 3 python user-interface pyqt
我\xe2\x80\x99m 使用 PyQt5 开发 Python GUI 应用程序,该应用程序具有用于显示数据的 QTableView。
\n这是代码:
\nimport sys\n\nfrom PyQt5 import QtWidgets, QtCore\nfrom PyQt5.QtCore import Qt\n\n\nclass DataModel(QtCore.QAbstractTableModel):\n def __init__(self):\n super().__init__()\n self.data = []\n\n def data(self, index, role):\n if role == Qt.DisplayRole:\n return self.data[index.row()][index.column()]\n\n def rowCount(self, index):\n return len(self.data)\n\n def columnCount(self, index):\n return len(self.data[0])\n\n\nclass MainWindow(UI.UserInterface):\n def __init__(self):\n super().__init__()\n self.model = DataModel()\n self.load()\n self.TableView.setModel(self.model)\n self.TableView.resizeColumnsToContents()\n self.TableView.horizontalHeader().setStretchLastSection(True)\n\n def load(self):\n try:\n self.model.data = [(1, \'2020-01-10 00:00:00\', \'KANIA\', \'HENRYK\', 4219)]\n except Exception:\n pass\n\n\nif __name__ == "__main__":\n app = QtWidgets.QApplication(sys.argv)\n window = MainWindow()\n window.show()\n app.exec_()\nRun Code Online (Sandbox Code Playgroud)\n该类UI.UserInterface位于单独的模块中。它具有QWidgets的界面和布局QWidgets。其中之一是QTableView。
我似乎找不到一种方法来设置QTableView.
我寻找了不同的解决方案(其中一些如下),但没有一个有效:
\nhttps://doc.qt.io/qt-5/sql-presenting.html(这个是用C++写的。我不太明白)
\n您必须实施headerData():
class DataModel(QtCore.QAbstractTableModel):
# ...
def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
return 'Column {}'.format(section + 1)
return super().headerData(section, orientation, role)
Run Code Online (Sandbox Code Playgroud)
显然,即使使用包含要显示的标签的简单列表,您也可以设置自己的标签。
请注意,为子类命名新属性时应非常小心,因为它们可能已经存在。
最重要的是,您不应该覆盖self.data.
| 归档时间: |
|
| 查看次数: |
6982 次 |
| 最近记录: |