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 @ 2023-02-03 21:18  李涛贤贤  阅读(688)  评论(0编辑  收藏  举报