栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何找到子字符串并在QTextEdit中突出显示它?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何找到子字符串并在QTextEdit中突出显示它?

我认为最简单的解决方案是使用与您的编辑器关联的光标进行格式化。这样,您可以设置前景,背景,字体样式…下面的示例用不同的背景标记匹配项。

from PyQt4 import QtGuifrom PyQt4 import QtCoreclass MyHighlighter(QtGui.QTextEdit):    def __init__(self, parent=None):        super(MyHighlighter, self).__init__(parent)        # Setup the text editor        text = """In this text I want to highlight this word and only this word.n""" +        """Any other word shouldn't be highlighted"""        self.setText(text)        cursor = self.textCursor()        # Setup the desired format for matches        format = QtGui.QTextCharFormat()        format.setBackground(QtGui.QBrush(QtGui.QColor("red")))        # Setup the regex engine        pattern = "word"        regex = QtCore.QRegExp(pattern)        # Process the displayed document        pos = 0        index = regex.indexIn(self.toPlainText(), pos)        while (index != -1): # Select the matched text and apply the desired format cursor.setPosition(index) cursor.movePosition(QtGui.QTextCursor.EndOfWord, 1) cursor.mergeCharFormat(format) # Move to the next match pos = index + regex.matchedLength() index = regex.indexIn(self.toPlainText(), pos)if __name__ == "__main__":    import sys    a = QtGui.QApplication(sys.argv)    t = MyHighlighter()    t.show()    sys.exit(a.exec_())

该代码是不言自明的,但是如果您有任何疑问,请问他们。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/659947.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号