PyQt (PySide)、WebKit 和从/向 Javascript 公开方法 [英] PyQt (PySide), WebKit and exposing methods from/to Javascript

查看:125
本文介绍了PyQt (PySide)、WebKit 和从/向 Javascript 公开方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am planning to use PyQt to control an embedded WebKit browser on the server side.

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

I have some inherit application logic in Javascript in the HTML page running inside WebKit.

我如何从主机进程(Python、PyQt)使用 Javascript 进行通信,以便

How could I communicate from the host process (Python, PyQt) with Javascript, so that

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

  • I can call Javascript functions inside the page

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

Python methods are exposed to Javascript and can be called from the Javascript, with arguments

推荐答案

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

The following source code should be helpful:

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_()

这篇关于PyQt (PySide)、WebKit 和从/向 Javascript 公开方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆