2009-04-23 92 views
14

我需要创建一个上下文菜单,右键单击我的窗口。但我真的不知道如何实现这一点。PyQt和上下文菜单

是否有任何小工具,或者我必须从一开始创建它?

的编程语言:Python的
图形LIB的:Qt(PyQt的)

回答

40

我不能蟒蛇说话,但它在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) 
+1

注意,在PyQt4中,在包CustomContextMenu位置是在这里:PyQt4.QtCore.Qt.CustomContextMenu – 2010-12-27 17:08:50

+2

爱是爱两年,19个upvotes后随机downvote :-P – 2011-09-24 01:48:49

14

它展示了如何使用在工具栏和上下文菜单操作另一个例子。

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))