PySide/PyQt:是否可以将附加到QTextBrowser的字符串设置为单独的可点击单元



这可能是一个愚蠢的问题,但是:

当您将给定的字符串附加到 QTextBrowser 对象时,您能否使它成为指向函数信号的链接,该函数获取其文本并对其执行某些操作?我所需要的只是让它实际上将文本保存到变量中。

例如,链接可以指向功能而不是网站吗?

这当然是可能的。

下面是一个代码示例:

import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
class MainWindow(QtGui.QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        main_layout = QtGui.QVBoxLayout()
        self.browser = QtGui.QTextBrowser()
        self.browser.setHtml('''<html><body>some text<br/><a href="some_special_identifier://a_function">click me to call a function</a><br/>
        <a href="#my_anchor">Click me to scroll down</a><br>foo<br>foo<br>foo<br>foo<br>foo<br>foo<br>
        foo<a id="my_anchor"></a><br>bar<br>bar<br>bar<br>bar<br>bar<br>bar<br>hello!<br>hello!<br>hello!<br>hello!<br>hello!<br>hello!<br>hello!<br>hello!</body></html''')
        self.browser.anchorClicked.connect(self.on_anchor_clicked)
        main_layout.addWidget(self.browser)
        self.setLayout(main_layout)
    def on_anchor_clicked(self,url):
        text = str(url.toString())
        if text.startswith('some_special_identifier://'):
            self.browser.setSource(QtCore.QUrl()) #stops the page from changing
            function = text.replace('some_special_identifier://','')
            if hasattr(self,function):
                getattr(self,function)()
    def a_function(self):
        print 'you called?'
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())

任何具有以"some_special_identifier://"开头的 url 的链接都将被拾取,之后的文本将用于查找和调用同名函数。请注意,这可能会有点风险,因为如果用户可以控制 TextBrowser 中显示的内容,则可能会调用您可能不希望调用的各种函数。最好只允许运行某些函数,也许只允许在特定时间运行。这当然取决于你来执行!

附言我的代码是为Python 2.7编写的(我看到你使用的是Python 3)。所以我认为你至少需要将print 'text'更改为print('text')

最新更新