PyQt and context menu

后端 未结 2 377
不思量自难忘°
不思量自难忘° 2020-12-31 07:04

I need to create a context menu on right clicking at my window. But I really don\'t know how to achieve that.

Are there any widgets for that, or I have to create it

相关标签:
2条回答
  • 2020-12-31 07:41

    I can't speak for python, but it's fairly easy in C++.

    first after creating the widget you set the policy:

    w->setContextMenuPolicy(Qt::CustomContextMenu);
    

    then you connect the context menu event to a slot:

    connect(w, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(ctxMenu(const QPoint &)));
    

    Finally, you implement the slot:

    void A::ctxMenu(const QPoint &pos) {
        QMenu *menu = new QMenu;
        menu->addAction(tr("Test Item"), this, SLOT(test_slot()));
        menu->exec(w->mapToGlobal(pos));
    }
    

    that's how you do it in c++ , shouldn't be too different in the python API.

    EDIT: after looking around on google, here's the setup portion of my example in python:

    self.w = QWhatever();
    self.w.setContextMenuPolicy(Qt.CustomContextMenu)
    self.connect(self.w,SIGNAL('customContextMenuRequested(QPoint)'), self.ctxMenu)
    
    0 讨论(0)
  • 2020-12-31 07:41

    Another example which shows how to use actions in a toolbar and context menu.

    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) )
    
    0 讨论(0)
提交回复
热议问题