Adding menus in main class derived from QWidget

2019-08-02 18:13发布

问题:

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