2016-11-26 35 views

回答

2

我创建了一个桥QObject,我在实现这个类时遇到的错误是我忘了添加@QtCore.pyqtSlot装饰器,这很重要。

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

在这里,我创建了一个QWebEngineViewQWebChannel并设置QWebEnginePage的Web信道为信道,并且反之亦然。

然后我创造了我的QObject桥在self.helper_bridge第一我没有用self,只是通过其自身的使用helper_bridge,当然这让我的应用程序崩溃

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) 
     ... 

最后,index.html页,

请注意Qt提供的第二个脚本。

在这里,我创建了一个QWebChannel实例给予我的传输:qt.webChannelTransport,并在回调中我处理了点击事件绑定,你可以看到。

<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> 

参考文献: