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

问题描述:

我用PyQt5创建了一个GUI.现在,我想将超链接添加到 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

与标准Web浏览器相比,Qt使用的HTML解析器是基本的,因此首选标准语法.

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

尽管可以就是否存在bug进行辩论,但最好在HTML属性周围使用引号.

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>")

注意:默认情况下,QTextBrowser只读,因此无需设置该选项.