Search code examples
c++qtlayout

How to align children in a QHBoxLayout Left, Center and Right


I have a QHBoxlayout with children set up as follows:

QHBoxlayout h = new QHBoxlayout();

QLLabel leftLabel = new QLLabel("Left");
QLLabel centerLabel = new QLLabel("Center");

QHBoxlayout rightContent = new QHBoxlayout();
QLLabel r1 = new QLLabel("2");
QLLabel r2 = new QLLabel("3");

rightContent.addWidget(r1);
rightContent.addWidget(r2);

h.addWidget(leftLabel);
h.addWidget(centerLabel);
h.addLayout(rightContent);

This will create a QHBoxlayout with all the children floated on the left. I would like leftLabel to be on the left, centerLabel at the center, and rightContent to the extreme right.

How can I achieve this?

Thank you all in advance.

UPDATE

I would like something like left, center, right below:

enter image description here


Solution

  • Just add spacers between "Left", "Center" and "Right":

    QHBoxLayout *h = new QHBoxLayout(&parentWidget);
    h->addWidget(leftLabel);
    h->addStretch()
    h->addWidget(centerLabel);
    h->addStretch()
    h->addLayout(rightLabel);
    

    Might be helpful to practice in Qt Designer.