QTextEdit查找某个字符串更换颜色样式
受到“一去二三里”启发,致谢,博客专家http://blog.sina.com.cn/s/blog_a6fb6cc90101iadm.html将某个指定字符串更改为指定颜色,确实有这个需要,比如警告 错误应该提醒用户为红色,正常应该为绿色,qt本身并没有这样自带的接口函数,需自己实现:void Widget::search(){QString search_text = ...
·
受到“一去二三里”启发,致谢,博客专家http://blog.sina.com.cn/s/blog_a6fb6cc90101iadm.html
将某个指定字符串更改为指定颜色,确实有这个需要,比如警告 错误应该提醒用户为红色,正常应该为绿色,qt本身并没有这样自带的接口函数,需自己实现:

void Widget::search()
{
QString search_text = "未安装";//被查找数据
if (search_text.trimmed().isEmpty())//trimmed移除前后空白字符并判断是不是为空
{
//failed
}
else
{
QTextDocument *document = textEdit_process->document();//全部数据
bool found = false;
QTextCursor highlight_cursor(document);
QTextCursor cursor(document);
//开始
cursor.beginEditBlock();
QTextCharFormat color_format(highlight_cursor.charFormat());
color_format.setForeground(Qt::red);
while (!highlight_cursor.isNull() && !highlight_cursor.atEnd()) {
//查找指定的文本,匹配整个单词
highlight_cursor = document->find(search_text, highlight_cursor, QTextDocument::FindWholeWords);
if (!highlight_cursor.isNull())
{
if(!found)
{
found = true;
}
highlight_cursor.mergeCharFormat(color_format);
}
}
cursor.endEditBlock();
//结束
if (found == false) {
//failed
}
}
}
更多推荐

所有评论(0)