QListWidget 更改文本的部分颜色 [英] QListWidget change part color of text
问题描述
点击这里打开示例图片,红色箭头是我想要的,但输出只是显示了所有代码,并没有像蓝色箭头那样工作
Click Here to open the Sample Picture, the red Arrow is what I want, But the output just show all the code and didn't work just like the Blue Arrow does
我尝试使用 <字体颜色 = 红色 >...</字体>||<跨度>...</span >
在 QListWidget 中,但是没有任何效果
I try use < font color = red >...< /font > || < span >...< /span >
in QListWidget, but There didn't have any Effect
我想要的是这样的东西:
What I want is some thing like:
item1 <font color=red>apple</font> ("item1" black, "apple" will output as red color)
item2 <font color=green>durian</font> (durian will output as green color)
有人可以帮忙吗?
Ps:其实我真正想要的是下图:当我输入cola"这个词时,QListwidget 的列表会将颜色%cola%"高亮/更改为不同的颜色.
Ps: Accually what I really want is the picture below: When I type the word "cola", the list of QListwidget will Highlight/Change the color "%cola%" into Different color.
推荐答案
QListWidget
默认情况下不呈现 Html,但为此 Qt 具有允许自定义视图的委托类.
QListWidget
by default does not render Html, but for this Qt has the delegate classes that allow customize the view.
在这种情况下,我们使用以下委托:
In this case we use the following delegate:
#ifndef HTMLDELEGATE_H
#define HTMLDELEGATE_H
#include <QPainter>
#include <QStyledItemDelegate>
#include <QTextDocument>
class HtmlDelegate : public QStyledItemDelegate
{
public:
void paint(QPainter* painter, const QStyleOptionViewItem & option, const QModelIndex &index) const
{
QStyleOptionViewItem options = option;
initStyleOption(&options, index);
painter->save();
QTextDocument doc;
doc.setHtml(options.text);
options.text = "";
options.widget->style()->drawControl(QStyle::CE_ItemViewItem, &options, painter);
painter->translate(options.rect.left(), options.rect.top());
QRect clip(0, 0, options.rect.width(), options.rect.height());
doc.drawContents(painter, clip);
painter->restore();
}
QSize sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const
{
QStyleOptionViewItem options = option;
initStyleOption(&options, index);
QTextDocument doc;
doc.setHtml(options.text);
doc.setTextWidth(options.rect.width());
return QSize(doc.idealWidth(), doc.size().height());
}
};
#endif // HTMLDELEGATE_H
然后使用QListWidget
的setItemDelegate()
方法如下图:
Then use the setItemDelegate()
method of QListWidget
as shown below:
ui->listWidget->setItemDelegate(new HtmlDelegate);
获得下图所示的内容:
完整的例子可以在下面找到链接.
The complete example can be found at the following link.
这篇关于QListWidget 更改文本的部分颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!