Qt5:标准布局管理器 QHBoxLayout / QVBoxLayout / QGridLayout / QFormLayout / 栈布局管理器

QHBoxLayout / QVBoxLayout / QGridLayout:

水平 / 垂直 / 格点 布局

QStackedLayout 栈布局管理器

栈布局可以添加很多窗口,但是在同一时刻,只能有一个窗口可以显示。

1 count:栈布局中的窗口数量,可以使用addWidget() insertWidget()添加窗口。

2 currentIndex:当前的窗口索引。

3 stackingMode:显示模式。

  • StackOne:只有当前的窗口是可见的。
  • StackAll:所有窗口都可见,但只有当前窗口在最上面。

代码实现:

#include "widget.h"
#include "ui_widget.h"
#include <QStackedLayout>
#include <QLabel>
#include <QPushButton>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);

    QPushButton *button = new QPushButton(this);
    QLabel *firstPage= new QLabel(this);
    QLabel *secondPage = new QLabel(this);
    QLabel *thirdPage = new QLabel(this);
    stackedLayout = new QStackedLayout();

    button->setText(QStringLiteral("Switch"));
    firstPage->setText(QStringLiteral("Page 1"));
    secondPage->setText(QStringLiteral("Page 2"));
    thirdPage->setText(QStringLiteral("Page 3"));

    stackedLayout->addWidget(firstPage);
    stackedLayout->addWidget(secondPage);
    stackedLayout->addWidget(thirdPage);

    QVBoxLayout *pLayout = new QVBoxLayout();
    pLayout->addWidget(button, 0, Qt::AlignLeft | Qt::AlignVCenter);
    pLayout->addLayout(stackedLayout);
    pLayout->setSpacing(10);
    pLayout->setContentsMargins(10, 10, 10, 10);
    setLayout(pLayout);

    connect(button, &QPushButton::clicked, this, &Widget::switchPage);

    // 切换页面

}

Widget::~Widget()
{
    delete ui;
}

void Widget::switchPage()
{
    int nCount = stackedLayout->count();
    int nIndex = stackedLayout->currentIndex();

    ++nIndex;

    if (nIndex >= nCount)
        nIndex = 0;

    stackedLayout->setCurrentIndex(nIndex);
}

猜你喜欢

转载自blog.csdn.net/francislucien2017/article/details/85612390