Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PyQt QtWebChannel: calling Python function from JavaScript

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.

like image 223
MrLoon Avatar asked Mar 21 '18 21:03

MrLoon


1 Answers

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>
like image 105
eyllanesc Avatar answered Oct 23 '22 04:10

eyllanesc