gpt4 book ai didi

python - 如何为 QTableView 列设置标题标签?

转载 作者:行者123 更新时间:2023-12-01 23:45:16 25 4
gpt4 key购买 nike

我正在使用 PyQt5 开发一个 Python GUI 应用程序,它有一个用于显示数据的 QTableView。

代码如下:

import sys

from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import Qt


class DataModel(QtCore.QAbstractTableModel):
def __init__(self):
super().__init__()
self.data = []

def data(self, index, role):
if role == Qt.DisplayRole:
return self.data[index.row()][index.column()]

def rowCount(self, index):
return len(self.data)

def columnCount(self, index):
return len(self.data[0])


class MainWindow(UI.UserInterface):
def __init__(self):
super().__init__()
self.model = DataModel()
self.load()
self.TableView.setModel(self.model)
self.TableView.resizeColumnsToContents()
self.TableView.horizontalHeader().setStretchLastSection(True)

def load(self):
try:
self.model.data = [(1, '2020-01-10 00:00:00', 'KANIA', 'HENRYK', 4219)]
except Exception:
pass


if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()

UI.UserInterface 类在单独的模块中。它有界面QWidgets和布局QWidgets。其中之一是 QTableView

我似乎找不到为 QTableView 设置标题标签的方法。

我寻找了不同的解决方案(其中一些在下面),但没有一个有效:

https://doc.qt.io/qt-5/sql-presenting.html (这个是C++写的,不太懂)

最佳答案

您必须实现 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)

显然,即使使用包含要显示的标签的简单列表,您也可以设置自己的标签。

请注意,在为子类命名新属性时应该非常小心,因为它们可能已经存在。
最重要的是,您应该覆盖self.data

关于python - 如何为 QTableView 列设置标题标签?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64287713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com