QStackedWidget类实现堆栈窗体

128 篇文章 0 订阅
#-------------------------------------------------
#
# Project created by QtCreator 2018-09-26T19:54:31
#
#-------------------------------------------------

QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = StackedWidget
TEMPLATE = app


SOURCES += main.cpp\
        stackdlg.cpp

HEADERS  += stackdlg.h

QMAKE_CXXFLAGS += -std=c++11
#ifndef STACKDLG_H
#define STACKDLG_H

#include <QDialog>

class QListWidget;
class QStackedWidget;
class QLabel;
class QHBoxLayout;

class StackDlg : public QDialog
{
    Q_OBJECT

public:
    StackDlg(QWidget *parent = 0);
    ~StackDlg();

private:
    inline void CreateQListWidget();
    inline void CreateQLabels();
    inline void CreateQStackedWidgetAndAddQLabels();
    inline void CreateMainLayout();

private:
    QListWidget *list;
    QStackedWidget *stack;
    QLabel *label1;
    QLabel *label2;
    QLabel *label3;
    QHBoxLayout *mainLayout;
};

#endif // STACKDLG_H
#include "stackdlg.h"
#include <QListWidget>
#include <QStackedWidget>
#include <QLabel>
#include <QHBoxLayout>

StackDlg::StackDlg(QWidget *parent)
    : QDialog(parent), list(nullptr), stack(nullptr)
    , label1(nullptr), label2(nullptr), label3(nullptr)
    , mainLayout(nullptr)
{
    setWindowTitle(tr("StackedWidget"));
    CreateMainLayout();
}

void StackDlg::CreateQListWidget()
{
    if (!list)
        list = new QListWidget(this);
    list->insertItem(0, tr("Window1"));
    list->insertItem(1, tr("Window2"));
    list->insertItem(2, tr("Window3"));
}

void StackDlg::CreateQLabels()
{
    if (!label1)
        label1 = new QLabel(tr("WindowTest1"));
    if (!label2)
        label2 = new QLabel(tr("WindowTest2"));
    if (!label3)
        label3 = new QLabel(tr("WindowTest3"));
}

void StackDlg::CreateQStackedWidgetAndAddQLabels()
{
    if (!stack)
        stack = new QStackedWidget(this);

    CreateQLabels();
    stack->addWidget(label1);
    stack->addWidget(label2);
    stack->addWidget(label3);
}

void StackDlg::CreateMainLayout()
{
    if (!mainLayout)
        mainLayout = new QHBoxLayout(this);
    mainLayout->setMargin(5);
    mainLayout->setSpacing(5);

    CreateQListWidget();
    mainLayout->addWidget(list);

    CreateQStackedWidgetAndAddQLabels();
    mainLayout->addWidget(stack, 0, Qt::AlignCenter);
    mainLayout->setStretchFactor(list, 1);
    mainLayout->setStretchFactor(stack, 3);

    connect(list, SIGNAL(currentRowChanged(int)), stack, SLOT(setCurrentIndex(int)));
}

StackDlg::~StackDlg()
{
    if (list) delete list;
    if (label1) delete label1;
    if (label2) delete label2;
    if (label3) delete label3;
    if (stack) delete stack;
    if (mainLayout) delete mainLayout;
}

输出结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值