QHBoxLayout的宽度不正确

时间:2019-02-20 16:38:21

标签: qt

你好:)这是我的代码(加上我在注释中尝试过的内容)。 “ this”是从QWidget派生的类,“ this”没有大小,因为我想根据孩子的大小来适应它(因此在“ paintEvent”中,我称为“ adjustSize()”):

QPushButton *button1 = new QPushButton("Hello and good morning");
QPushButton *button2 = new QPushButton("World");

QHBoxLayout *h1 = new QHBoxLayout(this);
QHBoxLayout *h2 = new QHBoxLayout(this);
QVBoxLayout *v = new QVBoxLayout(this);

h1->addWidget(button1);
h2->addWidget(button2);
//h2->setSizeConstraint(QLayout::SetMaximumSize);
//h2->setSizeConstraint(QLayout::SetDefaultConstraint);
//h2->setSizeConstraint(QLayout::SetFixedSize);
//h2->setSizeConstraint(QLayout::SetMinAndMaxSize);

v->addLayout(h1);
v->addLayout(h2);
//v->setSizeConstraint(QLayout::SetDefaultConstraint);
//v->setSizeConstraint(QLayout::SetFixedSize);
//v->setSizeConstraint(QLayout::SetMaximumSize);
//v->setSizeConstraint(QLayout::SetMinAndMaxSize);
//v->setSizeConstraint(QLayout::SetMinimumSize);
//v->setSizeConstraint(QLayout::SetNoConstraint);

QSize s1 = h1->sizeHint();
QSize s2 = h2->sizeHint();

QSize s3 = h1->totalSizeHint();
QSize s4 = h2->totalSizeHint();

QSize s5 = h1->totalMaximumSize();
QSize s6 = h2->totalMaximumSize();

QSize s7 = h1->totalMinimumSize();
QSize s8 = h2->totalMinimumSize();
setLayout(v);
show();

我得到这个结果:只有button1是可见的。当我在“ setLayout(v)”处设置断点时,我看到h2的每个QSize的大小都为(0,0)。

我的问题是:如何看到button2(当然还有button1))?我不想设置最小/最大大小,因为按钮必须适合其文本。

祝你有美好的一天!

1 个答案:

答案 0 :(得分:2)

布局直接设置为在布局的构造函数中作为参数传递的小部件。但是,一个小部件只能同时具有一个布局。

删除this参数,它应该可以工作。

QHBoxLayout *h1 = new QHBoxLayout();
QHBoxLayout *h2 = new QHBoxLayout();
QVBoxLayout *v = new QVBoxLayout();