6

I have created a menu bar and some menus with Qt creator. One of the menus had to be coded to use QActionGroup features. Now it is easy to add my custom menu to the menu bar with:

printMenu = menuBar()->addMenu(tr("&Print"));

but my menu will be in the last position of the menu bar. How do I add my menu at a specified place? (e.g. the second place right after the File menu)

Greetings

ollo
  • 24,797
  • 14
  • 106
  • 155
Linoliumz
  • 2,381
  • 3
  • 28
  • 35

2 Answers2

11

Use QMenuBar::insertMenu in conjunction with QMenu::menuAction.

For example, if you want to dynamically insert the "Print" menu at the location before the "Help" menu, you can do something like this:

QMenu *printMenu = new QMenu(tr("&Print"));
menuBar()->insertMenu(ui->menuHelp->menuAction(), printMenu);
Dan Moulding
  • 211,373
  • 23
  • 97
  • 98
mtvec
  • 17,846
  • 5
  • 52
  • 83
  • 1
    The usage of `new` caused some trouble: The menu was added, but *not* added to the child-list. Replacing `new` with `menuBar()->addMenu("whatever name")` did the trick (`QMenu *printMenu = menuBar()->addMenu(tr("&Print"))`). The menu is created correctly through the menubar and placed at the position of line 2 (if `insertMenu()` is not called, it's placed at the end). – ollo Feb 03 '14 at 18:41
2

If you want to add a sub menu in the middle of the menubar, this is not trivial. There is no direct API to do this but you can probably pull that out byt manipulating the internal actions of QWidget (QMenu::addMenu just calls QWidget::addAction(menu->menuAction()).

In theory, you can manipulate QMenuBar::actions(), but I never did it.

When I had to do handle this problem, I just reconstructed the menu from another dataset (look in your favorite search engine for qmdilib and you will see my solution).

elcuco
  • 8,948
  • 9
  • 47
  • 69