JaeJun LEE
JaeJun LEE

Reputation: 1334

QGridLayout doesn't work as expected

I'm building gui for my project using Qt5.5 and trying to use QGridLayout.

First source

This code worked as I expected.

QGridLayout * layout = new QGridLayout;
layout->addWidget(lineEdits[0], 0,0,1,1);
layout->addWidget(lineEdits[1], 0,1,1,1);

layout->addWidget(lineEdits[2], 1,0,1,1);
layout->addWidget(lineEdits[3], 1,1,1,2);

layout->addWidget(lineEdits[4], 2,0,1,2);
layout->addWidget(lineEdits[5], 2,2,1,1);
this->setLayout(layout);

Here is the result I got.

First case

Second source

But this code generated broken layout and that was very far from what I expected.

QGridLayout * layout = new QGridLayout;
layout->addWidget(lineEdits[0], 0,0,1,1);
layout->addWidget(lineEdits[1], 0,1,1,2); //this is the only difference

layout->addWidget(lineEdits[2], 1,0,1,1);
layout->addWidget(lineEdits[3], 1,1,1,2);

layout->addWidget(lineEdits[4], 2,0,1,2);
layout->addWidget(lineEdits[5], 2,2,1,1);
this->setLayout(layout);

enter image description here

I have no idea about how to fix this.

I would appreciate for your suggestions in advance.

Upvotes: 1

Views: 442

Answers (1)

Mat
Mat

Reputation: 206679

The problem is that there's nothing that gives the middle column any significant width - it's there but the only thing that makes it visible is the inter-column spacing, which is why the last row doesn't align with the other two.

One way to fix this is to set the column stretch factors. For example, try this (same factor for all columns, the actual number doesn't matter, only the proportion does):

//...
layout->addWidget(lineEdits[5], 2, 2, 1, 1);
for (int i=0; i<3; ++i)
  layout->setColumnStretch(i, 1);
this->setLayout(layout);

This gives me the following layout:

enter image description here

Another option is to force one of the multi-column widgets' widths explicitly, but better avoid that if you can.

Upvotes: 2

Related Questions