title: PyQt QtWebChannel: calling Python function from JavaScript
body: <p>I am trying, using Qt classes <code>QWebEngineView</code>, and <code>QWebChannel</code> to make a simple connection between HTML page and Python script. The goal is simply to execute <code>foo()</code> when the header <code>&lt;h2&gt;</code> is clicked. </p>
  
  <pre><code>import sys
  from PyQt5.QtCore import pyqtSlot
  from PyQt5.QtWidgets import QApplication
  from PyQt5.QtWebChannel import QWebChannel
  from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage
  
  html = '''
  &lt;!DOCTYPE html&gt;
  &lt;html&gt;
  &lt;head&gt;
      &lt;meta charset="utf-8"/&gt;        
      &lt;script src="qrc:///qtwebchannel/qwebchannel.js"&gt;&lt;/script&gt;
      &lt;script&gt;
      var backend;
      new QWebChannel(qt.webChannelTransport, function (channel) {
          backend = channel.objects.backend;
      });
  
      document.getElementById("header").addEventListener("click", function(){
          backend.foo();
      });
      &lt;/script&gt;
  &lt;/head&gt;
  &lt;body&gt; &lt;h2 id="header"&gt;Header.&lt;/h2&gt; &lt;/body&gt;
  &lt;/html&gt;
  '''
  
  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_()
  </code></pre>
  
  <p>The problem seems to be that the variable <code>backend</code> is not <em>visible</em> outside of the <code>QWebChannel</code> constructor. I tried to make <code>backend</code> an attribute of <code>widnow</code> to make it <em>global</em> but it did not work.</p>