QMenuBar not displaying
-
I am trying to create a simple QMenuBar with one QMenu.
mainwindow.h file:
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include <QMenuBar> #include <QMenu> class MainWindow : public QMainWindow { // Macros Q_OBJECT // Constructors public: MainWindow(QWidget *parent = nullptr); // Destructors public: ~MainWindow(); // QWidgets private: QWidget *QWidget_CenteralWidget; QMenuBar *QMenuBar_Bar; QMenu *QMenu_File; // Methods private: void setupGUI(); }; #endif
mainwindow.cpp file:
#include "mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) { setupGUI(); } MainWindow::~MainWindow() { }
mainwindow_gui.cpp file:
#include "mainwindow.h" void MainWindow::setupGUI() { // MainWindow if (this->objectName().isEmpty()) { this->setObjectName(QString::fromUtf8("QMainWindow_MainWindow")); } this->setWindowState(Qt::WindowMaximized); // Centeral Widget QWidget_CenteralWidget = new QWidget(this); QWidget_CenteralWidget->setStyleSheet("background-color: gray;"); this->setCentralWidget(QWidget_CenteralWidget); // QMenuBar QMenuBar_Bar = new QMenuBar(this); QMenuBar_Bar->setVisible(true); QMenuBar_Bar->setStyleSheet("background-color: red;"); QMenu_File = new QMenu(QMenuBar_Bar); QMenu_File->setObjectName( QString::fromUtf8("QMenu_File") ); QMenuBar_Bar->addMenu(QMenu_File); this->setMenuBar(QMenuBar_Bar); }
Here is the output:
As you can see, the menu bar is nowhere to be found.
Why is this happening?
-
Your menu has no text, so it occupies no space. Give it something to show e.g.
QMenu_File = new QMenu("&File", QMenuBar_Bar); QMenuBar_Bar->addMenu(QMenu_File);
or a shorthand:
QMenu_File = QMenuBar_Bar->addMenu("&File");
Btw.
setObjectName
has an overload that takes QAnyStringView, so you can use it and save on dynamically allocating temporary QString:setObjectName("QMainWindow_MainWindow")
.Btw.2 Calling
this->setWindowState(Qt::WindowMaximized);
or any other variant ofshow()
in the constructor is a bad practice. A widget should not dictate how it is shown. This should be the responsibility of the code that creates it. It would also make callingQMenuBar_Bar->setVisible(true);
unnecessary, as it would be shown automatically when the parent is shown. -
@Chris-Kawa Thank you for your solutions and suggestions. I made sure to use the overload and to change my code to use the following in the appropriate place:
this->setWindowState(Qt::WindowMaximized);
Thank you again.