PyQt and context menu

后端 未结 2 394
不思量自难忘°
不思量自难忘° 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)
    

提交回复
热议问题