QSpacerItem在布局中的用法示例

          需要实现的部件显示效果如下:

QSpacerItem在布局中的用法示例_第1张图片    QSpacerItem在布局中的用法示例_第2张图片

        构建方法如上右图,实现代码:

#include <QApplication>
#include <QWidget>
#include <QPushButton>
#include <QBoxLayout>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

        QWidget w;

        QPushButton btn1("btn1", &w);
        QPushButton btn2("btn2", &w);
        QPushButton btn3("btn3", &w);
        QPushButton btn4("btn4", &w);
        QPushButton btn5("btn5", &w);

        btn1.setFixedSize(60, 60); //大
        btn2.setFixedSize(40, 40); //小
        btn3.setFixedSize(40, 40);
        btn4.setFixedSize(40, 40);
        btn5.setFixedSize(40, 40);

        /*
        首先把vLayout1 : vSpacer1 btn1看成纵一组
        再把vLayout2 : vSpacer2 hLayout1(btn2btn3btn4btn5) vSpacer3看成纵一组(先把btn2btn3btn4btn5看成一横组)
        最后把hLayout : vLayout1 vLayout2 hSpacer1看成横一组
        */
        QHBoxLayout* hLayout = new QHBoxLayout();
        QVBoxLayout* vLayout1 = new QVBoxLayout();
        QHBoxLayout* hLayout1 = new QHBoxLayout();
        QVBoxLayout* vLayout2 = new QVBoxLayout();
        QSpacerItem* vSpacer1 = new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding);
        QSpacerItem* vSpacer2 = new QSpacerItem(20, 20, QSizePolicy::Minimum, QSizePolicy::Expanding);
        QSpacerItem* vSpacer3 = new QSpacerItem(20, 5, QSizePolicy::Minimum, QSizePolicy::Fixed);
        QSpacerItem* hSpacer1 = new QSpacerItem(20, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);

        //vLayout1 : vSpacer1 btn1
        vLayout1->addSpacerItem(vSpacer1);
        vLayout1->addWidget(&btn1);

        //hLayout1 : btn2btn3btn4btn5
        hLayout1->addWidget(&btn2);
        hLayout1->addWidget(&btn3);
        hLayout1->addWidget(&btn4);
        hLayout1->addWidget(&btn5);

        //vLayout2 : vSpacer2 hLayout1(btn2btn3btn4btn5) vSpacer3
        vLayout2->addSpacerItem(vSpacer2);
        vLayout2->addLayout(hLayout1);
        vLayout2->addSpacerItem(vSpacer3);

        //hLayout : vLayout1 vLayout2 hSpacer1
        hLayout->setSpacing(3);
        hLayout->addLayout(vLayout1);
        hLayout->addLayout(vLayout2);
        hLayout->addSpacerItem(hSpacer1);

        hLayout->setContentsMargins(0, 0, 0, 0);

        w.setLayout(hLayout);

        //w.setLayoutDirection(Qt::RightToLeft);

        w.show();

        return a.exec();
}

你可能感兴趣的:(QSpacerItem在布局中的用法示例)