Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQt and context menu

Tags:

python

qt

menu

pyqt

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 from the beginning?

Programming language: Python
Graphical lib: Qt (PyQt)

like image 776
Max Frai Avatar asked Apr 23 '09 15:04

Max Frai


People also ask

How to create menu in PyQt5?

To create a menu for a PyQt5 program we need to use a QMainWindow. This type of menu is visible in many applications and shows right below the window bar. It usually has a file and edit sub menu. The top menu can be created with the method menuBar().

How do I create a drop down menu in PYQT?

First, we define the comboBox, then we add a bunch of options, then we move the comboBox (a drop down button). When the combo box has a choice, it will take the string version of the choice, and run self.

Which actions displays the Windows context menu?

In Microsoft Windows, pressing the Application key or Shift+F10 opens a context menu for the region that has focus.


1 Answers

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)
like image 91
Evan Teran Avatar answered Sep 16 '22 21:09

Evan Teran