基于 qtqwebenginepage::setwebchannel() 传输对象和 QT: 无法从 JavaScript 调用返回自定义数据结构。我需要这个功能,但我不知道该怎么做。
/** this is my data type */
class QDataDictionary {
public:
QString number;
QString name;
QString description;
};
Q_DECLARE_METATYPE(QDataDictionary);
希望接口处理完相关操作后能返回自己定义的数据。以下是我的C++实现代码
#ifndef QSYSTEMDICTIONARYMANAGER_H
#define QSYSTEMDICTIONARYMANAGER_H
#include <QObject>
#include "qsystemdatadictionary.h"
class QSystemDictionaryManager : public QObject
{
Q_OBJECT
public:
explicit QSystemDictionaryManager(QObject *parent = nullptr);
virtual ~QSystemDictionaryManager();
signals:
public slots:
/** I want to return this data structure */
Q_INVOKABLE QDataDictionary debug(const QString& contents);
public slots:
protected:
};
#endif // QSYSTEMDICTIONARYMANAGER_H
#include "qsystemdictionarymanager.h"
#include <QTextStream>
#include <QMessageBox>
QSystemDictionaryManager::QSystemDictionaryManager(QObject *parent) : QObject(parent)
{
}
QSystemDictionaryManager::~QSystemDictionaryManager() {
}
QDataDictionary data;
QDataDictionary QSystemDictionaryManager::debug(const QString &contents)
{
QString DebugMessage;
QTextStream DebugTextStream(&DebugMessage);
DebugTextStream << this << " " << __LINE__ << " "<< __FUNCTION__ << " == " << contents;
QMessageBox::information(nullptr, "javascrpt call authenticate", DebugMessage);
data.number = "256";
data.name = "___dictionary__";
data.description = "QSystemDataDictionary";
return data;
}
下面是我通过JavaScript调用C++的接口,但是没有得到我想要返回的数据
var SystemDictionaryManager;
new QWebChannel(qt.webChannelTransport,
function (channel) {
SystemDictionaryManager = channel.objects.SystemDictionaryManager;
});
var debug = async function (text) {
if (typeof SystemDictionaryManager !== "undefined") {
var message = "System Dictionary Manager";
/** Calling the interface can't get the data I want */
await new Promise(resolve =>
SystemDictionaryManager.debug(message, function (result) {
document.getElementById("main").innerHTML = "data is == " + result;
resolve();
}));
}
}