简体   繁体   中英

Adding menus in main class derived from QWidget

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.

这是用setMenuBar添加的菜单

这是添加了menuBar()的菜单

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM