Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Dynamic change of font color in QTextEdit



  • I want to change the color of font basing on the user input.
    More precisely, if a user gives a certain word, I want only this word to be red and leave the rest of text with the same color.

    I was thinking to interpret every given character and if the pattern matches, do the following:

    # to move the cursor to the beginning of given input pattern
    self.textEdit.moveCursor(QTextCursor.End - 3)
    responseStyle = "<span style=\"  color:" + RESPONSE_COLOR + ";\" >"
    # change the style
    self.textEdit.insertHtml(responseStyle)
    self.textEdit.moveCursor(QTextCursor.End)
    # end the changed style section
    self.textEdit.insertHtml("</span>")
    

    However, the color doesn't change.
    Does anyone have an idea how to solve it?



  • @Anichka
    Looks to me like it should work. Start by debugging out the whole of self.textEdit.text.toHtml() after the last line of your code so we can verify what is in there.


  • Lifetime Qt Champion

    Hi,

    Sounds a bit like you need QSyntaxHighlighter.


Log in to reply