QT佈局

關於佈局,佈局能夠採用絕對定位和佈局定位,絕對定位就是直接給出座標值,可是若是用戶改變了窗口大小,好比最大化,若是你本身不作處理,那麼窗口上面的這些控件仍是在原來位置,並不能隨着窗口變化而變化。
QT提供了佈局管理器,能夠避免這種問題出現,經常使用的有水平佈局,垂直佈局,網格佈局
app

在佈局管理器中使用addWidget添加一個控件,使用addLayout添加一個子佈局
佈局

1.水平佈局
spa

#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();
get

}io

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();
gc

}方法


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();
im

}layout


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用於指定它佔了多行和佔了多少列。

img

相關文章
相關標籤/搜索