本博文源于笔者最近学习的Qt,内容讲解堆叠窗体QStackedWidget案例,效果是选择左侧列表框中不同的选项时,右侧显示所选的不同的窗体。
案例效果
案例书写过程
控件都是动态创建的,因此.h文件需要创建控件,.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文件,要分为两个部分
#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;
}