【问题标题】:PySide/PyQt: Is it possible to make strings that you attach to the QTextBrowser separate clickable unitsPySide/PyQt:是否可以将附加到 QTextBrowser 的字符串作为单独的可点击单元
【发布时间】:2013-10-18 16:05:56
【问题描述】:

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

当你将一个给定的字符串附加到一个 QTextBrowser 对象时,你能把它作为一个信号链接到一个函数,该函数接受它的文本并用它做一些事情吗?我所需要的只是将文本实际保存到变量中。

如中所示,链接可以指向功能而不是网站。

【问题讨论】:

    标签: python-3.x pyqt pyside qtextbrowser


    【解决方案1】:

    这当然是可能的。

    这是一个代码示例:

    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')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-16
      • 2022-01-03
      相关资源
      最近更新 更多