在 QTextDocument 中单击 Link 时生成自定义事件

Generate Custom Event on Clicking Link in QTextDocument

有没有一种方法可以在我们单击 QTextEdit 中添加的 QTextDocument 中的 link 时生成自定义事件。我目前能够使用 QTextCursor class 的 insertHtml() 函数创建 Link,但是 link 不可点击。

如果您知道如何在单击 QTextDocument 中的 link 时生成自定义事件,请分享。谢谢

QTextDocument 不是可视元素,而是存储格式化的信息,因此点击的概念与它无关,而是与小部件有关。

这里以QTextEdit为例,你必须重写mousePressEvent方法,使用anchorAt方法才能知道是否有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://whosebug.com" >Whosebug</a>!!!')

    def on_clicked(url):
        QtGui.QDesktopServices.openUrl(url)

    w.clicked.connect(on_clicked)
    w.show()
    sys.exit(app.exec_())

尽管 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://whosebug.com" >Whosebug</a>!!!')

    def on_clicked(url):
        QtGui.QDesktopServices.openUrl(url)

    w.anchorClicked.connect(on_clicked)
    w.show()
    sys.exit(app.exec_())