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]);
}

效果这样:

相关推荐
xlq223225 小时前
22.多态(上)
开发语言·c++·算法
D_evil__6 小时前
[C++高频精进] 并发编程:线程基础
c++
Mr_WangAndy7 小时前
C++17 新特性_第二章 C++17 语言特性_std::any和string_view
c++·string_view·c++40周年·c++17新特性·c++新特性any
水天需0108 小时前
C++ 三种指针转换深度解析
c++
言言的底层世界9 小时前
c++中STL容器及算法等
开发语言·c++·经验分享·笔记
Mr_WangAndy9 小时前
C++17 新特性_第一章 C++17 语言特性___has_include,u8字符字面量
c++·c++40周年·c++17新特性·__has_include·u8字面量
liu****9 小时前
八.函数递归
c语言·开发语言·数据结构·c++·算法
韭菜钟10 小时前
在Qt中使用QuickJS
开发语言·qt
Vanranrr10 小时前
C++临时对象与悬空指针:一个导致资源加载失败的隐藏陷阱
服务器·c++·算法
BestOrNothing_201510 小时前
【C++基础】Day 5:struct 与 class
c++·c·class类·struct结构体·typename模板·private与public