Two colours and center 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,
    !http://i.stack.imgur.com/5Gmov.png(Button)!

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

    !http://i.stack.imgur.com/PZgvb.png(Label)!

    Any solution?

    Thank very much.


  • Moderators

    Hi,

    AFAIK QPushButton or QToolButton doesnot accept RichText so HTML type code will not work.
    The best way in this case would be to subclass QPushButton to create your own button and then override paintevent() to draw the text in whatever way you like.


  • Moderators

    Why do you need a QTextDocument or HTML at all?
    You can directly draw the text on the pixmap with any color and alignment you want using "QPainter::drawText":http://qt-project.org/doc/qt-5/qpainter.html#drawText-4 with Qt::AlignCenter as part of the flags argument.



  • you can use painterevent of the push button to draw every thing you want.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.