开发者

Dynamic QT4 Menu in C++

I am using C++ and QT4 on Linux. I wish to add items to the menubar at runtime. My main GUI containing the menubar was designed with QT Designer and setup in the first line of code below.

In my main window constructor I have the following test code and it compiles fine. However, the new submenu bar and its item do not appear when the program is executed. I'm guessing Qt needs to be told to update the menubar somehow. An开发者_如何转开发y ideas?

 // Setup the user interface
 m_ui.setupUi(this);

 QMenu * iObjectsMenu = new QMenu(tr("Objects"), m_ui.menubar); //m_ui.menubar.menu_View->addMenu(tr("Objectz"));
 QAction * menu_testAction = new QAction(tr("Test"), m_ui.menubar);
 iObjectsMenu->addAction(menu_testAction);


The way you're doing it, you need to put the menu somewhere and you haven't done so.

I do it a little differently. When you make menus in the designer they have pointers in the ui member. You can then manipulate that menu quite easily.

For example, I wanted a menu that contains all the toolbars and dock windows that can be shown/hidden. I looked at the code that makes QMainWindow::createPopup() and made my own external function construct_view_menu(QMainWindow * parent, QMenu * view_menu). It's called during the main window initialization with construct_view_menu(this, ui.menu_View). Function just appends more menus and actions to that menu. The menu_View is just an empty menu I created with the designer.

I found this the easiest way to go about it, but you can also create new menus and then append or insert them into the menubar; it's this latter step you've neglected.


I would just generate the menu in your setup code rather than the ui, keep a member variable that points to the QMenu (allocated with new)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜