欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Qt5.11 利用QWebChannel实现C++与JS的交互

程序员文章站 2022-07-13 08:27:50
...

文章大部分内容来自另外一位博主的内容。但是文章的最后有几处个人认为阐述不清楚的地方,在自己更改过后,实现最终效果

引自:https://blog.csdn.net/lh1136863240/article/details/84978716

首先qwebchannel.js文件是在Qt的安装目录下\Examples\Qt-5.11.2\webchannel\shared\qwebchannel.js,直接copy&paste就完事了,在index.html里用<script>标签引用一下,这就是前端的工作了,而且工作量并不大,而且很简单所以就不多说了。
建一个基于控制台的Qt应用程序,构建组件这里我选择的是Vs2015 -32位

Qt5.11 利用QWebChannel实现C++与JS的交互

 接下来我们把Qt安装目录下的Examples\Qt-5.11.2\webchannel\shared下的文件全部复制到工程目录下,顺便建一个index.html

Qt5.11 利用QWebChannel实现C++与JS的交互

然后在Qt中将cpp与h文件全部导入进工程中

Qt5.11 利用QWebChannel实现C++与JS的交互

打开pro文件,里面加入QT += core websockets webchannel

main.cpp文件里包含websocketclientwrapper.h、websockettransport.h、<QtWebChannel/QWebChannel>、<QtWebSockets/QWebSocketServer>
Qt5.11 利用QWebChannel实现C++与JS的交互

Qt5.11 利用QWebChannel实现C++与JS的交互

上代码:

main.cpp
 

#include <QCoreApplication>
#include "websocketclientwrapper.h"
#include "websockettransport.h"
#include <QtWebChannel/QtWebChannel>
#include <QtWebSockets/QWebSocketServer>
#include "chatserver.h"
int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QWebSocketServer server(QStringLiteral("QWebChannel Standalone Example Server"),
                                QWebSocketServer::NonSecureMode);
        if (!server.listen(QHostAddress::LocalHost, 12345)) {
            qFatal("Failed to open web socket server.");
            return 1;
        }

        // wrap WebSocket clients in QWebChannelAbstractTransport objects
        WebSocketClientWrapper clientWrapper(&server);

        // setup the channel
        QWebChannel channel;
        QObject::connect(&clientWrapper, &WebSocketClientWrapper::clientConnected,
                         &channel, &QWebChannel::connectTo);

        // setup the dialog and publish it to the QWebChannel
        ChatServer* chatserver = new ChatServer(&a);
        channel.registerObject(QStringLiteral("chatserver"), chatserver);
    return a.exec();
}

chatserver.h

#ifndef CHATSERVER_H
#define CHATSERVER_H

#include <QObject>

class ChatServer : public QObject
{
    Q_OBJECT

public:
    explicit ChatServer(QObject *parent = nullptr);
    virtual ~ChatServer();

    Q_INVOKABLE void test1();

signals:
    void test2();
};

#endif // CHATSERVER_H

chatserver.cpp

#include "chatserver.h"
#include <QDebug>

ChatServer::ChatServer(QObject *parent)
    : QObject(parent)
{}

ChatServer::~ChatServer()
{}

void ChatServer::test1() {
    qDebug() << "This is test1";
    emit test2();
}

index.html

<!DOCTYPE html>
<html>
<head>
    <title>ChatClient</title>
 
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <script type="text/javascript" src="qwebchannel.js"></script>
 
    <script>
        'use strict';
        var wsUri = "ws://localhost:12345";
        window.onload = function() {
            var socket = new WebSocket(wsUri);
            socket.onclose = function() {
                console.error("web channel closed");
            };
            socket.onerror = function(error) {
                console.error("web channel error: " + error);
            };

			socket.onopen = function() {
    window.channel = new QWebChannel(socket, function(channel) {
        channel.objects.chatserver.test2.connect(function () {
            console.log('aaaa');
        });
        channel.objects.chatserver.test1();
    });
}
        }
    </script>
</head>
<body>
</body>
</html>

编译C++端并运行,然后打开index.html,按F12点击控制台选项,看到了aaaa,说明从C++端调用JS函数也是没问题的

同时,控制台界面能够看到“This is test1”字样

相关标签: Qt调用html