在布局管理器中使用addWidget添加一个控件,使用addLayout添加一个子布局
1.水平布局
#include <QApplication> #include <QPushButton> #include <QHBoxLayout> int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget *window = new QWidget; QPushButton *button1 = new QPushButton("One"); QPushButton *button2 = new QPushButton("Two"); QPushButton *button3 = new QPushButton("Three"); QPushButton *button4 = new QPushButton("Four"); QPushButton *button5 = new QPushButton("Five"); QHBoxLayout *layout = new QHBoxLayout; layout->addWidget(button1); layout->addWidget(button2); layout->addWidget(button3); layout->addWidget(button4); layout->addWidget(button5); window->setLayout(layout); window->show(); return app.exec();}
2.垂直布局 #include <QApplication> #include <QPushButton> #include <QHBoxLayout> #include <QVBoxLayout> int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget *window = new QWidget; QPushButton *button1 = new QPushButton("One"); QPushButton *button2 = new QPushButton("Two"); QPushButton *button3 = new QPushButton("Three"); QPushButton *button4 = new QPushButton("Four"); QPushButton *button5 = new QPushButton("Five"); QVBoxLayout *layout = new QVBoxLayout; layout->addWidget(button1); layout->addWidget(button2); layout->addWidget(button3); layout->addWidget(button4); layout->addWidget(button5); window->setLayout(layout); window->show(); return app.exec();}
3.网格布局 QGridLayout #include <QApplication> #include <QPushButton> #include <QGridLayout> int main(int argc, char *argv[]) { QApplication app(argc, argv); QWidget *window = new QWidget; QPushButton *button1 = new QPushButton("One"); QPushButton *button2 = new QPushButton("Two"); QPushButton *button3 = new QPushButton("Three"); QPushButton *button4 = new QPushButton("Four"); QPushButton *button5 = new QPushButton("Five"); QPushButton *button6 = new QPushButton("Six"); QGridLayout *layout = new QGridLayout; layout->addWidget(button1, 0 ,0); layout->addWidget(button2, 0, 1); layout->addWidget(button3, 1, 0); layout->addWidget(button4, 1, 1); layout->addWidget(button5, 2, 0); layout->addWidget(button6, 2, 1); window->setLayout(layout); window->show(); return app.exec();
}
QGridLayout的addWidget有两种重载方法 void addWidget(QWidget *widget, int row, int column) row和colume用于指定它的行和列 void addWidget(QWidget *widget, int fromRow, int fromColumn, int rowSpan, int columnSpan) fromRow和fromColumn开始行和列,rowSpan和columeSpan用于指定它占了多行和占了多少列。