Widget right-click to pop up the error location… here is a solution to the problem.
Widget right-click to pop up the error location
I added a right-click action to the widget embedded in the QTableWidget
. When I right-click, QMenu
appears in the wrong place. Here is my code :
I added widgets to QTableWidget
:
tableWidget = self._dlg.tableWidget
variableLabel = QLabel()
variableLabel.setText(str(var))
variableLabel.setContextMenuPolicy(Qt.CustomContextMenu)
variableLabel.customContextMenuRequested.connect(self.showMenu)
tableWidget.setCellWidget(row, 0, variableLabel)
The menu is shown here:
def showMenu(self, pos):
print("pos", str(pos))
menu = QMenu()
applyAction = menu.addAction("Tümüne Uygula")
action = menu.exec_(self._dlg.mapToGlobal(pos))
if action == applyAction:
...
Finally, here is my result, when I click on the colored cell (QLabel
), the menu appears below:
Solution
customContextMenuRequested
is sent relative to the widget that emits it, in your case to QLabel
, assuming showMenu
() belongs to any widget, we can use the sender()
method to get it.
def showMenu(self, pos):
menu = QMenu()
applyAction = menu.addAction("Tümüne Uygula")
action = menu.exec_(self.sender().mapToGlobal(pos))
if action == applyAction:
If showMenu()
does not belong to a widget, it must explicitly pass the tag using functools.part
from functools import partial
...
tableWidget = self._dlg.tableWidget
variableLabel = QLabel()
variableLabel.setText(str(var))
variableLabel.setContextMenuPolicy(Qt.CustomContextMenu)
variableLabel.customContextMenuRequested.connect(partial(self.showMenu, variableLabel))
tableWidget.setCellWidget(row, 0, variableLabel)
...
def showMenu(self, label, pos):
menu = QMenu()
applyAction = menu.addAction("Tümüne Uygula")
action = menu.exec_(label.mapToGlobal(pos))
if action == applyAction:
...