我有一个使用QTableWidget(PyQt)的多个表窗口。我使用鼠标右键单击创建了一个弹出菜单,它工作正常。 但是,我需要根据单击鼠标右键时鼠标悬停在哪个表上创建不同的弹出菜单。我怎样才能让鼠标告诉我它在哪个桌面上空盘旋?
或者换句话说,如何实现一个方法,以便根据鼠标位置设置特定的上下文菜单?
我正在使用Python和PyQt。
我的弹出式菜单与此代码类似(PedroMorgan从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) )
答案 0 :(得分:5)
一种方法是继承QTableWidget,然后实现自己的contextMenuEvent
方法。然后,您可以为每个实例设置上下文菜单事件的不同处理。这是一个小例子。
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_()