本页内容

Qt WebChannel JavaScript API

配置 JavaScript API

要与QWebChannel 或WebChannel 进行通信,客户端必须使用并配置qwebchannel.js 提供的 JavaScript API。对于在 Qt WebEngine中运行的客户端,若在本地加载页面,可通过qrc:///qtwebchannel/qwebchannel.js 加载该文件;或者将qwebchannel.js 设置为可通过在QWebEngineUrlScheme 上注册为QWebEngineUrlScheme::SecureScheme 的QWebEngineUrlSchemeHandler 访问。对于外部客户端,您需要将该文件复制到您的 Web 服务器上。 然后实例化一个 `QWebChannel ` 对象,并向其传递一个传输对象和一个回调函数——该回调函数将在通道初始化完成且已发布对象可用时被调用。可选的第三个参数包含一个转换器包装函数数组或单个函数。

传输对象实现了一个最简消息传递接口。它应是一个具有send() 函数的对象,该函数接受字符串化的JSON消息,并将其传输给服务器端的QWebChannelAbstractTransport 对象。此外,当收到来自服务器的消息时,应调用其onmessage 属性。或者,您也可以使用WebSocket来实现该接口。

请注意,应在传输对象完全就绪后才构建 JavaScriptQWebChannel 对象。如果是 WebSocket,这意味着您应在套接字的onopen 处理程序中创建QWebChannel 。请参阅Qt WebChannel 独立示例,了解具体实现方法。

注意: 同一页面中,每个传输仅能 创建一个QWebChannel 对象。

转换器包装函数可以是包含内置转换器名称的字符串,也可以是用户提供的函数——该函数将待处理的对象作为参数,返回处理后的类型;若函数不适用,则返回 undefined。若返回 undefined,则继续处理下一个转换器。 如果没有返回值(除 `undefined` 以外)的转换器,则处理将照常进行。“Date”是当前唯一的内置转换器函数。它接受一个包含 ISO 8601 日期格式的字符串,如果语法正确且日期有效,则返回一个新的 Date 对象。

与 QObject 的交互

一旦传递给QWebChannel 对象的回调被调用,通道即完成初始化,HTML客户端可通过channel.objects 属性访问所有已发布的对象。因此,假设某个对象以标识符“foo”发布,则我们可以如下例所示与其交互。 请注意,HTML客户端与QML/C++服务器之间的所有通信均为异步的。属性会在HTML端进行缓存。此外,请务必注意,只有能够转换为JSON格式的QML/C++数据类型才能被正确地序列化或反序列化,从而供HTML客户端访问。

new QWebChannel(yourTransport, function(channel) {

    // Connect to a signal:
    channel.objects.foo.mySignal.connect(function() {
        // This callback will be invoked whenever the signal is emitted on the C++/QML side.
        console.log(arguments);
    });

    // To make the object known globally, assign it to the window object, i.e.:
    window.foo = channel.objects.foo;

    // Invoke a method:
    foo.myMethod(arg1, arg2, function(returnValue) {
        // This callback will be invoked when myMethod has a return value. Keep in mind that
        // the communication is asynchronous, hence the need for this callback.
        console.log(returnValue);
    });

    // Read a property value, which is cached on the client side:
    console.log(foo.myProperty);

    // Writing a property will instantly update the client side cache.
    // The remote end will be notified about the change asynchronously
    foo.myProperty = "Hello World!";

    // To get notified about remote property changes,
    // simply connect to the corresponding notify signal:
    foo.myPropertyChanged.connect(function() {
        console.log(foo.myProperty);
    });

    // One can also access enums that are marked with Q_ENUM:
    console.log(foo.MyEnum.MyEnumerator);
});

重载的方法和信号

当您发布一个具有重载方法的QObject 时,QWebChannel 会将方法调用解析为最匹配的实现。 请注意,由于 JavaScript 的类型系统,仅存在一种“number”类型,它与 C++ 的“double”类型匹配度最高。当重载方法仅在数值型参数的类型上有所不同时,QWebChannel 将始终选择与 JavaScript “number” 类型最匹配的重载方法。 当您连接到一个重载的信号时,QWebChannel 客户端默认只会连接到该名称的第一个信号重载。此外,可以通过其完整的QMetaMethod 签名显式请求方法和信号的重载。假设我们在C++侧有以下QObject 子类:

class Foo : public QObject
{
    Q_OBJECT
slots:
    void foo(int i);
    void foo(double d);
    void foo(const QString &str);
    void foo(const QString &str, int i);

signals:
    void bar(int i);
    void bar(const QString &str);
    void bar(const QString &str, int i);
};

那么,在 JavaScript 端可以像这样与该类进行交互:

// methods
foo.foo(42); // will call the method named foo which best matches the JavaScript number parameter, i.e. foo(double d)
foo.foo("asdf"); // will call foo(const QString &str)
foo.foo("asdf", 42); // will call foo(const QString &str, int i)
foo["foo(int)"](42); // explicitly call foo(int i), *not* foo(double d)
foo["foo(QString)"]("asdf"); // explicitly call foo(const QString &str)
foo["foo(QString,int)"]("asdf", 42); // explicitly call foo(const QString &str, int i)

// signals
foo.bar.connect(...); // connect to first signal named bar, i.e. bar(int i)
foo["bar(int)"].connect(...); // connect explicitly to bar(int i)
foo["bar(QString)"].connect(...); // connect explicitly to bar(const QString &str)
foo["bar(QString,int)"].connect(...); // connect explicitly to bar(const QString &str, int i)

© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.