QListWidget change part color of text

喜欢而已 提交于 2019-12-09 22:33:04

问题


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

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)

Can Anyone help?

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.

回答1:


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

Then use the setItemDelegate() method of QListWidget as shown below:

ui->listWidget->setItemDelegate(new HtmlDelegate);

Obtaining what is shown in the following image:

The complete example can be found at the following link.



来源:https://stackoverflow.com/questions/46189816/qlistwidget-change-part-color-of-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!