PDA

View Full Version : Add QMenuBar to new windows



LucaDanieli
21st January 2017, 17:37
Hello,

I am writing a program.
I have a QMainWindow and a function called createMenus() that returns a QMenuBar*.

Within the class 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 QMainWindow::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 QMainWindow has disappeared.

Can someone direct me to the best implementation to create multiple windows with the same QMenuBar?

Kind regards,
Luca

anda_skoa
22nd January 2017, 10:14
If you need to have a menu bar in the second window, just use QMainWindow instead of QWidget.

Cheers,
_

d_stranz
22nd January 2017, 22:53
There isn't anything in the code you have posted that would result in the QMainWindow's menu bar "disappearing". And there isn't anything in the code that would cause the QWidget "window" to become visible, because you don't give it a parent when you create it, nor do you call its show() method. Perhaps there is something happening in the createMenus() method that would result in this side effect.

QMainWindow already has a QMainWindow::menuBar() method, which creates and returns a menu bar for you to populate with menu items. Calling QMainWindow::setMenuBar() replaces this built-in menubar with your own.

If your createMenus() method is actually retrieving the QMainWindow menubar through a call to QMainWindow::menuBar() and returning that instance, then putting that instance into another widget as its menu bar will of course remove it from the original parent (QMainWindow). The same widget instance cannot be shared among more than one parent widget. In other words, if you're doing this:



QMenuBar * MainWindow::createMenus()
{
QMenuBar * pMB = menuBar();

// add menus to pMB

return pMB;
}


then this would cause the "disappearing menu" effect you see when you add that menubar to a different widget.