QListview或Qtableview等控件无法识别Html代码的解决方法(让Qlistview成为富文本)

3 篇文章 0 订阅

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

测试结果:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值