3

I am using Qt 5.7 QWebEngineView.

How to connect HTML button click event to a Q_SLOT on C++/PyQt5 side?

I can't find a clear example on this.

Mohamed Anwer
  • 172
  • 2
  • 15

1 Answers1

5

I created a bridge QObject, The mistake I ran into while implementing this class, was that I forgot to add @QtCore.pyqtSlot decorator, and it was important.

class Bridge(QtCore.QObject):
    @QtCore.pyqtSlot()
    def some_slot():
        print("Slot Invoked")

Here I created a QWebEngineView and a QWebChannel and set the web channel of the QWebEnginePage to be that channel and vice versa.

Then I created my Bridge QObject self.helper_bridge at first I didn't use self and just used helper_bridge by its own, and of course this made my app crash

class MainWidget(object):
    def __init__(self):
        ...
        self.webView = QtWebEngineWidgets.QWebEngineView(parent)

        channel = QtWebChannel.QWebChannel(self.webView.page())
        self.webView.page().setWebChannel(channel)

        self.helper_bridge = Bridge()
        channel.registerObject("helperBridge", self.helper_bridge)

        url = QtCore.QUrl("file:///path/to/index.html")
        self.webView().page().load(url)
        ...

At last, the index.html page,

Pay attention to the second script which is provided by Qt.

Here I created an instance of QWebChannel given my transport: qt.webChannelTransport, and inside the callback I handled the click event binding as you can see.

<html>                                                                          
    <head>                                                                        
    </head>                                                                       
    <body>                                                                        
        <script src='https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js'</script>
        <script src='qrc:///qtwebchannel/qwebchannel.js'></script>
      <h1>hello</h1>                                         
      <ul>                                                   
          <li>list item 1</li>                                                      
          <li>list item 2</li>                                                      
      </ul>                                                                       
      <a href='#go'>GO</a>                                                      
      <script>                                                                    
        $(document).ready(function(){
            new QWebChannel(qt.webChannelTransport, function(channel){            
                $('h1').on('click', function({
                    channel.objects.helperBridge.some_slot()
                });
            });
        });                                                                       
      </script>
  </body>

References:

Community
  • 1
  • 1
Mohamed Anwer
  • 172
  • 2
  • 15