在QT当中,许许多多的控件是能识别html代码的,比如Qlable,Qpushbutton等等,这些控件都是支持识别Html代码的,例如下面代码:
QString a; a.append(QString("<font style='color:red;'>%1</font>").arg("aaa")); ui->lable->settext(a);
此时会Qlable会显示一个红色的aaa的标签,button也是如此。都是能自动识别的
但是这一方案在像Qlistview或者Qtableview中就不实用了(此处使用的是Qlistview),虽然在有QlistviewQStandardItem::setForeground和QStandardItem::setBackground这两个方法可以设置整行颜色背景和字体颜色,但是我想实现利用字符串更改颜色字体,在Qlistview就能实现显示,但是原本的控件使用会出现下面这个情况
但是这并不是我想要的结果,我想要的结果如下:
以上使用的model是QStringListModel
在经过好几天的测试,查找资料终于找到解决方案
方案比较简单,既然Qlistview不支持富文本,那就让他成为富文本
自定义一个MyModel类,这个类继承QStyledItemDelegate,从而实现对Qlistview的每行内容的代理。
mymodel.h代码如下:
class MyModel:public QStyledItemDelegate { Q_OBJECT protected: void paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const; };
mymodel.cpp代码如下:
void MyModel::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItemV4 optionV4 = option; initStyleOption(&optionV4, index); QStyle *style = optionV4.widget? optionV4.widget->style() : QApplication::style(); QTextDocument doc; doc.setHtml(optionV4.text); // Painting item without text optionV4.text = QString(); style->drawControl(QStyle::CE_ItemViewItem, &optionV4, painter); QAbstractTextDocumentLayout::PaintContext ctx; // Highlighting text if item is selected if (optionV4.state & QStyle::State_Selected) ctx.palette.setColor(QPalette::Text, optionV4.palette.color(QPalette::Active, QPalette::HighlightedText)); QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &optionV4); painter->save(); painter->translate(textRect.topLeft()); painter->setClipRect(textRect.translated(-textRect.topLeft())); doc.documentLayout()->draw(painter, ctx); painter->restore(); }
这样一来 使用代理功能就可以实现让Qlistview成为富文本,测试代码如下:
QString a; a.append(QString("<font style='background-color:#ffcccc; color:red;'>%1</font>").arg("aaa")); a.append('\n'); a.append(QString("<font style='background-color:#ffcccc; color:red;'>%1</font>").arg("衰老和你")); QStringList b; b = a.split('\n'); QStringListModel *model =new QStringListModel(); ui->listview->setModel(model); ui->listview->setItemDelegateForColumn(0, new MyModel()); model->setStringList(b);
测试结果: