pyqt highlight all occurrences of selected word qt

Solutions on MaxInterview for pyqt highlight all occurrences of selected word qt by the best coders in the world

showing results for - "pyqt highlight all occurrences of selected word qt"
Adriana
24 Aug 2020
1from PyQt4 import QtGui
2from PyQt4 import QtCore
3
4class MyHighlighter(QtGui.QTextEdit):
5    def __init__(self, parent=None):
6        super(MyHighlighter, self).__init__(parent)
7        # Setup the text editor
8        text = """In this text I want to highlight this word and only this word.\n""" +\
9        """Any other word shouldn't be highlighted"""
10        self.setText(text)
11        cursor = self.textCursor()
12        # Setup the desired format for matches
13        format = QtGui.QTextCharFormat()
14        format.setBackground(QtGui.QBrush(QtGui.QColor("red")))
15        # Setup the regex engine
16        pattern = "word"
17        regex = QtCore.QRegExp(pattern)
18        # Process the displayed document
19        pos = 0
20        index = regex.indexIn(self.toPlainText(), pos)
21        while (index != -1):
22            # Select the matched text and apply the desired format
23            cursor.setPosition(index)
24            cursor.movePosition(QtGui.QTextCursor.EndOfWord, 1)
25            cursor.mergeCharFormat(format)
26            # Move to the next match
27            pos = index + regex.matchedLength()
28            index = regex.indexIn(self.toPlainText(), pos)
29
30if __name__ == "__main__":
31    import sys
32    a = QtGui.QApplication(sys.argv)
33    t = MyHighlighter()
34    t.show()
35    sys.exit(a.exec_())
36