Two-color text in QPushButton

I need a QPushButton with two colors in the text. I found a solution with html code in a QTextDocument and it works. But I need center alignment and the html code is not 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 HTML code works in QLabel

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

enter image description here

Any solution?

Many thanks.

+5
source share
3 answers

You can get from QPushButton and draw the text yourself through a 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"); } }; 
+2
source

This is reported by an error report . When you use QTextDocument::drawContents , it tends to ignore child support. To make it work, set the width of the text using QTextDocument::setTextWidth .

 QTextDocument doc; doc.setHtml("<p align=center><font>Button</font><br/><font color=red>1</font></p>"); doc.setTextWidth(doc.size().width()); QPixmap pixmap(doc.size().width(), doc.size().height()); pixmap.fill( Qt::transparent ); QPainter painter(&pixmap); doc.drawContents(&painter); QPushButton button; button.setIconSize(pixmap.size()); button.setIcon(pixmap); button.show(); 
+2
source

As a workaround, you can use a shortcut or text document to print the text you want. You have to color it in pixmap and use pixmap on your button:

 QPushButton *button = new QPushButton(this); QTextDocument Text; Text.setHtml("<h2><i>Hello</i> ""<font color=red>Qt!</font></h2>"); QPixmap pixmap(Text.size().width(), Text.size().height()); pixmap.fill( Qt::transparent ); QPainter painter( &pixmap ); Text.drawContents(&painter, pixmap.rect()); QIcon ButtonIcon(pixmap); button->setIcon(ButtonIcon); button->setIconSize(pixmap.rect().size()); 

You can also find the implementation of the button with extended text here .

Another option is to use the QxtPushButton class from libqxt. QxtPushButton widget is an advanced QPushButton with support for rotation and rich text.

+1
source

Source: https://habr.com/ru/post/1206586/


All Articles