11

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

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

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

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

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

4

1 回答 1

28

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

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_()
于 2011-06-24T20:31:36.190 回答