Qt World Summit: Submit your Presentation

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

    And I get,

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


    Any solution?

    Thank very much.

  • Moderators


    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