Question

I've written a descendant of QTreeView with multiple columns. I want to create a popup menu that appears whe nthe user right-clicks over the column headers. I have tried catching signals from QTreeView for this, but QTreeView doesn't seem to emit signals on the headers. QTreeView.header() does. I therefore believe I must either:
1: connect one of QHeaderView's signals to a popup function - I have been unable to find a signal that is triggered on a single right click - I have tried sectionClicked, sectionHandleDoubleClicked, sectionDoubleClicked, sectionPressed (not surprised the double click functions didn't catch a single right click - but they do catch a double right click)

self.header().sectionClicked.connect(self.headerMenu)
self.header().sectionHandleDoubleClicked.connect(self.headerMenu)
self.header().sectionDoubleClicked.connect(self.headerMenu)
self.header().sectionPressed.connect(self.headerMenu)

or,
2: write a descendant of QHeaderView with my own MousePressEvent function, and use that for my headers. I have so far been unsuccessful in connecting the new header class to the QTreeView descendant. I keep getting a Segmentation Fault on runtime, with no more explanation.

#in DiceView's init, where DiceHeaders is the QHeaderView descendant
self.setHeader(DiceHeaders())

Any ideas?

Was it helpful?

Solution

I discovered the setContextMenuPolicy function:

self.header().setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.header().customContextMenuRequested.connect(self.headerMenu)

Then, in headerMenu:

def headerMenu(self, pos):
    globalPos = self.mapToGlobal(pos)
    menu = QMenu()
    menu.addAction("test item")
    selectedItem = menu.exec_(globalPos)
    if selectedItem:
        print "selected: ", selectedItem

OTHER TIPS

I'd go for solution n°2 : Write your own class inheriting QHeaderView. Your segmentation fault may be coming from a python/pyqt glitch ? You should make sure that you DiceHeaders object exists by keeping a reference to it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top