1.概要
2.实验
2.1 实验1 简单实验+跨行
2.1.1 代码
#ifndef WIDGET_H
#define WIDGET_H#include <QWidget>QT_BEGIN_NAMESPACE
namespace Ui {
class Widget;
}
QT_END_NAMESPACEclass Widget : public QWidget
{Q_OBJECTpublic:Widget(QWidget *parent = nullptr);~Widget();private:Ui::Widget *ui;
};
#endif // WIDGET_H
#include "widget.h"
#include "ui_widget.h"
#include <QGridLayout>
#include <QPushButton>Widget::Widget(QWidget *parent): QWidget(parent), ui(new Ui::Widget)
{ui->setupUi(this);// 创建一个QGridLayout对象QGridLayout *layout = new QGridLayout(this);// 创建几个按钮QPushButton *button1 = new QPushButton("Button 1");QPushButton *button2 = new QPushButton("Button 2");QPushButton *button3 = new QPushButton("Button 3");QPushButton *button4 = new QPushButton("Button 4");QPushButton *button5 = new QPushButton("Button 5");QPushButton *button6 = new QPushButton("Button 6");// 将按钮添加到布局中layout->addWidget(button1, 0, 0); // 将button1添加到网格的第0行,第0列layout->addWidget(button2, 0, 1); // 将button2添加到网格的第0行,第1列layout->addWidget(button6, 0, 2); // 将button2添加到网格的第0行,第1列layout->addWidget(button3, 1, 0, 1, 3); // 将button3添加到网格的第1行,跨越第0列到第1列layout->addWidget(button4, 2, 0, 1, 1); // 将button4添加到网格的第2行,第0列layout->addWidget(button5, 2, 1); // 将button4添加到网格的第2行,第0列
}Widget::~Widget()
{delete ui;
}
2.1.2 运行结果
2.2 实验2 一组控件实验
2.2.1 代码
#ifndef GRITLYOUTS_H
#define GRITLYOUTS_H#include <QWidget>namespace Ui {
class GritLyouts;
}class GritLyouts : public QWidget
{Q_OBJECTpublic:explicit GritLyouts(QWidget *parent = nullptr);~GritLyouts();private:Ui::GritLyouts *ui;
};#endif // GRITLYOUTS_H
#include "gritlyouts.h"
#include "ui_gritlyouts.h"
#include <QGridLayout>
#include <QPushButton>GritLyouts::GritLyouts(QWidget *parent): QWidget(parent), ui(new Ui::GritLyouts)
{ui->setupUi(this);// 创建一个QGridLayout对象QGridLayout *layout = new QGridLayout(this);for(int i=0;i<24;i++){QPushButton *button1 = new QPushButton("button_"+QString::number(i)+"");int hang = i/4;int lie = i%4;layout->addWidget(button1, hang, lie);}
}GritLyouts::~GritLyouts()
{delete ui;
}
2.2.2 运行结果
2.3 实验的公共代码
2.3.1 工程
QT += core guigreaterThan(QT_MAJOR_VERSION, 4): QT += widgetsCONFIG += c++17# You can make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0SOURCES += \gritlyouts.cpp \main.cpp \widget.cppHEADERS += \gritlyouts.h \widget.hFORMS += \gritlyouts.ui \widget.ui# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
2.3.2 代码
#include "widget.h"
#include "gritlyouts.h"#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);Widget w;w.show();//GritLyouts gl;//gl.show();return a.exec();
}