Qt add menuBar, menus, and sub menus to QMainWindow
15,320
Solution 1
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();
}
Solution 2
Each QMainWindow
should have a central widget:
QMainWindow *w = new QMainWindow;
QWidget* centralWidget = new QWidget;
w->setCentralWidget( centralWidget );
centralWidget->setLayout(L);
w->show();

Author by
Joseph Ali
.I always end up doing silly mistakes .I Did many medium difficulty programs ! . looking forward to be excellent programmer. . I'm very good at medium difficulty programs in java and PHP. . languages which i can speak c,c++,java,PHP,swift,javaScript. . i use blender 3d designing tool :: insta =} josephali
Updated on June 26, 2022Comments
-
Joseph Ali 4 months
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(); }