In Pyqt, I am trying to make the QHeaderView of a QTableWidget respond to right mouse clicks. I have subclassed QHeaderView and i have overloaded the mousePressEvent.
Then i can set it as as the header of my custom QTableWidget, the DataTable class. However i don't understand how to set the labels of the header.
Thanks for helping!
Here is some code.
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 ):
???
This sample code should be useful:
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()