如何在Qt中使用QWebChannel发送QJsonObject

How send a QJsonObject using QWebChannel in Qt

本文关键字:QWebChannel 发送 QJsonObject Qt      更新时间:2023-10-16

我使用QWebChannel在Qt中实现HTML包装器,并且我能够成功发送字符串,但是,我喜欢发送QJsonObject,而不是像"{a:1,b:2}"这样的json字符串,而是Qt QJsonObject。可能吗?

官方文件说

"不需要手动传递消息和数据序列化," http://doc.qt.io/qt-5/qwebchannel.html

如何使用 JsonObject 而不是字符串发出信号?

这是我的QWebChannel连接类

class Mapa : public QObject{
    Q_OBJECT
    public:
        explicit Mapa();
        displayMessage(const QString &message);
    signals:
        updateText(const QString &text); // success :sends text
        updateJson( const QJsonObject   &json); // fail: sends null
        updateJsond(const QJsonDocument &jsondoc);// fail: sends null
    }
 }

这是我的主要代码

Mapa map;
// setup the channel
QWebChannel channel;
QObject::connect(&clientWrapper, &WebSocketClientWrapper::clientConnected, &channel, &QWebChannel::connectTo);
// setup the dialog and publish it to the QWebChannel
channel.registerObject(QStringLiteral("map"), &map);
map.updateText("text");// sends "text" string
QJsonObject j;
j["Altitude"]  = 10;
map.updateJson(j); // sends "null" string
QJsonDocument doc(j);
map.updateJsond(doc); // sends "null" string

您可以将QVariant对象发送到 Javascript 代码中,而不是使用 QJson 系列对象

  • QJsonObject = QVariantMap
  • QJsonArray = QVariantList

您可以使用 .toVariantMap().toVariantList()方法轻松地从 JSON 对象转换对象。