QT通过JS与HTML的交互

头文件加入

QT       += core gui webenginewidgets webchannel

通过QWebChannel与JS交互 原理

    QWebEnginePage *page = new QWebEnginePage(this);
    webView->setPage(page);
    webView->load(QUrl("qrc:/html/index.html"));
    webView->show();
    QWebChannel *channel = new QWebChannel(this);
    //注册一个content  这里的内容通过JS的content来获取
    channel->registerObject(QString("content"),this);
    page->setWebChannel(channel);

注意:一定要先给WebView设置page,再加载网页,否则网页出不来!

QT发送信息到JS:

signals:
    void sendText(const QString &s_user,const QString &s_pwd);
//点击按钮 设置发送的文本
void MainWindow::callJSBtnClicked()
{
    //emit sendText(user->text(),password->text());
    sendText(user->text(),password->text());
    user->setText("");
    password->setText("");
}

QT接收到JS的信息

public slots:
    void receiveText(const QString &r_user,const QString &r_pwd);
void MainWindow::receiveText(const QString &r_user, const QString &r_pwd)
{
    user->setText(r_user);
    password->setText(r_pwd);
}

要用public才行!
JS中对信息的操作

window.onload = function () {
    new QWebChannel(qt.webChannelTransport,function (channel) {
        var content = channel.objects.content;
        //接收QT发送来的
        content.sendText.connect(function (s_user, s_pwd) {
            document.getElementById("userName").value = s_user;
            document.getElementById("userPwd").value = s_pwd;
        })
        //传给QT
        document.getElementById("submit").onclick = function () {
               var userName = document.getElementById("userName").value;
               var userPwd = document.getElementById("userPwd").value;
               document.getElementById("userName").value = "";
               document.getElementById("userPwd").value = "";
               content.receiveText(userName,userPwd);
        }
    })
}

JS中content.sendText.connect 不曾关闭
在MainWindow中关闭连接

MainWindow::~MainWindow()
{
    this->disconnect();
}

运行效果
“`这里写图片描述

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值