文章标题 原创 翻译 转载 文章内容 QTextEdit支持HTML展示,这样实现高亮就很简单了。 # 需求 QTextEdit展示了一些信息,增加一个搜索框,搜索时实时高亮出搜索的内容并滚动到最近搜索到的地方。 # 实现 连接textChanged信号,在onSearchChanged中实现,如果搜索文本为空就显示原文本内容,不为空就将其搜索的关键字替换成a标签,name为anchor是为了滚动到指定位置,然后将其拼装成html文档格式,增加css样式(红色高亮),这样就实现我们需要的功能。 注意这里如果不用a标签,高亮是可以的,但是滚动到anchor可能有问题。 ``` void CacheWidget::onSearchChanged(const QString &text) { if (text.isEmpty()) { setText(text_); } else { QString html = text_; html.replace(text, QString("<a name=\"anchor\">%1</a>").arg(text)); ui.teContent->setHtml(QString("<html><head><style>a{color:red;font-weight:bold;}</style></head><body>%1</body></html>").arg(html)); ui.teContent->scrollToAnchor("anchor"); } } ``` 文章类别 Python Mobile Android Java Shell Life Database Bug Windows IOS Tools Boost Node.js Mac Product Tips C/C++ Golang Javascript React Qt MQ MongoDB Design Web Linux LLM ChatGPT RAG AI 提交