Qt中用QLabel创建状态灯

首先ui设计中分别创建了4个大灯和4个小灯。

编辑.h文件

cpp 复制代码
#ifndef LED_H
#define LED_H

#include <QWidget>
#include <QLabel>

QT_BEGIN_NAMESPACE
namespace Ui { class Led; }
QT_END_NAMESPACE

class Led : public QWidget
{
    Q_OBJECT

public:
    Led(QWidget *parent = nullptr);
    ~Led();

private:
    void initData();
    void initUi();

private:
    Ui::Led *ui;
    QVector<QString> color_s;   ///< 存放设置小灯的样式字符串
    QVector<QString> color_b;   ///< 存放设置大灯的样式字符串
    enum colorType {GREY = 0, RED, GREEN, YELLOW};  ///< 灯颜色枚举
};
#endif // LED_H

编辑.cpp文件

cpp 复制代码
#include "led.h"
#include "ui_led.h"

Led::Led(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Led)
{
    ui->setupUi(this);
    initData();
    initUi();
}

Led::~Led()
{
    delete ui;
}

void Led::initData()
{
    QString comm_s("min-width:20px;min-height:20px;max-width:20px;max-height:20px;border-radius:13px;border:3px rgb(147, 147, 147);border-style:outset;");
    color_s.push_back(comm_s + QString("background-color:rgb(195, 195, 195);"));    ///< GREY
    color_s.push_back(comm_s + QString("background-color:rgb(255, 0, 0);"));        ///< RED
    color_s.push_back(comm_s + QString("background-color:rgb(0, 255, 0);"));        ///< GREEN
    color_s.push_back(comm_s + QString("background-color:rgb(255, 255, 0);"));      ///< YELLOW

    QString comm_b("min-width:34px;min-height:34px;max-width:34px;max-height:34px;border-radius:20px;border:3px rgb(147, 147, 147);border-style:outset;");
    color_b.push_back(comm_b + QString("background-color:rgb(195, 195, 195);"));    ///< GREY
    color_b.push_back(comm_b + QString("background-color:rgb(255, 0, 0);"));        ///< RED
    color_b.push_back(comm_b + QString("background-color:rgb(0, 255, 0);"));        ///< GREEN
    color_b.push_back(comm_b + QString("background-color:rgb(255, 255, 0);"));      ///< YELLOW
}

void Led::initUi()
{
    ui->leds1->setStyleSheet(color_s[colorType::GREY]);
    ui->ledb1->setStyleSheet(color_b[colorType::GREY]);

    ui->leds2->setStyleSheet(color_s[colorType::RED]);
    ui->ledb2->setStyleSheet(color_b[colorType::RED]);

    ui->leds3->setStyleSheet(color_s[colorType::GREEN]);
    ui->ledb3->setStyleSheet(color_b[colorType::GREEN]);

    ui->leds4->setStyleSheet(color_s[colorType::YELLOW]);
    ui->ledb4->setStyleSheet(color_b[colorType::YELLOW]);
}

效果这样:

相关推荐
快乐的划水a8 小时前
组合模式及优化
c++·设计模式·组合模式
星星火柴93610 小时前
关于“双指针法“的总结
数据结构·c++·笔记·学习·算法
艾莉丝努力练剑10 小时前
【洛谷刷题】用C语言和C++做一些入门题,练习洛谷IDE模式:分支机构(一)
c语言·开发语言·数据结构·c++·学习·算法
阿巴~阿巴~13 小时前
深入解析C++ STL链表(List)模拟实现
开发语言·c++·链表·stl·list
旺小仔.14 小时前
双指针和codetop复习
数据结构·c++·算法
jingfeng51414 小时前
C++ STL-string类底层实现
前端·c++·算法
郝学胜-神的一滴14 小时前
基于C++的词法分析器:使用正则表达式的实现
开发语言·c++·程序人生·正则表达式·stl
前端市界15 小时前
前端视角: PyQt6+Vue3 跨界开发实战
前端·qt·pyqt
努力努力再努力wz15 小时前
【c++深入系列】:万字详解模版(下)
java·c++·redis
瓦特what?16 小时前
关于C++的#include的超超超详细讲解
java·开发语言·数据结构·c++·算法·信息可视化·数据挖掘