PyQt QtWebChannel: calling Python function from JavaScript

强颜欢笑 提交于 2021-02-04 04:49:55

问题


I am trying, using Qt classes QWebEngineView, and QWebChannel to make a simple connection between HTML page and Python script. The goal is simply to execute foo() when the header <h2> is clicked.

import sys
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QApplication
from PyQt5.QtWebChannel import QWebChannel
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage

html = '''
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>        
    <script src="qrc:///qtwebchannel/qwebchannel.js"></script>
    <script>
    var backend;
    new QWebChannel(qt.webChannelTransport, function (channel) {
        backend = channel.objects.backend;
    });

    document.getElementById("header").addEventListener("click", function(){
        backend.foo();
    });
    </script>
</head>
<body> <h2 id="header">Header.</h2> </body>
</html>
'''

class HelloWorldHtmlApp(QWebEngineView):

    def __init__(self):
        super().__init__()

        # setup a page with my html
        my_page = QWebEnginePage(self)
        my_page.setHtml(html)
        self.setPage(my_page)

        # setup channel
        self.channel = QWebChannel()
        self.channel.registerObject('backend', self)
        self.page().setWebChannel(self.channel)
        self.show()

    @pyqtSlot()
    def foo(self):
        print('bar')


if __name__ == "__main__":
    app = QApplication.instance() or QApplication(sys.argv)
    view = HelloWorldHtmlApp()
    view.show()
    app.exec_()

The problem seems to be that the variable backend is not visible outside of the QWebChannel constructor. I tried to make backend an attribute of widnow to make it global but it did not work.


回答1:


The problem is not the visibility but the connection with the click event, the upload of the file is from top to bottom so you are trying to connect the header when it does not yet exist, the solution is to rewrite the HTML:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8"/>        
        <script src="qrc:///qtwebchannel/qwebchannel.js"></script>
    </head>
    <body> <h2 id="header">Header.</h2> </body>
    <script>
        var backend;
        new QWebChannel(qt.webChannelTransport, function (channel) {
            backend = channel.objects.backend;
        });

        document.getElementById("header").addEventListener("click", function(){
            backend.foo();
        });
    </script>
</html>


来源:https://stackoverflow.com/questions/49416790/pyqt-qtwebchannel-calling-python-function-from-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!