下列代码定义了一个窗口,窗口采用竖直布局:一个按钮及一个label。按下按钮时候,窗口扩张,显示label控件。再次按下按钮时,窗口收缩,隐藏label控件。
详细代码如下:
#include <QApplication>
#include <QWidget>
#include <QHBoxLayout>
#include <QTimer>
#include <QLabel>
#include <QVBoxLayout>
#include <QPushButton>
#include <QDebug>
class MyWidget : public QWidget
{
//Q_OBJECT
public:
MyWidget(QWidget* parent = nullptr) : QWidget(parent), m_bD(true)
{
setFixedWidth(100);
// setStyleSheet("background-color:red;");
m_vLayout = new QVBoxLayout();
m_vLayout->setContentsMargins(0, 0, 0, 0);
setLayout(m_vLayout);
m_hLayout = new QHBoxLayout();
m_pushBtn = new QPushButton("d!", this);
m_pushBtn->setFixedSize(20, 20);
m_hLayout->addStretch(1);
m_hLayout->addWidget(m_pushBtn);
m_vLayout->addLayout(m_hLayout);
m_label = new QLabel(this);
m_label->setText("just a label text!");
m_vLayout->addWidget(m_label);
m_vLayout->addStretch(1);
//setFixedHeight(m_pushBtn->height() + m_label->height());
setFixedHeight(m_pushBtn->height());
m_label->hide();
QObject::connect(m_pushBtn, &QPushButton::clicked, [=]() {
if (m_bD)
{
//m_vLayout->addWidget(m_label);
m_label->show();
m_pushBtn->setText("d!");
qDebug() << "push btn h:" << m_pushBtn->height() << ", label h:" << m_label->height();
setFixedHeight(m_pushBtn->height() + m_label->height());
m_bD = false;
}
else
{
m_bD = true;
//m_vLayout->removeWidget(m_label);
m_label->hide();
m_pushBtn->setText("p!");
qDebug() << "push btn h:" << m_pushBtn->height() << ", label h:" << m_label->height();
setFixedHeight(m_pushBtn->height());
}
});
}
private:
QHBoxLayout* m_hLayout;
QPushButton* m_pushBtn;
bool m_bD;
QVBoxLayout* m_vLayout;
QLabel *m_label;
};
int main(int argc, char** argv)
{
QApplication app(argc, argv);
MyWidget w;
w.show();
return app.exec();
}
页面效果如下: