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

标签 python user-interface pyqt

我正在使用 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/

相关文章:

java - 使用 CSS 为 Javafx 设计样式

python - QProgressBar 中的 MySQL 咨询

docker - 如何从Dockerfile创建交互式图像?

python - 如何使 QToolTip 消息持久化?

python : Comma at the end of print statement

python - 尝试从新闻文章中提取元数据

ios - 如何通过 Interface Builder 将 UIImage 对象放置在 UITableViewController View 的底部

Java Swing : Generating dynamic GUI forms from XML

python - 线性同余发生器 - 弱测试结果

python - 多处理映射引发异常