kevinarpe
kevinarpe

Reputation: 21319

How to align two widgets in a QHBoxLayout where one is aligned far left, and one is aligned far right?

I want to have a QHBoxLayout where one QLabel is on the far left, the one QLabel is on the far right.

My Google-fu fails me. :( I cannot find the solution.

Here is a screenshot of the QHBoxLayout with two QLabel widgets:

enter image description here

Whatever I try, I cannot get the second QLabel widget aligned on the far right.

Roughly speaking, I tried something like this:

QHBoxLayout* const hboxLayout = new QHBoxLayout{};
hboxLayout->addWidget(m_leftLabel, 1);
hboxLayout->addStretch(1);
hboxLayout->addWidget(m_rightLabel, 0, Qt::AlignmentFlag::AlignRight);

I tried various large stretch values for the first addWidget() call and addStretch().

I also tried:

m_rightLabel->setAlignment(Qt::AlignmentFlag::AlignRight)

None of these solutions works. I am sure the solution is very simple ( ! ), but I cannot find it.

How can I do this?

Upvotes: 2

Views: 1128

Answers (1)

eyllanesc
eyllanesc

Reputation: 244282

My solution is to set a stretch in the middle:

#include <QtWidgets>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QWidget w;
    QHBoxLayout *lay = new QHBoxLayout(&w);
    lay->addWidget(new QLabel("Left"));
    lay->addStretch();
    lay->addWidget(new QLabel("Right"));
    w.show();
    return a.exec();
}

enter image description here

Upvotes: 4

Related Questions