【问题标题】:Get header section text in QHeaderView在 QHeaderView 中获取标题部分文本
【发布时间】:2020-03-28 18:21:28
【问题描述】:

我在 QTableWidget 中对 QHeaderView 进行子类化,以提供用于隐藏/显示部分的自定义功能。有没有办法从标题视图中获取部分的文本?我知道我可以在表格范围内做到这一点,但这不是我想要做的。

我意识到数据存储在模型内部,但是以下测试只返回“无”:

self.model().index(0,0).data()

【问题讨论】:

    标签: python pyqt qheaderview


    【解决方案1】:

    您可以使用分配给QHeaderView的模型并使用headerData()方法获取文本:

    from PyQt5 import QtCore, QtGui, QtWidgets
    
    
    class HeaderView(QtWidgets.QHeaderView):
        def text(self, section):
            if isinstance(self.model(), QtCore.QAbstractItemModel):
                return self.model().headerData(section, self.orientation())
    
    
    if __name__ == "__main__":
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
    
        w = QtWidgets.QTableWidget(10, 4)
        w.setHorizontalHeaderLabels(
            ["section-{}".format(i) for i in range(w.columnCount())]
        )
    
        horizontal_headerview = HeaderView(QtCore.Qt.Horizontal, w)
        w.setHorizontalHeader(horizontal_headerview)
    
        print(horizontal_headerview.text(1))
    
        vertical_headerview = HeaderView(QtCore.Qt.Vertical, w)
        w.setVerticalHeader(vertical_headerview)
    
        print(vertical_headerview.text(2))
    
        w.show()
    
        sys.exit(app.exec_())
    

    【讨论】:

    • 哇所以你需要调用header的model的header!我试图直接获取数据,这当然行不通。
    猜你喜欢
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多