Qt add menuBar, menus, and sub menus to QMainWindow

Joseph Ali picture Joseph Ali · Dec 28, 2016 · Viewed 13.2k times · Source

I have a hard time adding menu Bar, menus and sub menus to Qt QMainWindow programmatically.

The following code produces an error:

QWidget::setLayout: Attempting to set QLayout "" on QMainWindow "", which already has a layout

Notes : *.The main window come out without any menu or Layout (Empty!)

#include <QApplication>

#include <QApplication>
#include<QSlider>
#include<QSpinBox>
#include<QHBoxLayout>
#include<QWidget>

#include "mainwindow.h"
#include<QMenuBar>
#include<QStatusBar>

int main(int argc, char *argv[])
{

    QApplication a(argc, argv);

    QMenuBar *menu = new QMenuBar;
            QMenu *file = new QMenu();
            file->addMenu("&File");
            menu->addMenu(file);

            QSlider *s1 = new QSlider(Qt::Horizontal);
               QSlider *s2 = new QSlider(Qt::Vertical);
               QSpinBox *sb = new QSpinBox;


               QHBoxLayout *L = new QHBoxLayout;
                L->addWidget(s1);
                L->addWidget(s2);
                L->addWidget(sb);




     QMainWindow *w = new QMainWindow;
     w->setLayout(L);
     w->show();

    return a.exec();
}

Answer

Vladimir Bershov picture Vladimir Bershov · Dec 28, 2016

Each QMainWindow should have a central widget:

QMainWindow *w = new QMainWindow;

QWidget* centralWidget = new QWidget;
w->setCentralWidget( centralWidget );

centralWidget->setLayout(L);
w->show();