python-3.x - PySide/PyQt : Is it possible to make strings that you attach to the QTextBrowser separate clickable units

标签 python-3.x pyqt pyside 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_())

任何 URL 以“some_special_identifier://”开头的链接都将被选中,后面的文本将用于查找和调用同名的函数。请注意,这可能有点冒险,因为如果用户可以控制 TextBrowser 中显示的内容,则可能会调用您可能不希望调用的各种函数。最好只允许某些功能运行,并且可能只在特定时间运行。这当然由您来执行!

附注我的代码是为 Python 2.7 编写的(我看到您正在使用 Python 3)。因此,我认为您至少需要将 print 'text' 更改为 print('text')!

关于python-3.x - PySide/PyQt : Is it possible to make strings that you attach to the QTextBrowser separate clickable units,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19454113/

相关文章:

Python:从列表中删除特定项目的重复项

如果我去 bash 然后 tcsh (anaconda),则 Python3 只在 tcsh 中打开

python - (Pyqt : Spacing in QHBoxLayout shows centralwidget's background, 不是 parent

python - PySide 节点图连接项

python - PySide 中类似终端的应用程序

python-3.x - 在Python中使用Geckodriver和Selenium警告: use setter for headless property instead of set_headless opts. set_headless(headless = True)

python-3.x - 如何让 Python "import.util.module_from_spec"更像 "import"”?

qt - 如何获取自动换行后标签的大小(高度)

python - 如何在PyQt中保存 'jpeg'格式的Qimage?

python - Pyside 改变 QIcon 中 SVG 的颜色或不透明度