题
我需要在我的窗口上创建右键单击上下文菜单。但我真的不知道该如何实现这个目标。
是否有任何部件,或者我必须从一开始就建立了吗?
的编程语言:Python的结果 图形LIB的:Qt(PyQt的)
解决方案
我不能为蟒说话,但它是在C ++中相当容易的。
首先创建一个构件之后您将策略:
w->setContextMenuPolicy(Qt::CustomContextMenu);
,那么您的上下文菜单事件连接到一个槽:
connect(w, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(ctxMenu(const QPoint &)));
最后,需要实现槽:
void A::ctxMenu(const QPoint &pos) {
QMenu *menu = new QMenu;
menu->addAction(tr("Test Item"), this, SLOT(test_slot()));
menu->exec(w->mapToGlobal(pos));
}
这是你怎么做它在C ++中,不应该是Python的API中太不一样了。
修改在谷歌四处寻找后,这里的在python的我的例子的建立部分:
self.w = QWhatever();
self.w.setContextMenuPolicy(Qt.CustomContextMenu)
self.connect(self.w,SIGNAL('customContextMenuRequested(QPoint)'), self.ctxMenu)
其他提示
其示出了如何在工具栏和上下文菜单使用动作另一个例子。
class Foo( QtGui.QWidget ):
def __init__(self):
QtGui.QWidget.__init__(self, None)
mainLayout = QtGui.QVBoxLayout()
self.setLayout(mainLayout)
# Toolbar
toolbar = QtGui.QToolBar()
mainLayout.addWidget(toolbar)
# Action are added/created using the toolbar.addAction
# which creates a QAction, and returns a pointer..
# .. instead of myAct = new QAction().. toolbar.AddAction(myAct)
# see also menu.addAction and others
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)
self.actionDelete.setDisabled(True)
# Tree
self.tree = QtGui.QTreeView()
mainLayout.addWidget(self.tree)
self.tree.setContextMenuPolicy( Qt.CustomContextMenu )
self.connect(self.tree, QtCore.SIGNAL('customContextMenuRequested(const QPoint&)'), self.on_context_menu)
# Popup Menu is not visible, but we add actions from above
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) )
不隶属于 StackOverflow