Adding menus in main class derived from QWidget

*爱你&永不变心* 提交于 2019-12-11 04:43:12

问题


I'm trying to create a program in Qt that contains menus. The main class is derived from QWidget, and I know I could use QMainWindow to use the function menuBar(), but I can't use layouts in QMainWindow. I tried to add a QMenuBar at the window's layout using setMenuBar, but it does not display like using menuBar() and I don't know how to make it a drop-down menu.


回答1:


QVBoxLayout *boxLayout = new QVBoxLayout(this); // Main layout of widget

QMenuBar* menuBar = new QMenuBar();
QMenu *fileMenu = new QMenu("File");
menuBar->addMenu(fileMenu);
fileMenu->addAction("Save");
fileMenu->addAction("Exit");

this->layout()->setMenuBar(menuBar);

In above code i had used menu bar of widget layout.




回答2:


You can use layouts in a QMainWindow. You need to provide a central widget. Within this widget, you can use a layout like you would in a stand-alone QWidget.

If you don't need the other stuff provided by QMainWindow (status and tool bars), you can add a menu by just creating a QMenuBar and placing it at the top of a suitable layout, then adding a QMenu to it. But I don't know if this works for window managers putting the menu bar outside the window, like OS X and Unity in Ubuntu do.

So QMainWindow should be the way to go. Try adding your layout to the centralWidget(), not to the main window itself.




回答3:


You need create a QMenuBar object and add it to your layout. Then call addMenu function to add menus to your menubar. After adding menus, you can call addAction function to add menu items and connect its triggered signal to handle user clicks.

I found a detailed tutorial which explains how to do this: Qt QWidget add menu bar



来源:https://stackoverflow.com/questions/10684776/adding-menus-in-main-class-derived-from-qwidget

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!