PyQt与上下文菜单

15 投票
2 回答
27557 浏览
提问于 2025-04-15 11:13

我想在我的窗口上右键点击时创建一个上下文菜单。但是我真的不知道该怎么做。

有没有现成的组件可以用,还是我需要从头开始自己做?

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

2 个回答

15

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

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

我不能代表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)

撰写回答