python - 如何为 href 指定方法名称?

标签 python hyperlink pyqt qlabel qtextbrowser

我有一个 QTextBrowser() 对象:

self.PAddressLink = QTextBrowser()

我需要单击此 QTextBrowser 上的链接,它应该打开一个新对话框。

self.PAddressLink.setHtml("<html><body><a href=#>+Add Permanent Address</a></body></html>")

无论如何,我都可以使用以下代码打开新窗口:

self.PAddressLink.anchorClicked.connect(self.AddPAddress) #self.AddPAddress is the method of displaying a dialog box.

但我需要知道是否可以将 self.AddPAddress 放在 href 中并避免使用以下额外语句:

self.PAddressLink.anchorClicked.connect(self.AddPAddress) #self.AddPAddress 

最佳答案

假设所有方法都定义在同一个对象上(例如 self),您可以在 href 属性中设置方法名称:

self.PAddressLink.setHtml('<a href="AddPAddress">...</a>')
self.PAddressLink.anchorClicked.connect(self.handleLink)

然后使用 getattr调用方法:

def handleLink(self, url):
    if url.scheme():
        # handle normal urls here if necessary...
    else:
        getattr(self, url.toString())()
<小时/>

这是使用 QLabelQTextBrowser 的完整演示:

screenshot

from PyQt5 import QtCore, QtGui, QtWidgets

html = """
<p><a href="https://www.google.com">Url Link</a></p>
<p><a href="myMethod">Method Link</a></p>
"""

class Window(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        self.label = QtWidgets.QLabel(html)
        self.browser = QtWidgets.QTextBrowser()
        self.browser.setOpenLinks(False)
        self.browser.setHtml(html)
        layout = QtWidgets.QVBoxLayout(self)
        layout.addWidget(self.browser)
        layout.addWidget(self.label)
        self.label.linkActivated.connect(self.handleLink)
        self.browser.anchorClicked.connect(self.handleLink)

    def handleLink(self, url):
        url = QtCore.QUrl(url)
        if url.scheme():
            # handle real urls
            QtGui.QDesktopServices.openUrl(url)
        else:
            # handle methods
            getattr(self, url.toString())()

    def myMethod(self):
        QtWidgets.QMessageBox.information(self, 'Test', 'Hello World!')

if __name__ == '__main__':

    app = QtWidgets.QApplication(['Test'])
    window = Window()
    window.setGeometry(600, 100, 300, 200)
    window.show()
    app.exec()

关于python - 如何为 href 指定方法名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28146230/

相关文章:

python - 有没有办法让 ConfigParser 'not' 返回列表

python - 在python中对两个列表进行排序?

python3 - 使用 socket.send() 时出现管道错误

python - Scrapy:使用正则表达式跟踪链接

python - 如何让 PyQt4 与 PyCharm 一起工作

Python BeautifulSoup 提取字体标签的内容

javascript - 如何在悬停时指定图像的位置

html - 链接到网页的特定部分

python - pyqt5主窗口内弹出自定义对话框输入

python - PyQt、PyOPENGL : when adding a texture to an area, 然后其他区域失去颜色并变成白色