QPushButton中的两种颜色的文本 [英] Two colours text in QPushButton

查看:458
本文介绍了QPushButton中的两种颜色的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个QPushButton,文本中有两种颜色。我在QTextDocument中找到了带有html代码的解决方案,并且可以正常工作。但是我需要居中对齐,并且html代码无法正常工作。

I need a QPushButton with two colors in the text. I found a solution with a html code in QTextDocument and it's working. But I need center align and the html code isn't working.

 QTextDocument Text;
  Text.setHtml("<p align=center><font>Button</font><br/><font color=yellow>1</font></p>");

   QPixmap pixmap(Text.size().width(), Text.size().height());
   pixmap.fill( Qt::transparent );
   QPainter painter(&pixmap);
   Text.drawContents(&painter, pixmap.rect());

   QIcon ButtonIcon(pixmap);
   ui->toolButton->setText("");
   ui->toolButton->setIcon(ButtonIcon);
   ui->toolButton->setIconSize(pixmap.rect().size());

我得到

同一代码HTML在QLabel中工作

The same code HTML is working in a QLabel

ui->label->setText("<p align=center><font>Label</font><br/><font color=yellow>1</font></p>");

有什么解决方案吗?

非常感谢。

推荐答案

您可以从QPushButton派生并通过QPainter在paintEvent中自己绘制文本。

You can derive from QPushButton and draw text yourself via QPainter in paintEvent.

class Button : public QPushButton
{
Q_OBJECT

public:
Button(QWidget *parent = 0)
: QPushButton(parent)
    { }

void paintEvent(QPaintEvent *p)
    {
        QPushButton::paintEvent(p);
        QPainter paint(this);
        paint.drawText(QPoint(10,10),"Hello");
    }
};

这篇关于QPushButton中的两种颜色的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆