14

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

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

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

4

2 回答 2

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)
于 2009-04-23T16:14:44.097 回答
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) )
于 2009-06-06T04:07:47.460 回答