Home > database >  How do you access the menus given a QMenuBar?
How do you access the menus given a QMenuBar?

Time:04-04

In Qt how do you recover the menus given a populated QMenuBar?

They do not seem to be the menu bar's children. For example, after the following (where the menu creation functions succeed and do what you expect)

menuBar()->addMenu(create_file_menu(this));
menuBar()->addMenu(create_view_menu(this));
auto children = menuBar()->children();
auto first_child = children[0];

children ends up with a size of 1 and that one child, first_child, is some object of type QMenuBarExtension. I was expecting to get two children with the first being the file menu.

I'm using Qt6 if that matters.

CodePudding user response:

A QMenu is added to a QMenuBar internaly via QWidget::addAction(menu->menuAction()) (see <QtInstallPath/src\widgets\widgets\qmenubar.cpp>. From QWidget you can retrieve the added QActions via QWidget::actions() - method which returns a list of associated QActions. In your specific example menuBar()->actions() should retrieve at least two actions for your menus.

However, there seems to be no way to get from a QMenu::menuAction() - created QAction back to the associated menu. Therefore you may need to store a pointer to your created QMenu - objects on your own.

  •  Tags:  
  • c qt
  • Related