QT简单设计 网格布局 QT5.12.3环境 C++实现
根据设计实现布局。
代码:
widget.cpp
#include "widget.h"
#include "ui_widget.h"
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
this->resize(400,400); // 设置页面大小
QPushButton *b1 = new QPushButton;
b1->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred);
b1->setStyleSheet("background-color:yellow");
QPushButton *b2 = new QPushButton;
b2->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred);
b2->setStyleSheet("background-color:orange");
QPushButton *b3 = new QPushButton;
b3->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred);
b3->setStyleSheet("background-color:pink");
QPushButton *b4 = new QPushButton;
b4->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred);
b4->setStyleSheet("background-color:lightgreen");
QPushButton *b5 = new QPushButton;
b5->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred);
b5->setStyleSheet("background-color:darkgreen");
QPushButton *b6 = new QPushButton;
b6->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Preferred);
b6->setStyleSheet("background-color:blue");
QGridLayout *layout = new QGridLayout(this); // 设置网格布局
this->setLayout(layout); // 将布局添加到页面
layout->addWidget(b1,0,0,2,2);
layout->addWidget(b2,0,2,1,2);
layout->addWidget(b3,2,0,1,2);
layout->addWidget(b4,1,2,2,1);
layout->addWidget(b5,1,3,3,1);
layout->addWidget(b6,3,0,1,3);
layout->setMargin(0); // 设置边距
layout->setSpacing(0); // 设置各部件间距
}
Widget::~Widget()
{
delete ui;
}
输出: