PyQt和上下文菜单

时间:2009-04-23 15:26:42

标签: python qt pyqt menu

我需要在我的窗口右键单击时创建一个上下文菜单。但我真的不知道如何实现这一目标。

是否有任何小部件,或者我必须从头开始创建它?

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

2 个答案:

答案 0 :(得分:40)

我不能说python,但它在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 :(得分: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) )