这可能是一个愚蠢的问题但是:
当你将一个给定的字符串附加到一个QTextBrowser对象时,你可以把它作为一个信号的链接到一个函数,该函数接受它的文本并用它做一些事情吗?我只需要将文本实际保存到变量中。
如同,链接可以导致功能而不是网站。
答案 0 :(得分:4)
当然有可能。
这是一个代码示例:
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://”开头的网址的链接都将被选中,之后的文本将用于查找并调用相同名称的函数。请注意,这可能有点冒险,因为如果用户可以控制TextBrowser中显示的内容,则可能会调用各种函数,这可能是您不想要的。最好只允许运行某些函数,也许只在某些时候运行。这当然取决于你执行!
P.S。我的代码是为Python 2.7编写的(我看到你使用的是Python 3)。所以我认为您至少需要将print 'text'
更改为print('text')
!