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

效果这样:

相关推荐
小保CPP8 小时前
OpenCV C++计算多边形的最大内切圆
c++·人工智能·opencv·计算机视觉
lueluelue479 小时前
八股临时总结
c++
Quz9 小时前
QML 基础按钮:Button、RoundButton 与 DelayButton
qt
Quz9 小时前
QML ToolTip 组件:图标、多行文本与阴影
qt
xcyxiner10 小时前
DicomViewer14(读取图像按固定窗宽窗位显示)
qt
xvhao201310 小时前
T750414 【游戏】计算24点 题解
数据结构·c++·算法·游戏
草莓熊Lotso11 小时前
【LangChain】核心组件详解:文档加载器(Document Loaders)
开发语言·c++·python·langchain·软件工程
ysa05103011 小时前
优先队列贪心dp
c++·笔记·算法·板子
草莓熊Lotso12 小时前
【Linux网络】深入理解Linux IO多路复用:select服务器完善、内核原理与poll实战
linux·运维·服务器·c语言·网络·c++
Andy12 小时前
Cpp进阶语法详解
c++