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;
}
相关推荐
rainbow6889几秒前
Linux文件描述符与重定向原理
c++
mengzhi啊42 分钟前
QUndoView 本质是一个 Qt 界面控件(继承自 QListView),专门适配 QUndoStack
qt
CodeSheep程序羊44 分钟前
拼多多春节加班工资曝光,没几个敢给这个数的。
java·c语言·开发语言·c++·python·程序人生·职场和发展
编程小白20261 小时前
从 C++ 基础到效率翻倍:Qt 开发环境搭建与Windows 神级快捷键指南
开发语言·c++·windows·qt·学习
深蓝海拓1 小时前
PySide6,QCoreApplication::aboutToQuit与QtQore.qAddPostRoutine:退出前后的清理工作
笔记·python·qt·学习·pyqt
薛定谔的猫喵喵2 小时前
天然气压力能利用系统综合性评价平台:基于Python和PyQt5的AHP与模糊综合评价集成应用
开发语言·python·qt
.小墨迹2 小时前
apollo学习之借道超车的速度规划
linux·c++·学习·算法·ubuntu
云中飞鸿2 小时前
linux中qt安装
开发语言·qt
少控科技2 小时前
QT第6个程序 - 网页内容摘取
开发语言·qt
历程里程碑2 小时前
Linux20 : IO
linux·c语言·开发语言·数据结构·c++·算法