简体   繁体   中英

PyQt5 - How to display a clickable hyperlink in QTextBrowser

I have created a GUI with PyQt5. Now I would like to add hyperlinks to a QTextBrowser . Unfortunately, the texts are not clickable but instead displayed as normal text and I have a hard time finding out why.

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QTextBrowser

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.text_browser = QTextBrowser()
        self.text_browser.setOpenExternalLinks(True)
        self.text_browser.setReadOnly(True)
        self.text_browser.append("<a href=https://google.com/>Google</a>")
        self.text_browser.append("<a href=https://github.com/>Github</a>")

        layout = QVBoxLayout()
        layout.addWidget(self.text_browser)
        self.setLayout(layout)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    app.exec_()

GUI without links

The HTML parser used by Qt is elementary compared to those of a standard web browser, so a more standard syntax is preferred.

While it's open to debate whether this is a bug or not, it's always better to use quotes around HTML attributes.

    self.text_browser.append("<a href='https://google.com/'>Google</a>")
    self.text_browser.append("<a href='https://github.com/'>Github</a>")

Note: QTextBrowser is already read only by default, there's no need to set that option.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM