C++Qt堆叠窗体的使用案例

本博文源于笔者最近学习的Qt,内容讲解堆叠窗体QStackedWidget案例,效果是选择左侧列表框中不同的选项时,右侧显示所选的不同的窗体。

案例效果

案例书写过程

控件都是动态创建的,因此.h文件需要创建控件,.cpp书写业务代码

cpp 复制代码
#ifndef DIALOG_H
#define DIALOG_H

#include <QDialog>
#include<QListWidget>
#include<QStackedWidget>
#include<QLabel>


namespace Ui {
class Dialog;
}

class Dialog : public QDialog
{
    Q_OBJECT

public:
    explicit Dialog(QWidget *parent = nullptr);
    ~Dialog();

private:
    Ui::Dialog *ui;
    QListWidget *list;
    QStackedWidget *stack;
    QLabel* label1;
    QLabel* label2;
    QLabel* label3;
};

#endif // DIALOG_H

.cpp文件,要分为两个部分

cpp 复制代码
#include "dialog.h"
#include "ui_dialog.h"
#include<QHBoxLayout>


Dialog::Dialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::Dialog)
{
//    ui->setupUi(this);
    setWindowTitle(tr("StackedWidget"));
    list = new QListWidget(this);
    list->insertItem(0,tr("Window1"));
    list->insertItem(1,tr("Window2"));
    list->insertItem(2,tr("Window3"));

    label1 = new QLabel(tr("WindowTest1"));
    label2 = new QLabel(tr("WindowTest2"));
    label3 = new QLabel(tr("WindowTest3"));
    stack = new QStackedWidget(this);

    //
    stack->addWidget(label1);
    stack->addWidget(label2);
    stack->addWidget(label3);
    QHBoxLayout* mainLayout = new QHBoxLayout(this);

    mainLayout->setMargin(5);
    mainLayout->setSpacing(5);
    mainLayout->addWidget(list);
    mainLayout->addWidget(stack,0,Qt::AlignHCenter);
    mainLayout->setStretchFactor(list,1);
    mainLayout->setStretchFactor(stack,3);
    connect(list,SIGNAL(currentRowChanged(int)),stack,SLOT(setCurrentIndex(int)));


}

Dialog::~Dialog()
{
    delete ui;
}
相关推荐
郝学胜_神的一滴5 分钟前
CMake 30:循环语法全解|foreach_while双循环精讲、迭代技巧与实战避坑指南
c++·cmake
卷无止境2 天前
C++ 的Eigen 库全解析
c++
卷无止境2 天前
现代 C++特性大盘点:一门脱胎换骨的老语言
c++·后端
郝学胜_神的一滴2 天前
CMake 27:缓存变量的特性、语法、类型与实操全解
c++·cmake
Quz3 天前
QML Hello World 入门示例
qt
博客18004 天前
酷宝的使用方法,超好用的免费界面库,C++、MFC可用
c++·mfc·界面库·库来帮·酷宝
郝学胜_神的一滴4 天前
CMake 026:属性体系精讲、四大作用域全解 & 实战代码落地
c++·cmake
众少成多积小致巨5 天前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
xcyxiner6 天前
DicomViewer (dcmtk读取dcm文件)5
qt
xcyxiner7 天前
DicomViewer (后台线程处理文件)4
qt