Aligning QMenuBar items (add some on left and some on right side)
Asked Answered
A

2

6

Currently I have QMenuBar with three QActions and it looks like this:

enter image description here

but I would like to get this (get some QActions right-aligned):

enter image description here

Is there a way to do this?

Absa answered 4/1, 2012 at 12:11 Comment(0)
S
1

Well one possible solution is here. But it involves implementing your own style (QStyle as I recall). However here is a snippet that I have just tried on mainwindow class:

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)  {  

ui->setupUi(this);

QMenuBar *barLeft = new QMenuBar; 
QMenuBar *barRight = new QMenuBar;

barLeft->addAction("Foo Left 1");
barLeft->addAction("Foo Left 2");
barRight->addAction("Foo Left 1");
barRight->addAction("Foo Left 2");

QHBoxLayout *mainMenuLayout = new QHBoxLayout;

mainMenuLayout->addWidget(barLeft);
mainMenuLayout->addWidget(barRight);

mainMenuLayout->setAlignment(barLeft, Qt::AlignLeft);
mainMenuLayout->setAlignment(barRight, Qt::AlignRight);

QWidget *central = new QWidget;
central->setLayout(mainMenuLayout);

setCentralWidget(central);

}

This should be suitable.

Steward answered 4/1, 2012 at 12:35 Comment(0)
N
20

Probably the most simple solution to this particular problem is to use the corner widget. It can be used to place almost anything at the rightmost position, of course also a new menu bar:

QMenuBar *bar = new QMenuBar(ui->menuBar);

QMenu *menu = new QMenu("Test menu", bar);
bar->addMenu(menu);

QAction *action = new QAction("Test action", bar);
bar->addAction(action);

ui->menuBar->setCornerWidget(bar);

Result:

Standard QMenuBar with additional rightmost 2nd QMenuBar

This is esp. helpful when the main menu is still to be edited in QDesigner...

Newman answered 17/6, 2014 at 16:54 Comment(1)
This is a better answer than the chosen answer imo.Driggers
S
1

Well one possible solution is here. But it involves implementing your own style (QStyle as I recall). However here is a snippet that I have just tried on mainwindow class:

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)  {  

ui->setupUi(this);

QMenuBar *barLeft = new QMenuBar; 
QMenuBar *barRight = new QMenuBar;

barLeft->addAction("Foo Left 1");
barLeft->addAction("Foo Left 2");
barRight->addAction("Foo Left 1");
barRight->addAction("Foo Left 2");

QHBoxLayout *mainMenuLayout = new QHBoxLayout;

mainMenuLayout->addWidget(barLeft);
mainMenuLayout->addWidget(barRight);

mainMenuLayout->setAlignment(barLeft, Qt::AlignLeft);
mainMenuLayout->setAlignment(barRight, Qt::AlignRight);

QWidget *central = new QWidget;
central->setLayout(mainMenuLayout);

setCentralWidget(central);

}

This should be suitable.

Steward answered 4/1, 2012 at 12:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.