Search code examples
qtqlabelqmainwindowqtoolbar

How to set a center aligned QLabel to toolbar in Qt


I'm new to qt and exploring it .I want to have a text which is center aligned in my Mainwindow's toolbar.Below is my code inside my MainWindow constructor:

QLabel* label=new QLabel("Hello World");
label->setAlignment(Qt::AlignHCenter);

QHBoxLayout *layout = new QHBoxLayout();
layout->addWidget(label);

QWidget* wid = new QWidget;
wid->setLayout(layout);

ui->mainToolBar->addWidget(wid);

The above code displays the text , but not at the center.It displays at the left.What am I missing?Any help will be really helpful.


Solution

  • label->setAlignment(Qt::AlignHCenter);
    

    This tells the label to (horizontally) center the text in itself.

    layout->addWidget(label);
    

    This is expanded by default argument to

    layout->addWidget(label, 0);
    

    Where the 0 is the stretch factor of the label within this layout. Zero means your label will be given as much space as it needs to display properly but nothing more. So your label is just as big as your text needs, has it's text centered, but since it's on a QHBoxLayout it's shown on the left side within your bar. If there are no other widgets in your bar's layout, you can set the stretch-factor to 1 to make the label fill the layout, your text will then show in the center.

    layout->addWidget(label, 1);