Qt之QTableView显示富文本
2024-10-01 06:52:26
简述
对于QTableView中的显示,我们前面介绍过很多种,其中包括:文本、进度条、复选框等,今天我们介绍一下关于富文本的显示。
可能绝大多数小伙伴会通过QAbstractTableModel中的data来实现,可是现实告诉我们,那是行不通的,那么我们如何去显示呢?请看正文。
效果
源码
下面我们使用QAbstractItemDelegate来进行富文本的显示,主要通过QTextDocument设置HTML代码来实现。
void CheckBoxDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
QStyleOptionViewItem viewOption(option);
initStyleOption(&viewOption, index);
if (option.state.testFlag(QStyle::State_HasFocus))
viewOption.state = viewOption.state ^ QStyle::State_HasFocus;
// ... 省略
// 设置显示文本为空,使用默认样式
QStyle *pStyle = viewOption.widget? viewOption.widget->style() : QApplication::style();
viewOption.text = "";
pStyle->drawControl(QStyle::CE_ItemViewItem, &viewOption, painter, viewOption.widget);
// 需要显示的HTML
QString strHTML = QString("<html> \
<head> \
<style> \
font{font-size:18px; color:white;} #f{font-size:26px; color: green;} \
</style> \
</head> \
<body>\
<font>%1</font><font id=\"f\">%2</font> \
<img src=\":/Images/logo\" width=\"40\" height=\"40\"> \
</body> \
</html>").arg("I am a ").arg("Qter");
QTextDocument doc;
doc.setHtml(strHTML);
QAbstractTextDocumentLayout::PaintContext paintContext;
QRect textRect = pStyle->subElementRect(QStyle::SE_ItemViewItemText, &viewOption);
painter->save();
// 坐标变换,将左上角设置为原点
painter->translate(textRect.topLeft());
// 设置HTML绘制区域
painter->setClipRect(textRect.translated(-textRect.topLeft()));
doc.documentLayout()->draw(painter, paintContext);
painter->restore();
}
分析
首先我们需要保留原有样式,所以设置QStyleOptionViewItem的文本为空,然后调用QStyle的drawControl接口来进行绘制,然后通过QTextDocument设置HTML代码,利用QPainter来进行文本的绘制,绘制区域通过整个文本区域经过坐标变换后得到的。
最新文章
- C# Iterator迭代器的实现方式
- 使用TypeScript开发程序
- 关于C#迭代器
- 【网络收集】如何修改vs tfs的登录名和密码 .
- Google Code Jam 2015 Round1A 题解
- jQuery—一些常见方法(1)【filter(),not(),has(),next(),prev(),find(),eq(),index(),attr(),】
- 江中微型统计分析软件V1.0版本完成
- 使用layer显示弹出框笔记
- Jquery在线咨询地址
- 【笔记】nodejs读取JSON,数组转树
- ASP.NET部分代码示例
- 关于dp(背包)
- P1754 球迷购票问题
- android保持服务不休眠(持续运行)以及唤醒屏幕的方法
- 万恶之源 - Python装饰器及内置函数
- 八,ESP8266 文件保存数据(基于Lua脚本语言)
- SQL优化|Java面试题
- 【BZOJ】【1251】序列终结者
- codeforces 256 div2 C. Painting Fence 分治
- customs event
热门文章
- How Big Is A Petabyte, Exabyte, Zettabyte, Or A Yottabyte?
- HTTP message vs SOAP message
- ASP.NET用户控件事件的定义和实践
- Sqli-labs less 26a
- Java 8怎么了之二:函数和原语
- Unix安装BerkeleyDB
- [你必须知道的.NET]第二十九回:.NET十年(上)
- UVA 11181 dfs 概率
- __stdcall 与 __cdecl
- spring mvc 基于注解的使用总结