pythonhyperlinkpyqtpyqt5qplaintextedit

PyQt5 QPlainTextEdit make hyperlinks


We are a chat application in python using PyQt5 but we hit a roadblock while trying to make hyperlinks clickable in our QPlainTextEdit which we use for our chatbox. Our output is just a plain html tag without highlighting.

        chatbox = QPlainTextEdit()
        chatbox.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        chatbox.setReadOnly(True)
        chatbox.setBackgroundVisible(False)
        chatbox.setStyleSheet("""
        QPlainTextEdit{
            background: rgba(255, 255, 255, 0.5);
        }
        """)
        chatbox.setMaximumHeight(650)
        chatbox.setMaximumWidth(self.screenShape.width()-50)

    def handleMessage(self):
        try:
            message = self.chatline.text()
            if message == "":
                pass
            else:
                if message.startswith('http://') or message.startswith('https://'):
                    message = f'<a href=""{message}>{message}</a>'
                    message = f"{username}: {message}"
                    message.encode("utf-8")
                    s.sendall(message.encode())
                    self.chatline.setText("")
                    chatbox.linkActivated.connect(self.link)
                    chatWidget.update()
                    
                else:
                    message = f"{username}: {message}"
                    message.encode("utf-8")
                    s.sendall(message.encode())
                    self.chatline.setText("")
                    chatWidget.update()

        except:
            pass
    
    def link(self, linkStr):
        QDesktopServices.openUrl(QUrl(linkStr))

Solution

  • Try to use QTextEdit instead QPlainTextEdit and setAcceptRichText to True