Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

layout

qt

qt4

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.

like image 561
user3294 Avatar asked Jun 23 '11 08:06

user3294


2 Answers

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

like image 135
Gerstmann Avatar answered Oct 07 '22 01:10

Gerstmann


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.

like image 40
houbysoft Avatar answered Oct 07 '22 00:10

houbysoft