I have a QTableWidget with a number of columns that are only checkboxes (and some that aren't). I am trying to implement a feature so that when the user right clicks on a header item related to a "checkbox only" column, they are presented with the option to "uncheck all" or "check all".
So far, I've managed to implement a customContextMenu
via 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)
Which 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 pops up a context menu, however I cannot find any way to get the index of the header that was right-clicked, I've tried self.headers.selectedIndexes()
as well as self.headers.currentIndex()
but these seem to only relate to the actual table selections, and not the headers.
Once I manage to get the right-clicked header index, I can easily restrict the menu to show only when the right indexes are selected (those columns with only checkboxes), so that's an additional thing, really.
What am I missing? Thanks in advance for any help.
The customContextMenuRequested
signal sends the position of the context menu event as a QPoint
. Conveniently, the table's headers have an overload of logicalIndexAt that can directly exploit that, so you can simply do:
def show_header_context_menu(self, position):
column = self.headers.logicalIndexAt(position)
I see you're using python but I think this should still work.
Try creating a QHeaderView
-derived class and try overriding the behaviour of
void QHeaderView::mousePressEvent ( QMouseEvent * e )
to get the right-click mouse event, then use
int QHeaderView::logicalIndexAt ( int x, int y ) const
to get the logical index of the column that was right clicked. Lastly display your context menu.
See http://doc.qt.nokia.com/4.7-snapshot/qheaderview.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With