Search code examples
c++qtqt4qpushbuttonqtextdocument

Two colours text in QPushButton


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());

And I get, enter image description here

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>");

enter image description here

Any solution?

Thank very much.


Solution

  • 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");
        }
    };