user3294
user3294

Reputation: 73

Expanding a Qt Layout : how to put a widget on the right side and the let the other widget to fully fill the left?

I want to put a widget on the right side of a QHBoxLayout, and the other spaces should expand the left side. I've set the widget's SizePolicy to Expanding, but it's not valid. Anyone could offer some help? Thanks.

Code is here:

QHBoxLayout* tmplayout = new QHBoxLayout(this);
tmplayout->setContentsMargins(0, 0, 0, 0);
lineEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Ignored);
tmplayout->addWidget(lineEdit, 0, Qt::AlignRight);
tmplayout->addWidget(pushButton, 0, Qt::AlignRight);

lineEdit should expand.

Upvotes: 7

Views: 13322

Answers (4)

houbysoft
houbysoft

Reputation: 33410

For the widgets you want to be on the left and expand, try to simply add them before the ones on the right, and add a 1 for their stretch factor. For example,

tmplayout->addWidget(exampleWidget, 1);

Then, you could simply add the widgets you want to be on the right side after the ones on the left, using just:

tmplayout->addWidget(lineEdit);
tmplayout->addWidget(pushbutton);

This will automatically give them a stretch factor of 0.

Since the stretch factor of exampleWidget in this example is 1 which is higher than the default 0, exampleWidget will expand; and, since you add it before the others, it will be on the left.

Upvotes: 3

bjoernz
bjoernz

Reputation: 3852

I am not sure if I understand your problem correctly, but maybe you need to look into QSpacerItem. If that is not helpful, maybe you can make a rough mock-up in Qt-Creator and post the screen shots (one example showing approx. what you have, one example showing what you want)

Upvotes: 1

Gerstmann
Gerstmann

Reputation: 5518

Try changing:

tmplayout->addWidget(lineEdit, 0, Qt::AlignRight);
tmplayout->addWidget(pushButton, 0, Qt::AlignRight);

To:

tmplayout->addWidget(lineEdit);
tmplayout->addWidget(pushButton);

When dealing with simple layouts like this, there is no need to specify alignments or stretch factors explicitly.

If you want to force pushButton to specific size, you can use setMinimumSize, setMaximumSize, and setFixedSize

Best regards

Upvotes: 7

Donotalo
Donotalo

Reputation: 13035

Try fixed or minimum size policies. Even you may want to fix the maximum width.

Upvotes: 0

Related Questions