QT布局

关于布局,布局可以采用绝对定位和布局定位,绝对定位就是直接给出坐标值,但是如果用户改变了窗口大小,比如最大化,如果你自己不做处理,那么窗口上面的这些控件还是在原来位置,并不能随着窗口变化而变化。
QT提供了布局管理器,可以避免这种问题出现,常用的有水平布局,垂直布局,网格布局

在布局管理器中使用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用于指定它占了多行和占了多少列。

posted @ 2011-11-21 15:38  移动应用开发  阅读(316)  评论(0编辑  收藏  举报