简体   繁体   English

QGridLayout不能按预期工作

[英]QGridLayout doesn't work as expected

I'm building gui for my project using Qt5.5 and trying to use QGridLayout. 我正在使用Qt5.5为我的项目构建gui,并尝试使用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. 这是我得到的结果。

第一种情况

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);

在此处输入图片说明

I have no idea about how to fix this. 我不知道如何解决这个问题。

I would appreciate for your suggestions in advance. 提前感谢您的建议。

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: 这给了我以下布局:

在此处输入图片说明

Another option is to force one of the multi-column widgets' widths explicitly, but better avoid that if you can. 另一种选择是显式强制使用多列窗口小部件的宽度,但如果可以的话,最好避免这种情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM