Right click on QHeaderView inside QTreeView

I wrote a descendant of QTreeView with multiple columns. I want to create a popup menu that appears when the user right-clicks over the column headings. I tried to catch signals from the QTreeView for this, but the QTreeView doesn't seem to emit signals in the headers. QTreeView.header () does. So I believe I should: 1: connect one of the QHeaderView signals to the popup function - I could not find a signal that is triggered by a single right click - I tried sectionClicked, sectionHandleDoubleClicked, sectionDoubleClicked, sectionPressed (not surprised that the double click functions are not caught a single right click - but they do 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 it for my headers. I still have no success in attaching a new header class to a QTreeView descendant. I keep getting segmentation error at runtime, without any explanation.

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

      

Any ideas?

+2


a source to share


2 answers


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

      

+3


a source


I would go for solution # 2: write your own class inheriting QHeaderView. Segmentation fault can occur due to python / pyqt bug? You need to make sure the DiceHeaders object exists by keeping a reference to it.



0


a source







All Articles