pythonpython-3.xpyqtpyqt5qtextdocument

Generate Custom Event on Clicking Link in QTextDocument


Is there a way that we can generate a custom event when we click on link inside QTextDocument which is added in QTextEdit. I'm currently able to create Link using insertHtml() function of QTextCursor class but that link is not clickable.

If you know something how to generate custom event on clicking link in QTextDocument please share. Thanks


Solution

  • QTextDocument is not a visual element but stores the information formatted so the concept of clicked has nothing to do with it but with a widget.

    In this case I will use QTextEdit as an example, you must override the mousePressEvent method and use the anchorAt method to know if there is an anchor(url):

    import sys
    
    from PyQt5 import QtCore, QtGui, QtWidgets
    
    
    class TextEdit(QtWidgets.QTextEdit):
        clicked = QtCore.pyqtSignal(QtCore.QUrl)
    
        def mousePressEvent(self, event):
            anchor = self.anchorAt(event.pos())
            if anchor:
                self.clicked.emit(QtCore.QUrl(anchor))
            super().mousePressEvent(event)
    
    
    if __name__ == "__main__":
        app = QtWidgets.QApplication(sys.argv)
        w = TextEdit()
        w.append('Welcome to <a href="https://stackoverflow.com" >StackOverflow</a>!!!')
    
        def on_clicked(url):
            QtGui.QDesktopServices.openUrl(url)
    
        w.clicked.connect(on_clicked)
        w.show()
        sys.exit(app.exec_())
    

    Although that same functionality already has QTextBrowser:

    import sys
    
    from PyQt5 import QtCore, QtGui, QtWidgets
    
    
    if __name__ == "__main__":
        app = QtWidgets.QApplication(sys.argv)
        w = QtWidgets.QTextBrowser()
        w.append('Welcome to <a href="https://stackoverflow.com" >StackOverflow</a>!!!')
    
        def on_clicked(url):
            QtGui.QDesktopServices.openUrl(url)
    
        w.anchorClicked.connect(on_clicked)
        w.show()
        sys.exit(app.exec_())