Mixed development of Qt and Web: realize two-way communication

introduction

In today's software development, combining Qt and Web technologies for hybrid development is becoming more and more popular. As a powerful C++ framework, Qt provides a rich graphical interface and function library, while Web technology provides flexibility and cross-platform advantages. Combining these two technologies, we can develop powerful and attractive applications. This blog will introduce how to implement two-way communication between Qt and the Web, by using QWebChannel and JavaScript bridging, let's get started!

Introduction to QWebChannel

QWebChannel fills the gap between C++ applications and HTML/JavaScript applications. By publishing a QObject derived object to a QWebChannel and referencing the qwebchannel.js script in HTML. On the HTML side, properties, public slots and methods of QObject can be accessed transparently. Instead of manually passing messages and serializing data, property updates and signal emissions from the C++ side are automatically transmitted to HTML clients that may be running remotely. On the client side, JavaScript objects will be created for any published C++ QObjects. It mirrors the API of C++ objects, so it can be used intuitively.

C++ side

Create a QObject derived class

First, on the C++ side, we need to create a class that inherits from QObject to transfer data and call functions between Qt and the Web. For example, let's create a class called MyObject and declare some slots and signals in it:

myobject.h

#include <QObject>
#include <QString>

class MyObject : public QObject
{
    Q_OBJECT

public:
    explicit MyObject(QObject *parent = nullptr);

public slots:
    void myFunction(const QString &message);
    void sendMessage(const QString &message);

signals:
    void sig_sendMessage(const QString &message);

};

myobject.cpp

#include "myobject.h"

#include <QDebug>

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

}

void MyObject::myFunction(const QString &message)
{
    qDebug() << message;
}

void MyObject::sendMessage(const QString &message)
{
    emit sig_sendMessage(message);
    qDebug() << message;
}

Register QObject derived class

On the C++ side, we create a QWebEngineView and add the MyObject object to the Web channel:

#include <QApplication>
#include <QWebChannel>
#include <QWebEngineView>

#include "myobject.h"

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

    QWebEngineView *webView = new QWebEngineView();
    QWebChannel *channel = new QWebChannel();

    MyObject *myObject = new MyObject();
    channel->registerObject(QStringLiteral("myObject"), myObject);

    webView->page()->setWebChannel(channel);
    webView->load(QUrl("file:///C:/Users/yxc/Desktop/untitled/bmdemo.html")); // 路径根据实际情况
    webView->show();

    return app.exec();
}

Web side

On the Web side, we need to load the JavaScript library of QWebChannel in the HTML page, and use JavaScript to interact with Qt. By using the name of the Qt object (in this case "myObject"), we can access the functions and signals of the Qt object:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>bm qt + web test</title>
    <script src="./qwebchannel.js"></script>
    <script type="text/javascript">
        var myObject;
        var webChannel = new QWebChannel(qt.webChannelTransport, function (channel) {
      
      
            myObject = channel.objects.myObject;
        });

        function myFunction() {
      
      
            // 调用Qt函数
            myObject.myFunction("Hello from Web");
        }

        function sendMessage() {
      
      
            // 发送信号到Qt
            myObject.sendMessage("Message from Web");
        }
    </script>
</head>

<body>
    <button id="myFunction" onclick="myFunction()">my function</button>
    <button id="sendMessage" onclick="sendMessage()">send message</button>
</body>

</html>

run and test

Run the application and the Qt application will load the web pages and display messages from the web on the console. Through the slot function of the Qt object, we can process messages sent from the Web, or communicate with the Web through signals.

The test results are shown in the figure:

insert image description here

in conclusion

By using Qt WebChannel and JavaScript bridging, we can achieve two-way communication between Qt and the Web. This mixed development method allows us to make full use of the powerful functions of Qt and the flexibility of Web technology to develop applications with rich functions and strong interactivity. This article introduces the basic concepts and usage of QWebChannel, and provides a simple example to demonstrate how to communicate between Qt and the Web. I hope this blog can provide you with a good starting point to learn more about Qt and Web hybrid development.

In actual development, you can further expand and customize this communication mechanism according to specific needs, and combine your creativity and application scenarios to achieve more feature-rich interactive experiences. I wish you success in your journey of mixed Qt and Web development.

Guess you like

Origin blog.csdn.net/bmseven/article/details/131785158