Qt: How to add two widgets (say, QPushButton) to the status bar, one to the left and the other to the right?

I would like to add two widgets (say QPushButton ) to the status bar, one to the left and the other to the right.

I am thinking of adding a horizontal spacer between two widgets, but I donโ€™t know how to add it.

PS: I tried using addWidget() to add to the left and addPermanentWidget() to add to the right, but it does not look neat and also it does not feel good.

+6
source share
3 answers

You can add two buttons to the layout in the widget and add the widget to the status bar using QStatusBar::addWidget :

 QWidget * widget = new QWidget(); QPushButton * leftBut = new QPushButton("Left"); QPushButton * rightBut = new QPushButton("Right"); QGridLayout * layout = new QGridLayout(widget); layout->addWidget(leftBut,0,0,1,1,Qt::AlignVCenter | Qt::AlignLeft); layout->addWidget(rightBut,0,1,1,1,Qt::AlignVCenter | Qt::AlignRight); ui->statusBar->addWidget(widget,1); 
+7
source

I am thinking of adding a horizontal spacer between two widgets, but I donโ€™t know how to add it.

Here's a way to use a fake spacer.

 QPushButton *leftButton = new QPushButton("Left"); QPushButton *rightButton = new QPushButton("Right"); QLabel *spacer = new QLabel(); // fake spacer ui->statusBar->addPermanentWidget(leftButton); ui->statusBar->addPermanentWidget(spacer, 1); ui->statusBar->addPermanentWidget(rightButton); 

The second parameter, addPermanentWidget, is used to calculate the appropriate size for this widget when the status bar grows and contracts. "

Demo:

The result is as follows.

+1
source

I think the easiest way is to use QGridLayout (to be honest, I never tried to change the status bar), assuming the status bar is off the widget, you can do this:

 QGridLayout *myGridLayout = new QGridLayout(); statusbar->setLayout(myGridLayout) QPushButton *button1 = new QPushButton(this); myGridLayout->addWidget(button1,0,0,1,1); QPushButton *button2 = new QPushButton(this); myGridLayout->addWidget(button2,X,0,1,1); 

The biggest X more space that you want to leave between them, I would suggest starting with 3, and then doing a few tests to see how it looks.

0
source

Source: https://habr.com/ru/post/975034/


All Articles