QTextEdit查找某个字符串更换颜色样式

导读:本篇文章讲解 QTextEdit查找某个字符串更换颜色样式,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

受到“一去二三里”启发,致谢,博客专家http://blog.sina.com.cn/s/blog_a6fb6cc90101iadm.html

将某个指定字符串更改为指定颜色,确实有这个需要,比如警告 错误应该提醒用户为红色正常应该为绿色,qt本身并没有这样自带的接口函数,需自己实现:

QTextEdit查找某个字符串更换颜色样式

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
        }
    }
}

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之家整理,本文链接:https://www.bmabk.com/index.php/post/96564.html

(0)
小半的头像小半

相关推荐

极客之家——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!