Mohammad Sheykholeslam
Mohammad Sheykholeslam

Reputation: 1437

Context Menu Creation with ‪ Qt Designer(Qt Creator IDE)

How can i create a Context menu in Qt Designer (1.3)? Certainly I want to create it with out writing one line code!!

Upvotes: 15

Views: 12653

Answers (3)

Dmitro25
Dmitro25

Reputation: 173

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 to myContextMenuHandler(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.

Upvotes: 1

Jose F. Velez
Jose F. Velez

Reputation: 529

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 value ActionsContextMenu.

  • 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);

Upvotes: 23

delor
delor

Reputation: 800

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

Upvotes: 0

Related Questions