Getting right-click column header for QTableWidget

I have a QTableWidget with several columns that are just checkboxes (and some are not). I am trying to implement a function, so when the user right-clicks on the header element associated with the “only checkbox” column, they will be given the option to “remove all” or “check all”.

So far, I have managed to implement customContextMenu with the following signals:

 self.headers = self.tblData.horizontalHeader() self.headers.setContextMenuPolicy(Qt.CustomContextMenu) self.headers.customContextMenuRequested.connect(self.show_header_context_menu) self.headers.setSelectionMode(QAbstractItemView.SingleSelection) 

This leads to the following context menu call:

 def show_header_context_menu(self, position): menu = QMenu() deselect = menu.addAction("Clear Checked") ac = menu.exec_(self.tblData.mapToGlobal(position)) if ac == deselect: pass #Actually do stuff here, of course 

This displays the context menu, however I cannot find a way to get the index of the header that was right-clicked, I tried self.headers.selectedIndexes() as well as self.headers.currentIndex() , but they seem to apply only to selection of actual tables, not headers.

Once I manage to get the right-click header index, I can easily restrict the menu display only when choosing the right indexes (these columns are with only checkboxes), so actually it is.

What am I missing? Thanks in advance for any help.

+4
source share
2 answers

The customContextMenuRequested signal sends the context menu event position as QPoint . Conveniently, the table headers have a logicalIndexAt overload that can directly use this, so you can simply do:

 def show_header_context_menu(self, position): column = self.headers.logicalIndexAt(position) 
+2
source

I see that you are using python, but I think this should work anyway.

Try creating the QHeaderView -derived class and try overriding the behavior

 void QHeaderView::mousePressEvent ( QMouseEvent * e ) 

to get the mouse event right click then use

 int QHeaderView::logicalIndexAt ( int x, int y ) const 

to get the logical index of the column that was right-clicked. Finally, you will see a context menu.

See http://doc.qt.nokia.com/4.7-snapshot/qheaderview.html

0
source

All Articles