Search code examples
pythonpyqt5qtexteditqtextdocument

How to highlight a word from the text in qtextedit in pyqt5 python?


I'm creating a text editor in pyqt5 python. and I want to add the find feature like any other text/code editor. After entering a word or words in a find line edit; that word will be highlighted in TextEdit! how can do it in pyqt5 python [not in pyqt4 or any other programming language] my code:

class Ui_nms_pad(QMainWindow):
    def __init__(self):
        super(Ui_nms_pad, self).__init__() 
        uic.loadUi('Nms_pad.ui', self)
        self.Find_Button.clicked.connect(self.Find_word())
    def Find_word(self):
        words = self.Find_lineEdit.text
        {highlight words in text edit}

Solution

  • from PyQt5.QtWidgets import QMainWindow, QTextEdit, QWidget, QLineEdit, QVBoxLayout, QApplication
    from PyQt5.QtGui import QTextCharFormat, QBrush
    from PyQt5.QtCore import Qt
    import sys
    
    class MainWindow(QMainWindow):
    
        def __init__(self, parent=None):
            super().__init__(parent)
    
            self.extraSelections = []
            self.lineEdit = QLineEdit(placeholderText="search")
            self.textEdit = QTextEdit("""Lorem Ipsum is simply dummy text of the printing
                                                            and typesetting industry.
                                                            Lorem Ipsum has been the industry's standard
                                                            dummy text ever since the 1500s, when an
                                                            unknown printer took a galley of type and
                                                            scrambled it to make a type specimen book.
                                                            It has survived not only five centuries,
                                                            but also the leap into electronic typesetting,
                                                            remaining essentially unchanged.
                                                            It was popularised in the 1960s with the release of
                                                            Letraset sheets containing Lorem Ipsum passages,
                                                            and more recently with desktop publishing software
                                                            like Aldus PageMaker including versions of Lorem Ipsum.""")
            
            w = QWidget()
            v  = QVBoxLayout()
            v.addWidget(self.lineEdit)
            v.addWidget(self.textEdit)
            w.setLayout(v)
            self.setCentralWidget(w)
    
            self.lineEdit.returnPressed.connect(self.find_word)
    
        def appendExtraSelection(self, tc):
            
                ex = QTextEdit.ExtraSelection()            
                ex.cursor = tc
                ex.format.setForeground(QBrush(Qt.blue))
                ex.format.setBackground(QBrush(Qt.yellow))
                self.extraSelections.append(ex)
     
                
        def find_word(self):
            
            self.extraSelections.clear()    
            doc = self.textEdit.document()
            self.find_recursion(0)
            self.textEdit.setExtraSelections(self.extraSelections)
                
        def find_recursion(self, pos):
    
            doc = self.textEdit.document()
            tc = doc.find(self.lineEdit.text(), pos)
            if not tc.isNull():
                self.appendExtraSelection(tc)
                self.find_recursion(tc.selectionEnd())
    
    
         
        
            
    def main():
    
        app = QApplication([])
        w = MainWindow()
        w.show()
        sys.exit(app.exec())
    
    if __name__ == "__main__":
        main()
    
    1. To use find function of QTextDocument.
    2. To set QTextEdit.ExtraSelection for highlighting text.
    3. To use find function as recursion to search for all target texts.

    enter image description here