1. 程式人生 > >Qt+QML+Html的開發模式.

Qt+QML+Html的開發模式.

不多說,直接上程式碼.

1.QT.pro檔案配置

QT += qml quick webengine

2.QML檔案

import QtQuick 2.5
import QtQuick.Window 2.2
import QtWebEngine 1.4
import QtQuick.Controls 2.0
import QtWebSockets 1.1

Window {
    visible: true
    width: 1500
    height: 900
    title: qsTr("Hello World")

    WebEngineView {
        id: eCharts
        anchors.fill: parent
        url: "qrc:/index.html"
        Component.onCompleted: {

        }
    }

    //建立websocket服務物件.
    WebSocketServer {
        id: server
        port: 12335
        listen: true
        onClientConnected: {
            webSocket.onTextMessageReceived.connect(function(message) {
                console.log((qsTr("Server received message: %1").arg(message)));
                webSocket.sendTextMessage(qsTr("Hello html!"));
            });
        }
        onErrorStringChanged: {
            console.log(qsTr("Server error: %1").arg(errorString));
        }

    }

    Button{
        id:btFunc
        text: "PressMe"
        anchors.bottom:eCharts.bottom
        onClicked: {
            //呼叫html上面的方法sayHelloFromQML,回撥函式接收返回值result
            eCharts.runJavaScript("window.sayHelloFromQML(\""+"Hello HTML"+"\")",
                                  function(result) {
                                      console.log(result);
                                  }
                    );
        }
    }

}

3.Html檔案

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1 user-scalable=0">
    <title>Qt+QML+HTML</title>

</head>
<body>

    <button onClick="sendMsgToQML()">hello qml</button>

    <script type="text/javascript">
        if ("WebSocket" in window)
        {

        }else{
            alert("您的瀏覽器不支援 WebSocket!");
        }
        // 開啟一個 web socket
        var ws = new WebSocket("ws://localhost:12335/echo");

        ws.onopen = function()
        {
           // Web Socket 已連線上,使用 send() 方法傳送資料
           alert("websocket已連線...");
        };

        ws.onmessage = function (evt)
        {
           var received_msg = evt.data;
           alert("資料已接收..."+received_msg);
        };

        ws.onclose = function()
        {
           // 關閉 websocket
           alert("連線已關閉...");
        };

        //定義函式傳送資料給QML
        function sendMsgToQML(){
            ws.send("Hello QML");
        }

        //定義函式給QML呼叫
        function sayHelloFromQML(msg){
            alert(msg)
            return "sayHelloToQML"
        }

    </script>
</body>
</html>