QPushButton设置不同颜色字体,以便强调数量的变化

先上效果图:

上方按钮是原始形态,直接给QPushButton设置文本,是无法达到局部文字颜色变化的,普普通通;

而下方按钮,是可以随意更改局部某些文字,十分方便。

 

具体实现如下:

(自定义按钮)

复制代码
#include <QHBoxLayout>
#include <QLabel>

CustomBtn::CustomBtn(QWidget *parent) : QPushButton(parent)
{
    this->setCheckable(true);

    m_lb = new QLabel(this);
    m_lb->setAttribute(Qt::WA_TransparentForMouseEvents, true);
    m_lb->setAlignment(Qt::AlignCenter);
    m_lb->setTextFormat(Qt::RichText);

    auto in_lay = new QHBoxLayout(this);
    in_lay->setMargin(0);
    in_lay->addWidget(m_lb);
}

void CustomBtn::setTextWithColor(const QString &in_str)
{
    m_lb->setText(in_str);
}
复制代码

(设置文字)

复制代码
#include "custombtn.h"
#include <QDebug>

FrmTest::FrmTest(QWidget *parent) : QWidget(parent), ui(new Ui::FrmTest)
{
    ui->setupUi(this);

    CustomBtn *in_btn = new CustomBtn();
    QString in_str = QStringLiteral("信号列表(<font color='red'>%1+</font>)").arg(99);
    in_btn->setTextWithColor(in_str);

    ui->verticalLayout_2->insertWidget(1, in_btn);
    connect(in_btn, &CustomBtn::clicked, this, [=](){
        qDebug()<<"FrmTest:"<<in_btn->isChecked();
    });
}

FrmTest::~FrmTest()
{
    delete ui;
}
复制代码

(测试:选中状态与非选中状态,反应灵敏准备)

 

posted @   李涛贤贤  阅读(1014)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示