简体   繁体   English

PyQt5 - 如何在 QTextBrowser 中显示可点击的超链接

[英]PyQt5 - How to display a clickable hyperlink in QTextBrowser

I have created a GUI with PyQt5.我用 PyQt5 创建了一个 GUI。 Now I would like to add hyperlinks to a QTextBrowser .现在我想将超链接添加到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无链接的 GUI

The HTML parser used by Qt is elementary compared to those of a standard web browser, so a more standard syntax is preferred.与标准的 web 浏览器相比,Qt 使用的 HTML 解析器是基本的,因此首选更标准的语法。

While it's open to debate whether this is a bug or not, it's always better to use quotes around HTML attributes.虽然这是否是一个错误还有待商榷,但最好在 HTML 属性周围使用引号。

    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.注意:QTextBrowser 已经默认为只读,无需设置该选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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