96、QT 实现LED圆形指示灯控件

发布于:2024-08-15 ⋅ 阅读:(136) ⋅ 点赞:(0)

在这里插入图片描述
代码实现更改控件样式表的颜色和形状等

//QLabel控件变成圆形LED指示灯样式表
const QString QLabel_LED_Circle_SheetStyle_Red = "min-width: 20px; min-height: 20px;max-width:20px; max-height: 20px;border-radius: 10px; background:red";//红色
const QString QLabel_LED_Circle_SheetStyle_Green = "min-width: 20px; min-height: 20px;max-width:20px; max-height: 20px;border-radius: 10px; ;background:green";//绿色
const QString QLabel_LED_Circle_SheetStyle_Gray = "min-width: 20px; min-height: 20px;max-width:20px; max-height: 20px;border-radius: 10px;  border:1px solid black;background:grey";//灰色
const QString QLabel_LED_Circle_SheetStyle_Yellow = "min-width: 20px; min-height: 20px;max-width:20px; max-height: 20px;border-radius: 10px;  border:1px solid black;background:yellow";//黄色
    ui->led->setStyleSheet(QLabel_LED_Circle_SheetStyle_Red);// 红色圆形警示灯

在这里插入图片描述
在这里插入图片描述
第二种方法:
声明:

    void QT_QLabel_LED_Set(QLabel *label,QString rgb_color,bool shape = false,uint8_t size = 20);

直接调用此函数

/****************************************
@function:QT QLabel指示颜色设置
@param:label--文本控件
    rgb_color--颜色值,见宏RGB颜色值,如dRGB_RED
    shape--LED形状,假-圆形,真-矩形,默认圆形
    size--像素大小px,默认20px
@return:void
@note:QLabel控件变成圆形|矩形LED指示灯样式表,拖放控件时请把最小高度设置为使用的像素大小
****************************************/
void Common::QT_QLabel_LED_Set(QLabel *label,QString rgb_color,bool shape,uint8_t size)
{
    QString min_width,min_height,max_width,max_height,border_radius,border,background;
    label->setText("");// 将label中的文字清空
    if(shape)
    {
        min_width  = QString("min-width: %1px;").arg(size);       // 最小宽度:size
        min_height = QString("min-height: %1px;").arg(size / 2);  // 最小高度:size
        max_width  = QString("max-width: %1px;").arg(size * 3);   // 最大宽度:size
        max_height = QString("max-height: %1px;").arg(size);      // 最大高度:size
    }
    else
    {
        min_width  = QString("min-width: %1px;").arg(size);       // 最小宽度:size
        min_height = QString("min-height: %1px;").arg(size);  // 最小高度:size
        max_width  = QString("max-width: %1px;").arg(size);   // 最大宽度:size
        max_height = QString("max-height: %1px;").arg(size);      // 最大高度:size
    }
    // 再设置边界形状及边框
    border_radius = QString("border-radius: %1px;").arg(size/2);  // 边框是圆角,半径为size/2
    border = QString("border:1px solid black;");  // 边框为1px黑色

    // 最后设置背景颜色
    background = "background-color:" + rgb_color;
    const QString SheetStyle = min_width + min_height + border_radius + border + background;
    label->setStyleSheet(SheetStyle);
    label->setAlignment(Qt::AlignCenter);
}