QT:使用堆叠窗口、标签、下拉条

widget.h

cpp 复制代码
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include <QStackedWidget>  //堆叠窗口
#include <QComboBox>       //下拉条
#include <QLabel>          //标签

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = 0);
    ~Widget();
private:
    QStackedWidget *sw; //容器,装标签
    QComboBox *cbb;     //下拉条
    QLabel *lb[2];      //两个标签,装两张图片
};

#endif // WIDGET_H

widget.cpp

cpp 复制代码
#include "widget.h"
#include <QVBoxLayout>
#include <QHBoxLayout>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    setWindowTitle("堆叠窗口");
    sw = new QStackedWidget(this);  //创建堆叠窗口
    sw->setFixedSize(640,480);      //设置窗口大小

    QStringList picFileList = {":/pictures/1.jpg",":/pictures/2.jpg"};  //保存图片路径信息
    for(int i = 0;i < 2;i++)
    {
        lb[i] = new QLabel(this);   //创建标签
        lb[i]->setFixedSize(640,480);    //设置标签大小
        lb[i]->setScaledContents(true);   //设置自适应大小
        lb[i]->setPixmap((QPixmap(picFileList.at(i))));  //在标签中装入picFileList中索引为i的对应图片
        sw->addWidget(lb[i]);   //容器中添加2个标签
    }
    sw->setCurrentIndex(0);  //堆叠窗口设置当前索引为0,运行后显示的是第一个标签的图片

    cbb = new QComboBox(this);   //创建下拉条
    for(int i = 0;i < 2;i++)
    {
        cbb->addItem(QIcon(picFileList[i]),picFileList.at(i));  //添加条目,包括图片图标,图片路径
    }

    //cbb->addItems(picFileList);

    QHBoxLayout *hb = new QHBoxLayout();
    hb->addStretch();    //弹簧
    hb->addWidget(cbb);   //设置在中间位置
    hb->addStretch();

    QVBoxLayout *vb = new QVBoxLayout();
    vb->addWidget(sw);
    vb->addLayout(hb);

    setLayout(vb);

    connect(cbb,QOverload<int>::of(&QComboBox::currentIndexChanged),[=](int index){ //有重载,需要确定使用带哪个参数的函数
        sw->setCurrentIndex(index);     //下拉条索引改变时触发容器当面页面改变
    });
}

Widget::~Widget()
{

}

main.cpp

cpp 复制代码
#include "widget.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Widget w;
    w.show();

    return a.exec();
}

结果

相关推荐
bug和崩溃我都要2 小时前
QT 开发的专业截图录屏工具 - macOS版 / Windows版
windows·qt·mac·录屏·截屏
Python图像识别4 小时前
40-【2027毕设】YOLO11面部口罩检测识别系统 - Python完整源码+PyQt5界面+训练模型+数据集
python·qt·课程设计
Python图像识别5 小时前
39-【2027毕设】YOLO11行人摔倒检测系统 - Python完整源码+PyQt5界面+训练模型+数据集
python·qt·课程设计
Quz14 小时前
QML PathView:直线路径与曲线路径
qt·动画·qml
扶尔魔ocy16 小时前
【qt openGL入门笔记】OSG实现飞机模型在网格图上飞行
qt·opengl·osg
西飘客1 天前
vs 怎么根据dll 生成lib文件
c++·qt
bkspiderx1 天前
Qt 插件机制:动态扩展应用功能的核心框架
开发语言·qt·元数据·qt 插件·qpluginloader
半杯咖啡半行码1 天前
Qt开发实战:数据库、MV 模式、QProcess与串口通信全攻略
数据库·qt
时间的拾荒人1 天前
Qt 界面优化:绘图详解 —— 从基础图形到图片处理
开发语言·qt·面试