Qt World Summit: Submit your Presentation

Center a QLabel in a Qwidget

  • I want to do like a toolbar, 3 buttons on the left and a label in the middle of the screen, no matter the size of my app.

    I tried to do this with QToolBar but can't add a QLabel, so I'm trying with a QWidget.

    My QWidget has Horizontal Layout, and I added 3 QPushButton and a QLabel.

    How can I center the QLabel to always stay in the middle?

    Screen Shot 2020-04-02 at 17.26.42.png

    Screen Shot 2020-04-02 at 17.25.48.png

    I have tried different things, like putting the three buttons in a widget and the label in another widget and play with the layouts and size constrains but I haven't achieved it

  • Lifetime Qt Champion


    Out of curiosity, why not use the toolbar feature of QMainWindow for that ?

  • I tried but I couldn't add a label. Is that possible?

  • Well, I saw that I could do something like

    ui->mainToolBar->addWidget(new QLabel("MY LABEL"));,

    But have the same problem of centering the label

  • Okay! I research a little bit more and found what I was looking for. Example code:

        QLabel* label = new QLabel("MY LABEL");
        QHBoxLayout* layout = new QHBoxLayout();
        layout->addWidget(label, Qt::AlignCenter);
        QWidget* wid = new QWidget;
        wid->setContentsMargins(0, 0, 0, 0);
        wid->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
        QToolButton* p_butt_1 = new QToolButton;
        QToolButton* p_butt_2 = new QToolButton;
        QToolButton* p_butt_3 = new QToolButton;
        setStyleSheet("QToolButton { border: 1px solid magenta; }"); // Just for visibility in this example
        label->setStyleSheet("border: 1px solid blue;"
                            "background-color: yellow;");

Log in to reply