QML 与h5 通信

一,场景

公司有多端需求,安卓,ios ,web,pc。  web用h5开发的页面,比如登陆页面 在复用的情况下会节省很多开发工作。

二,解决办法

利用QML WebEngineView 与  WebChannel  实现QML 与h5 的通信。

 

(1),定义 h5中需要调用的方法

#ifndef SAGE_H
#define SAGE_H

#include <QObject>

class QMLHtmlOb : public QObject
{
    Q_OBJECT
public:
    explicit QMLHtmlOb(QObject *parent = 0);
    Q_INVOKABLE void sendMsg(int index,QString msg);

    Q_INVOKABLE void setUser(QString str);
    Q_INVOKABLE void setCourse(QString str);

signals:
    void sendMsgChanged(int index,QString msg);

    void userChanged(const QString str);
    void courseChanged(const QString str);

private:
    QString m_msgFromHtml;
};

#endif // SAGE_H


#include "qmlHtml.h"
#include <QDebug>
QMLHtmlOb::QMLHtmlOb(QObject *parent)
    : QObject(parent)
{ }

void QMLHtmlOb::sendMsg(int index,QString msg)
{
    emit sendMsgChanged(index,msg);
}


void QMLHtmlOb::setUser(QString str)
{
    qDebug()<<"setUser"<<str;
    emit userChanged(str);
}

void QMLHtmlOb::setCourse(QString str)
{
    qDebug()<<"setCourse"<<str;
    emit courseChanged(str);
}

(2),qml文件

import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
import QtWebChannel 1.0
import QtWebEngine 1.1

import QMLHtmlOb 1.0

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("WebChannel QML Example")

    QMLHtmlOb {
        id: qmlHtmlOb
        WebChannel.id: "qmlHtmlOb"
        onUserChanged: {
            console.log("onUserChanged")
            textArea.append(str)
        }
        onCourseChanged: {
            console.log("onCourseChanged")
            textArea.append(str)
        }
    }

    Rectangle{
        anchors.left: parent.left
        anchors.top: parent.top
        anchors.bottom: parent.bottom
        width: parent.width/2
        border.color: "red"
        WebEngineView {
            id: webview
            anchors.fill: parent
            anchors.margins: 10
            url: "qrc:/index.html"
            webChannel: channel
            profile:  WebEngineProfile{
                id:profile
            }

            Component.onCompleted:  {
                var defaultAgent =  profile.httpUserAgent;
                profile.httpUserAgent = defaultAgent+" HiClass-Window"
                console.log(profile.httpUserAgent)
            }
        }

    }


    WebChannel {
        id: channel
        registeredObjects: [qmlHtmlOb]
    }

    Rectangle{
        anchors.right: parent.right
        anchors.top: parent.top
        anchors.bottom: parent.bottom
        width: parent.width/2
        border.color: "blue"

        WebEngineView {
            id: devToolsView
            visible: true
            //inspectedView: 0
            anchors.top: parent.top
            anchors.right: parent.right
            height: parent.height/3

            onNewViewRequested: function(request) {
                var tab = webview.profile
               // tabs.currentIndex = tabs.count - 1;
                request.openIn(webview);
            }
        }


        Button {
            id:sendBtn
            text: qsTr("发送")
            anchors.top: devToolsView.bottom
            anchors.topMargin: 100
            anchors.horizontalCenter: parent.horizontalCenter
            onClicked: qmlHtmlOb.sendMsgChanged(1,"你好html")
        }
        TextArea{
            id:textArea
            anchors.top: sendBtn.bottom
            anchors.topMargin: 20
            anchors.bottom: parent.bottom
            anchors.left: parent.left
            anchors.right: parent.right
        }
    }

}

(3),h5  js文件是qt官方文件,需要放到服务器上

<!doctype html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <script type="text/javascript" src="qrc:///qtwebchannel/qwebchannel.js"></script>
        <script type="text/javascript">

            var qmlHtmlOb
            function setUser(msg){
                qmlHtmlOb.setUser(msg)
            }


            window.onload = function() {
                new QWebChannel(qt.webChannelTransport, function(channel) {
                    // all published objects are available in channel.objects under
                    // the identifier set in their attached WebChannel.id property
                    qmlHtmlOb = channel.objects.qmlHtmlOb;

                });
             }
        </script>
    </head>
    <body>
        <button type="button" onclick= "setUser('你好QML')"> 发送 </button>
        <p id="currentAnswer"></p>
        <div id="output"></div>
    </body>
</html>

(4),main 函数  初始化QtWebEngine::initialize();

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QtWebEngine/QtWebEngine>

#include "qmlHtml.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    qmlRegisterType<QMLHtmlOb>("QMLHtmlOb", 1, 0, "QMLHtmlOb");

    QtWebEngine::initialize();//

    QQmlApplicationEngine engine;
    engine.load(QUrl(QLatin1String("qrc:/main.qml")));

    return app.exec();
}

demo(人家的):https://download.csdn.net/download/weixin_38416696/12240622

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

土拨鼠不是老鼠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值