我可以使用带有 Q_GADGET 标记的结构体从 C++ 向 QML 发送信号。
是否可能从 QML 将这样的结构体发送到 C++ 插槽?我的代码在第一步失败:在 QML 中创建一个实例。
这段代码在第一行失败...
var bs = new BatteryState()
bs.percentRemaining = 1.0
bs.chargeDate = new Date()
DataProvider.setBatteryState(bs)
...带错误信息:
qrc:///main.qml:34: ReferenceError: BatteryState is not defined
我可以从C++向QML发出一个BatteryStatus结构,但我想将其作为单个参数发送回插槽。
这是BatteryState.h和BatteryState.cpp文件的内容:
// BatteryState.h
#pragma once
#include <QDate>
#include <QMetaType>
struct BatteryState
{
Q_GADGET
Q_PROPERTY(float percentRemaining MEMBER percentRemaining)
Q_PROPERTY(QDate date MEMBER date)
public:
explicit BatteryState();
BatteryState(const BatteryState& other);
virtual ~BatteryState();
BatteryState& operator=(const BatteryState& other);
bool operator!=(const BatteryState& other) const;
bool operator==(const BatteryState& other) const;
float percentRemaining;
QDate date;
};
Q_DECLARE_METATYPE(BatteryState)
// BatteryState.cpp
#include "BatteryState.h"
BatteryState::BatteryState()
: percentRemaining(), date(QDate::currentDate())
{}
BatteryState::BatteryState(const BatteryState& other)
: percentRemaining(other.percentRemaining),
date(other.date)
{}
BatteryState::~BatteryState() {}
BatteryState&BatteryState::operator=(const BatteryState& other)
{
percentRemaining = other.percentRemaining;
date = other.date;
return *this;
}
bool BatteryState::operator!=(const BatteryState& other) const {
return (percentRemaining != other.percentRemaining
|| date != other.date);
}
bool BatteryState::operator==(const BatteryState& other) const {
return !(*this != other);
}
我在main.cpp中注册了这种类型:
qRegisterMetaType<BatteryState>();
建议?