4
votes

I have a window with multiple tables using QTableWidget (PyQt). I created a popup menu using the right click mouse and it works fine. However, I need to create different popup menu based on which table the mouse is hovering over at the time the right mouse is clicked. How can I get the mouse to tell me which table it is hovering over?

or, put in another way, how to implement a method so as to have a specific context menu based on mouse location?

I am using Python and PyQt.

My popup menu is developed similar to this code (PedroMorgan answer from Qt 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) )
1
You're talking about QTableWidget but your example uses a QTreeView. Which one are you using? - aukaost

1 Answers

6
votes

One way is to subclass QTableWidget and then implement your own contextMenuEvent method. Then you can set different handling of the context menu event for each of your instances. Here's 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_()