Several context menus in PyQt based on mouse location

I have a window with multiple tables using QTableWidget (PyQt). I created a popup menu with the right mouse button and it works great. However, I need to create another pop-up menu based on the table on which the mouse cursor hangs at the moment of right-clicking. How can I make the mouse tell me which table it is in?

or, in other words, how to implement a method to have a specific context menu based on the location of the mouse?

I am using Python and PyQt.

My popup menu is designed like this code ( Qt's PedroMorgan answer and context menu ):

class Foo( QtGui.QWidget ): def __init__(self): QtGui.QWidget.__init__(self, None) # Toolbar toolbar = QtGui.QToolBar() # Actions self.actionAdd = toolbar.addAction("New", self.on_action_add) self.actionEdit = toolbar.addAction("Edit", self.on_action_edit) self.actionDelete = toolbar.addAction("Delete", self.on_action_delete) # Tree self.tree = QtGui.QTreeView() self.tree.setContextMenuPolicy( Qt.CustomContextMenu ) self.connect(self.tree, QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'), self.on_context_menu) # Popup Menu self.popMenu = QtGui.QMenu( self ) self.popMenu.addAction( self.actionEdit ) self.popMenu.addAction( self.actionDelete ) self.popMenu.addSeparator() self.popMenu.addAction( self.actionAdd ) def on_context_menu(self, point): self.popMenu.exec_( self.tree.mapToGlobal(point) ) 
+4
source share
1 answer

One way is to subclass QTableWidget and then implement your own contextMenuEvent method. You can then set up a different context menu event handling for each of your instances. Here is a small example.

 from PyQt4 import QtGui, QtCore import sys class MyTableWidget(QtGui.QTableWidget): def __init__(self, name='Table1', parent=None): super(MyTableWidget, self).__init__(parent) self.name = name def contextMenuEvent(self, event): menu = QtGui.QMenu(self) Action = menu.addAction("I am a " + self.name + " Action") Action.triggered.connect(self.printName) menu.exec_(event.globalPos()) def printName(self): print "Action triggered from " + self.name class Main(QtGui.QWidget): def __init__(self, parent=None): super(Main, self).__init__(parent) layout = QtGui.QVBoxLayout(self) self.table1 = MyTableWidget(name='Table1', parent=self) self.table2 = MyTableWidget(name='Table2', parent=self) layout.addWidget(self.table1) layout.addWidget(self.table2) self.setLayout(layout) if __name__ == '__main__': app = QtGui.QApplication(sys.argv) main = Main() main.show() app.exec_() 
+5
source

Source: https://habr.com/ru/post/1369046/


All Articles