【问题标题】:PyQt (PySide), WebKit and exposing methods from/to JavascriptPyQt (PySide)、WebKit 以及从/向 Javascript 公开方法
【发布时间】:2011-06-22 21:54:14
【问题描述】:

我打算使用 PyQt 来控制服务器端的嵌入式 WebKit 浏览器。

在 WebKit 中运行的 HTML 页面中,我在 Javascript 中有一些继承应用程序逻辑。

如何从宿主进程(Python、PyQt)与 Javascript 进行通信,以便

  • 我可以在页面内调用Javascript函数

  • Python 方法暴露给 Javascript,可以从 Javascript 调用,带参数

【问题讨论】:

    标签: javascript python webkit pyqt pyside


    【解决方案1】:

    以下源代码应该会有所帮助:

    import sys
    from PyQt4.QtCore import QObject, pyqtSlot
    from PyQt4.QtGui import QApplication
    from PyQt4.QtWebKit import QWebView
    
    html = """
    <html>
    <body>
        <h1>Hello!</h1><br>
        <h2><a href="#" onclick="printer.text('Message from QWebView')">QObject Test</a></h2>
        <h2><a href="#" onclick="alert('Javascript works!')">JS test</a></h2>
    </body>
    </html>
    """
    
    class ConsolePrinter(QObject):
        def __init__(self, parent=None):
            super(ConsolePrinter, self).__init__(parent)
    
        @pyqtSlot(str)
        def text(self, message):
            print message
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        view = QWebView()
        frame = view.page().mainFrame()
        printer = ConsolePrinter()
        view.setHtml(html)
        frame.addToJavaScriptWindowObject('printer', printer)
        frame.evaluateJavaScript("alert('Hello');")
        frame.evaluateJavaScript("printer.text('Goooooooooo!');")
        view.show()
        app.exec_()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-13
      • 2018-03-17
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      相关资源
      最近更新 更多