How can i create a Context menu in Qt Designer (1.3)? Certainly I want to create it with out writing one line code!!
3 Answers
You need two steps in Qt Designer and a few lines of code in the form constructor:
Set the
contextMenuPolicy
of your widget to the valueActionsContextMenu
.Create actions using the action editor tab.
For each action you created in Qt Designer, put a line such as the following in the form constructor:
ui->yourwidget->addAction(ui->youraction);

- 1,567
- 1
- 11
- 12

- 519
- 5
- 8
-
The OP stated "Certainly I want to create it with out writing one line code!!" which this doesn't satisfy. – Dale Sep 03 '18 at 04:50
-
2OP's in the wrong place if he's looking for literally no code. And probably in the wrong career. – David Culbreth Sep 22 '19 at 01:25
-
Sorry but, where do I have to put ui->yourwidget->addAction(ui->youraction) exactly? Who is "ui'? I'm new to Python – Pedro Antônio Sep 25 '21 at 23:47
I can suggest a method that allows you to write a few lines of general code manually and then add context menus for any number of components on the form using only Qt Creator. For example, we have three components on the form: QLabel lbl1, QPushButton btn1, and QTextEdit ed1. We need to add it's own context menu to each of them. To do this:
- Add the
myContextMenuHandler(QPoint)
slot to the form (QMainWindow). - In the cpp-file of the form, write the following code for this slot:
void MainWindow::myContextMenuHandler(QPoint pt)
{
QMenu *mnu = ui->menuPopupMenus->findChild<QMenu *>("menu" + sender()->objectName());
if (mnu)
mnu->popup(dynamic_cast<QWidget *>(sender())->mapToGlobal(pt));
}
- Add a top-level menu item (with title="PopupMenus" and name="menuPopupMenus" (name is autogenerated by Qt Creator) to the Menu Bar of form.
- Create three subitems for this menu item:
- title="lbl1" (same as our QLabel), name=menulbl1 (autogenerated)
- title="btn1" (same as our QPushButton), name=menubtn1 (autogenerated)
- title="ed1" (same as our QTextEdit), name=menued1 (autogenerated)
Each of these items must have the set of its own subitems, which will be displayed as a context menu for the corresponding component (e.g. "lbl1" item will have "Item1", "Item2" and "Item3" subitems; "btn1" - "Item4" and "Item5"; "ed1" - "Item6").
- connect
customContextMenuRequested(QPoint)
signal of lbl1, btn1 and ed1 components tomyContextMenuHandler(QPoint)
slot of form. - set
contextMenuPolicy
property of lbl1, btn1 and ed1 components to "CustomContextMenu" - add the following line of code to the form class constructor:
ui->menuPopupMenus->menuAction()->setVisible(false);
All of the above actions (except for the two where we wrote the code) can be executed in Design Mode of Qt Creator. Adding new context menus for new components does not require writing code. Also if necessary different context menus can contain shared QActions.

- 143
- 7
Only thing you can do is set contextMenuPolicy but I doubt that it is what you are looking for.

- 800
- 1
- 7
- 19