Search code examples
pythonpyqt5highlightqtextedit

How to darken selected text of `textEdit.find()` in PyQt5?


I have this method that finds a term in a textEdit:

def search(self, term, case_sensitive=False):
    self.textedit.moveCursor(qtg.QTextCursor.Start)
    if case_sensitive:
        cur = self.textedit.find(
            term,
            qtg.QTextDocument.FindCaseSensitively
        )
    else:
        cur = self.textedit.find(term)
    if not cur:
        self.statusBar().showMessage('No matches Found', 2000)

Now the function is working properly but the textedit.find(term) seems to just lightly highlight the found text like this

My question is if textedit.find(term) can select the found text like this


Solution

  • You have to change the color associated with QPalette::Highlight:

    p = self.textedit.palette()
    p.setColor(qtg.QPalette.Highlight, QColor("blue"))
    self.textedit.setPalette(p)