c++ - QPushButton 中的两种颜色文本

标签 c++ qt qt4 qpushbutton qtextdocument

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

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

我明白了,enter image description here

相同的代码 HTML 在 QLabel 中工作

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

enter image description here

有什么解决办法吗?

非常感谢。

最佳答案

作为解决方法,您可以使用标签或文本文档来打印您想要的文本。你应该把它画成一个像素图并在你的按钮上使用像素图:

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

您还可以找到富文本按钮实现 here .

另一种选择是使用 QxtPushButton来自 libqxt 的类。 QxtPushButton 小部件是具有旋转和富文本支持的扩展 QPushButton。

关于c++ - QPushButton 中的两种颜色文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26852340/

相关文章:

c++ - 创建没有可调用对象的 boost::thread

android - 如何作为模块缓冲读/写数据

linux - 在 linux 中生成鼠标按钮单击

c++ - Qt:如何使用 QtSound 重复声音 x 次

c++ - QAbstractItemModel::endInsertRows:无效索引运行时错误

c++ - FFmpeg + OpenAL - 无法播放视频中的流式声音

c++ - boost::variant 与 bool 和 string

python - 如何设置像素图的最大宽度和高度?

QtQuick 未正确安装 Visual C++

c++ - 如何将图像保存在调整大小的 QLabel 中?