基於QML的WebEngineView的Html與C++通信

WebEngineView

如果你使用WebView那麼可以看之前的文章通過封裝的WebSocket通信;
使用WebEngineView當然也可以,不過略顯麻煩,畢竟有了WebChannel;

利用Webchannel 實現Html 與C++相互調用
調用C++交給QMl來完成,從而間接實現;
如果用socket 可以做到直接通信;

        WebEngineView {
            id:view
            width:parent.width
            height:parent.height-control.height
            url: "qrc:/Html/Login.html"
            webChannel: channel.channelId
        }

封裝的WebChannel

  JHWebChannel{
            id:channel

            transportName:"socket"

			////接收html傳來的json
            onReceivedMessage: {
					dealMsg(msg);
            }
	}


/////通知Html  

channel.sendMessage(msg);


接收Html消息處理:
function delaMsg(msg){
     var nnn=JSON.parse(msg);
       var index=parseInt(nnn.Code);

        switch(index){
                case 101:
                    view.url="qrc:/Html/Test.html";
                    if(nnn.Data.name==="[email protected]"&&nnn.Data.pass==="123"){
                            view.url="qrc:/Html/Test.html";
                    }
                    break;

                case 102:
                     var sindex=parseInt(nnn.Data.openPath);

                     switch(sindex){
                     case 1:case 2:case 3:case 4:case 5:console.log("openPath:"+sindex);break;
                     }
                     break;
         }
}

JHWebChannel

Item{

    property alias transportId: obj
    property alias channelId: channel
    property string transportName: "chanel"
    signal receivedMessage(string msg);
    width:0
    height:0
    function sendMessage(msg){
        obj.notifyHtml(msg);
    }

    QtObject{
        id: obj
        WebChannel.id: transportName

        signal notifyHtml(string message);

        function notifyQML(newText) {
           receivedMessage(newText);
        }
    }

    WebChannel {
        id: channel
        registeredObjects: [obj]
    }
}

HTML

引入JS

<script type="text/javascript" src="qrc:///Html/qwebchannel.js"></script>

<script type="text/javascript" src="qrc:///Html/Base.js"></script>

添加腳本:
在這裏插入圖片描述

Base.js

function notify(flag,data){
    if(socket){
     var dd=JSON.stringify({"Code":flag,"Data":data});
      socket.notifyQML(dd);
    }
};

function initChannel (callback){
   new QWebChannel(qt.webChannelTransport,function(channel){
    socket = channel.objects.socket;

    socket.notifyHtml.connect(function (message) { 
        callback(message);
    });

    });

  rturn socket;
};



界面

在這裏插入圖片描述

登錄成功:

模板實在網上下載的http://demo.cssmoban.com/cssthemes4/cttp_16_x_lbd/dashboard.html
在這裏插入圖片描述
在這裏插入圖片描述

在這裏插入圖片描述

注意

資源文件Html/CSS/Image/JS 都可以添加到qrc中,這樣會被直接編譯到exe中

改天整理一份Android 端基於X5瀏覽器內核 的C++與Html 通信;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章