如何在PyQt中设置QHeaderView的标签?

2024-05-02 12:36:17 发布

您现在位置:Python中文网/ 问答频道 /正文

在Pyqt中,我试图使QTableWidget的QHeaderView响应鼠标右键单击。 我已经子类化了QHeaderView,并且重载了mousePressEvent。

然后我可以将其设置为我的自定义QTableWidget的头,DataTable类。但是我不知道如何设置标题的标签。

谢谢你的帮助!

这是一些代码。

class Header( QtGui.QHeaderView ):
    def __init__ ( self, parent ):
        QtGui.QHeaderView.__init__( self, QtCore.Qt.Vertical, parent=parent )

    def mousePressEvent( self, event ):
        if event.button() == QtCore.Qt.RightButton:
            do_stuff()


class DataTable( QtGui.QTableWidget ):
    def __init__ ( self ):
        QtGui.QTableWidget.__init__( self )
        self.setShowGrid(True)

        self.header = Header( parent = self )
        self.header.setClickable(True)
        self.setHorizontalHeader( self.header )

    def set_header( self, labels ):
        ???

Tags: selfeventinitdefqtclassparentheader
2条回答

简短回答:

QTableWidget有一个名为“setHorizontalHeaderLabels”的函数,只需向它提供标题即可。就像这样:

your_table_widget.setHorizontalHeaderLabels(["name", "phone number", "email"])

我本想把这个作为评论添加到pedrotech,但我没有足够的代表来发表评论。

此示例代码应该有用:

import sys
import string
from PyQt4.QtCore import *
from PyQt4.QtGui import *

class Header(QHeaderView):
    def __init__(self, parent=None):
        super(Header, self).__init__(Qt.Horizontal, parent)

        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.ctxMenu)
        self.hello = QAction("Hello", self)
        self.hello.triggered.connect(self.printHello)
        self.currentSection = None

    def printHello(self):
        data = self.model().headerData(self.currentSection, Qt.Horizontal)
        print data.toString()

    def ctxMenu(self, point):
        menu = QMenu(self)
        self.currentSection = self.logicalIndexAt(point)
        menu.addAction(self.hello)
        menu.exec_(self.mapToGlobal(point))


class Table(QTableWidget):
    def __init__(self, parent=None):
        super(Table, self).__init__(parent)
        self.setHorizontalHeader(Header(self))
        self.setColumnCount(3)
        self.setHorizontalHeaderLabels(['id', 'name', 'username'])
        self.populate()

    def populate(self):
        self.setRowCount(10)
        for i in range(10):
            for j,l in enumerate(string.letters[:3]):
                self.setItem(i, j, QTableWidgetItem(l)) 

if __name__ == '__main__':
    app = QApplication(sys.argv)
    t = Table()
    t.show()
    app.exec_()
    sys.exit()

相关问题 更多 >