js端:
<html> <head> <title>测试与js交互</title> <script src="qwebchannel.js"></script> //QWebEngineView需要引用该资源 <script language="JavaScript"> window.onload = function() { new QWebChannel(qt.webChannelTransport, function(channel) { // 获取Qt类交互对象 var interactObject = channel.objects.interactObject; // 链接Qt类信号函数 window.foo = interactObject; }); } //判断系统类型 function isMac() { return /macintosh|mac os x/i.test(navigator.userAgent); } function setCutScreen() { if(isMac()) { foo.CutScreen(); //调用QWebEngineView浏览器 } else { window.CutScreen(); //调用cef浏览器 } } function setNoCutScreen() { if(isMac()) { foo.NoCutScreen(); } else { window.NoCutScreen(); } } function close() { if(isMac()) { foo.CloseClient(); } else { window.CloseClient(); } } </script> </head> <body> <form> <input type="button" onclick="setCutScreen();" value="不霸屏"> <input type="button" onclick="setNoCutScreen();" value="霸屏"> <input type="button" onclick="CloseClient();" value="关闭"> </form> </body> </html>
客户端:
//C++对象 class InteractObject : public QObject { Q_OBJECT public slots: void CutScreen() { QMessageBox::information(nullptr,"","CutScreen()"); } }; InteractObject *interactObject = new InteractObject(); QWebChannel *channel = new QWebChannel(this); //QWebChannel 对象 channel->registerObject("interactObject", interactObject); //将interactObject注册到QWebChannel对象中 view->page()->setWebChannel(channel); //WebEngineView下的page设置channel