PySide6\u4e2d\u7684\u5927\u8868\u683c\u63a7\u4ef6\uff08TableView\uff09\u662f\u4e00\u4e2a\u7528\u4e8e\u5c55\u793a\u548c\u7f16\u8f91\u8868\u683c\u6570\u636e\u7684\u63a7\u4ef6\u3002\u4ee5\u4e0b\u662f\u4e00\u4e2a\u7b80\u5355\u7684\u4f7f\u7528\u5927\u8868\u683c\u7684\u793a\u4f8b\u4ee3\u7801\uff1a\n\npython\nfrom PySide6.QtCore import Qt, QAbstractTableModel\nfrom PySide6.QtGui import QStandardItemModel\nfrom PySide6.QtWidgets import QApplication, QMainWindow, QTableView\n\nclass MyTableModel(QAbstractTableModel):\n def __init__(self, data):\n super().__init__()\n self.data = data\n\n def rowCount(self, parent):\n return len(self.data)\n\n def columnCount(self, parent):\n if len(self.data) > 0:\n return len(self.data[0])\n return 0\n\n def data(self, index, role):\n if role == Qt.DisplayRole:\n row = index.row()\n col = index.column()\n return str(self.data[row][col])\n\n def headerData(self, section, orientation, role):\n if role == Qt.DisplayRole:\n if orientation == Qt.Horizontal:\n return f"Column {section+1}"\n else:\n return f"Row {section+1}"\n\nif __name__ == "__main__":\n app = QApplication([])\n window = QMainWindow()\n \n # \u521b\u5efa\u6a21\u578b\u548c\u6570\u636e\n data = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n ]\n\n model = MyTableModel(data)\n\n # \u521b\u5efa\u5927\u8868\u683c\u5e76\u8bbe\u5b9a\u6a21\u578b\n table = QTableView()\n table.setModel(model)\n\n # \u8bbe\u5b9a\u5927\u8868\u683c\u7684\u884c\u548c\u5217\u5927\u5c0f\u8c03\u6574\u6a21\u5f0f\n table.resizeColumnsToContents()\n table.resizeRowsToContents()\n\n # \u5c06\u5927\u8868\u683c\u6dfb\u52a0\u5230\u4e3b\u7a97\u53e3\n window.setCentralWidget(table)\n window.show()\n\n app.exec()\n\n\n\u5728\u8fd9\u4e2a\u793a\u4f8b\u4e2d\uff0c\u6211\u4eec\u9996\u5148\u5b9a\u4e49\u4e86\u4e00\u4e2a\u81ea\u5b9a\u4e49\u7684\u6a21\u578b\u7c7b\uff0c\u7ee7\u627f\u4e8e\u201cQAbstractTableModel\u201d\u3002\u5728\u8be5\u7c7b\u4e2d\uff0c\u6211\u4eec\u91cd\u5199\u4e86\u201crowCount()\u201d\u3001\u201ccolumnCount()\u201d\u3001\u201cdata()\u201d\u548c\u201cheaderData()\u201d\u7b49\u65b9\u6cd5\uff0c\u7528\u4e8e\u5b9a\u4e49\u8868\u683c\u7684\u884c\u6570\u3001\u5217\u6570\u3001\u6570\u636e\u4ee5\u53ca\u8868\u5934\u3002\u7136\u540e\uff0c\u6211\u4eec\u521b\u5efa\u4e86\u4e00\u4e2a\u6570\u636e\u5217\u8868\uff0c\u5e76\u5c06\u5176\u4f20\u9001\u7ed9\u6a21\u578b\u3002\u7136\u540e\uff0c\u6211\u4eec\u521b\u5efa\u4e00\u4e2a\u5927\u8868\u683c\uff0c\u5e76\u5c06\u6a21\u578b\u8bbe\u5b9a\u4e3a\u5176\u6a21\u578b\u3002\u6700\u540e\uff0c\u5c06\u5927\u8868\u683c\u6dfb\u52a0\u5230\u4e3b\u7a97\u53e3\u5e76\u5c55\u793a\u51fa\u6765\u3002\n\n\u8fd9\u662f\u4e00\u4e2a\u975e\u5e38\u7b80\u5355\u7684\u5927\u8868\u683c\u4f7f\u7528\u793a\u4f8b\uff0c\u4f60\u53ef\u4ee5\u6839\u636e\u81ea\u5df1\u7684\u9700\u6c42\u8fdb\u4e00\u6b65\u6269\u5c55\u548c\u81ea\u5b9a\u5236\u5927\u8868\u683c\u7684\u529f\u80fd\u3002


原文地址: https://www.cveoy.top/t/topic/pLpd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录