1、让对话框大小总是以最合适的大小显示
。。。。
label = new QLabel(QObject::tr("初始文本"));
label->setMaximumWidth(100);
/*自适应大小,可有可无*/
label->adjustSize();
/*自动换行*/
label->setWordWrap(true);
button = new QPushButton(tr("改变文本"));
QHBoxLayout *layout = new QHBoxLayout;
layout->addStretch();
layout->addWidget(button);
QVBoxLayout *mainlayout = new QVBoxLayout;
mainlayout->addWidget(label);
mainlayout->addLayout(layout);
this->setLayout(mainlayout);
/*让对话框大小总是以最合适的大小显示*/
this->layout()->setSizeConstraint(QLayout::SetFixedSize);
connect(button, SIGNAL(released()), this, SLOT(changeText()));
。。。。。
void exerciseDialog::changeText()
{
label->setText(getText());
this->layout()->setSizeConstraint(QLayout::SetFixedSize);
return ;
}
QString getText()
{
static int i = 0;
QString str;
if(i%3 == 0)
str = QObject::tr("好好学习!");
else if(i%3 == 1)
str = QObject::tr("生活是道菜,味道让人爱!");
else
str = QObject::tr("毕竟西湖六月中,风光不与四时同。接天莲叶无穷碧,映日荷花别样红。");
i++;
return str;
}
以上转自:https://blog.csdn.net/qian_f/article/details/8927723
2、QBoxLayout中addStretch 平均分配Layout
函数说明:
void QBoxLayout::addStretch(int stretch = 0)
Adds a stretchable space (a QSpacerItem) with zero minimum size and stretch factor stretch to the end of this box layout.
函数的作用是在布局器中增加一个伸缩量,里面的参数表示QSpacerItem的个数,默认值为零,会将你放在layout中的空间压缩成默认的大小。
例如:一个layout布局器,里面有三个控件,一个放在最左边,一个放在最右边,最后一个放在layout的1/3处,这就可以通过addStretch去实现。
QHBoxLayout *buttonLayout = new QHBoxLayout;
QPushButton *button1;
QPushButton *button2;
QPushButton *button3;
button1 = new QPushButton;
button2 = new QPushButton;
button3 = new QPushButton;
buttonLayout->addStretch(1);
buttonLayout->addWidget(button1);
buttonLayout->addStretch(1);
buttonLayout->addWidget(button2);
buttonLayout->addStretch(1);
buttonLayout->addWidget(button3);
buttonLayout->addStretch(6);
buttonLayout->setContentsMargins(0, 0, 0, 0);
运行结果:
其中四个addStretch()函数用于在button按钮间增加伸缩量,伸缩量的比例为1:1:1:6,意思就是将button以外的空白地方按设定的比例等分为9份并按照设定的顺序放入buttonLayout布局器中。