PDA

View Full Version : Prevent QMenuBar in QMainWindow from shrinking



Radagast
3rd March 2015, 15:02
The problem looks simple, but still I didn't manage to find a solution here or on stackoverflow...
So, I have a plain QMainWindow with QMenuBar (with a few normal menus like File/Edit/Help etc), and that menu bar has a corner widget (in the top-right corner) with a few buttons, i.e.


ui->setupUi(this);
QFrame* frame = new QFrame(0);
QHBoxLayout* hbox = new QHBoxLayout(frame);
hbox->setMargin(0);
QPushButton* btn1 = new QPushButton(frame);
btn1->setText("button 1");
QPushButton* btn2 = new QPushButton(frame);
btn2->setText("button 2");
hbox->addWidget(btn1);
hbox->addWidget(btn2);
menuBar()->setCornerWidget(frame);
The default resizing behaviour of QMainWindow is to allow a user to shrink the menu bar and show an extension button instead of menu items. It is implemented in QMenuBarPrivate::updateGeometries:


if (hiddenActions.count() > 0) {
QMenu *pop = extension->menu();
//and so on

My goal is to prevent a user from shrinking the menu bar at all. I.e. the minimum size of QMainWindow should be equal to menuBar()->sizeHint() that by default includes total widths of all QMenus + width of the corner widget.
For now I managed only to prevent the extension menu:


menuBar()->setMinimumWidth(menuBar()->sizeHint().width());

Now when I shrink MainWindow, QMenus stay visible, but the corner widget gets hidden instead.
In summary, I have 2 questions:
1. what should I add to make the corner widget always visible?
2. is there a more elegant solution (probably using layouts and size policies) than calling a function that relies on a fixed number (setMinimumWidth)? the problem with this solution is that derived classes of my MainWindow will add more stuff to the menu bar, and then its sizeHint will change. Scheduling a timer event with duration=0 just for this is ugly and an overkill IMHO.