c++qtqt5qmainwindowqmenubar

Qt add menuBar, menus, and sub menus to QMainWindow


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();
}

Solution

  • add layout to central widget:

    #include <QApplication>
    
    #include <QApplication>
    #include<QSlider>
    #include<QSpinBox>
    #include<QHBoxLayout>
    #include<QWidget>
    
    #include<QMenuBar>
    #include<QStatusBar>
    #include <QMainWindow>
    
    int main(int argc, char *argv[])
    {
    
        QApplication a(argc, argv);
    
        QMainWindow *w = new QMainWindow;
    
        QMenuBar *menu = new QMenuBar;
        QMenu *file = new QMenu();
        file->addMenu("&File");
        menu->addMenu(file);
    
        QWidget *centralwidget = new QWidget(w);
        w->setCentralWidget(centralwidget);
    
        QSlider *s1 = new QSlider(Qt::Horizontal, centralwidget);
        QSlider *s2 = new QSlider(Qt::Vertical, centralwidget);
        QSpinBox *sb = new QSpinBox;
    
    
        QHBoxLayout *L = new QHBoxLayout(centralwidget);
        L->addWidget(s1);
        L->addWidget(s2);
        L->addWidget(sb);
        w->show();
    
        return a.exec();
    }
    

    enter image description here