继承 Qt笔记1,接下来是界面布局
QVBoxLayout 竖直布局
引入头文件:QVBoxLayout
定义一个竖直布局:QVBoxLayout* vBoxLayout = new QVBoxLayout();
添加布局到窗口:vBoxLayout->addWidget(widgetName);
但是,按以上操作进行布局之后,你会发现窗口没有任何变化。
因为我们还需要定义一个中心部件。这个部件将会占据整个窗口。
定义中心部件:QWidget* centralWidget = new QWidget(this);
设置中心部件:setCentralWidget(centralWidget)
设置布局: centralWidget->setLayout(vBoxLayout);
水平布局(QHBoxLayout
)同理,这里不多解释。
示例代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| #include "mainwindow.h" #include "./ui_mainwindow.h"
#include <QPushButton> #include <QVBoxLayout> #include <QMessageBox>
MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent) , ui(new Ui::MainWindow) { ui->setupUi(this);
QWidget* centralWidget = new QWidget(this); setCentralWidget(centralWidget);
QVBoxLayout* vBoxLayout = new QVBoxLayout(); QPushButton* button = new QPushButton("01", this); QPushButton* button2 = new QPushButton("02", this); button->setFixedSize(100, 100); button2->setFixedSize(100, 100);
button->setStyleSheet("color: yellow;" "background-color: lightblue;" "font-size: 30px;"); button->setFlat(false);
connect(button, &QPushButton::clicked, []{ QMessageBox::information(nullptr, "Title", "You clicked Button!"); });
vBoxLayout->addWidget(button); vBoxLayout->addWidget(button2);
centralWidget->setLayout(vBoxLayout); }
MainWindow::~MainWindow() { delete ui; }
|