当前位置:
首页 >
QTextEdit查找某个字符串更换颜色样式
发布时间:2025/3/19
45
豆豆
生活随笔
收集整理的这篇文章主要介绍了
QTextEdit查找某个字符串更换颜色样式
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
受到“一去二三里”启发,致谢,博客专家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}} }
总结
以上是生活随笔为你收集整理的QTextEdit查找某个字符串更换颜色样式的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: C语言 IP地址合法性判断 去除字
- 下一篇: QT最方便的LOG库使用Easylogg