2009-04-23 48 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))