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

How can I do something when the user clicks on a specific part of the text in a QTextEdit?



  • How can I do something when the user clicks on a specific part of the text in a QTextEdit? I can't figure it out..

    I've tried:

    def addmsg(textedit, nick, message):
       textedit.cursor.insertText("<")
       nickframe = textedit.cursor.insertFrame(QTextFrameFormat())
       nickframe.nick = nick
       framecursor = nickframe.firstCursorPosition()
       framecursor.insertText(nick)
       textedit.cursor.insertText("> ")
       colorify(textedit, message)
       textedit.cursor.insertHtml("<br>")
    

    and then, in the QTextEdit subclass..

    def mousePressEvent(self, e):
        print(f"{getattr(self.cursorForPosition(e.pos()).currentFrame(), 'nick', None)=}")
        print(f"{self.cursorForPosition(e.pos()).position()=}")
        print(f"{self.cursorForPosition(e.pos()).currentFrame()=}")
        print(f"{self.cursorForPosition(e.pos()).currentFrame().document().toPlainText()=}")
        print(f"{getattr(self.cursor.currentFrame(), 'nick', None)=}")
        print(f"{self.cursor.position()=}")
    

    but there's two problems with this. one, self.cursorForPosition(e.pos()).currentFrame().document().toPlainText() always returns the whole document text, not the specific frame i'm trying to click on, and, of course, {getattr(self.cursor.currentFrame(), 'nick', None) is always None, and two, where I insert the frame it creates a newline, which I need it not to do.

    I also tried:

    class TextFragment(QTextDocumentFragment):
      def __init__(self, textdocument):
        QTextFragment.__init__(self, textdocument)
      def event(self, e):
        print(f"{e.type=}")
        
    def addmsg(textedit, nick, message):
      if config.show_timestamp:
        obj_now = datetime.now()
        textedit.insertPlainText(f"[{obj_now.hour: >2}:{obj_now.minute: >2}] ")
      textedit.cursor.insertText("<")
      nickdoc = TextFragment(QTextDocument(nick, textedit))
      nickdoc.nick = nick
      textedit.cursor.insertFragment(nickdoc)
      textedit.cursor.insertText("> ")
      colorify(textedit, message)
      textedit.cursor.insertHtml("<br>")
    

    but, as i expected, the event function apparently isn't triggered when I click on the text fragment.

    I don't know what else to try.. Thanks.


Log in to reply