I am writing a program with Qt. I have a QMainWindow and a function called createMenus() that returns a QMenuBar*.
Within the class MainWindow : QMainWindow, I call: this->setMenuBar(createMenus());
So I have a beautiful MainWindow with a menu in the top.
Now, in "File", I want to put a button that creates a new window (presumably a QWidget?). And I would like to show the same MenuBar in the top part of my new window.
void MainWindow::createWindow()
{
QWidget* window = new QWidget;
QVBoxLayout* center_box = new QVBoxLayout;
center_box->setContentsMargins(0, 0, 0, 0);
center_box->setSpacing(0);
#ifndef Q_OS_MAC
QMenuBar* newMenu = createMenus();
center_box->setMenuBar(newMenu);
#endif
window->setLayout(center_box);
}
This works (in Linux), as a QMenuBar is shown in the new window. The aftereffect is that the QMenuBar in the MainWindow has disappeared.
Can someone direct me to the best implementation to create multiple windows with the same QMenuBar?
I've looked up your issue and noticed the same behaviour, however you cannot simply copy the existing QMenuBar
of your QMainWindow
.
You could however use a factory method like you did, but you have to assure that you don't return an empty QMenuBar
, otherwise the menu won't show up.
Possible implementation:
QMenuBar* MainWindow::createMenu()
{
QMenuBar *menu = new QMenuBar();
menu->addMenu("Test0");
menu->addMenu("Test1");
menu->addMenu("Test2");
menu->addMenu("Test3");
return menu;
}
And then in your method you can do:
void MainWindow::createWindow()
{
QWidget* window = new QWidget;
QVBoxLayout* center_box = new QVBoxLayout;
#ifndef Q_OS_MAC
center_box->setMenuBar(createMenu());
#endif
window->setLayout(center_box);
window->show();
}
Another way would be to subclass QMenuBar
, which is however more suitable if you want to create a specific kind of implementation or add to the functionality of the already existing class.
custommenubar.h
#ifndef CUSTOMMENUBAR_H
#define CUSTOMMENUBAR_H
#include <QObject>
#include <QMenuBar>
class CustomMenuBar : public QMenuBar
{
Q_OBJECT
public:
explicit CustomMenuBar();
};
#endif // CUSTOMMENUBAR_H
custommenubar.cpp
#include "custommenubar.h"
CustomMenuBar::CustomMenuBar()
{
addMenu("Test");
addMenu("1");
addMenu("2");
addMenu("3");
}
And then in your method:
void MainWindow::createWindow()
{
QWidget* window = new QWidget;
QVBoxLayout* center_box = new QVBoxLayout;
#ifndef Q_OS_MAC
QMenuBar* newMenu = new CustomMenuBar();
center_box->setMenuBar(newMenu);
#endif
window->setLayout(center_box);
window->show();
}
Make sure you take care of cleaning everything up :)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.