I can emit signals with structs tagged with Q_GADGET from C++ to QML.
Is it possible send such a struct from QML to a C++ slot? My code fails on the first step: creating an instance in QML.
This code fails on the first line ...
var bs = new BatteryState()
bs.percentRemaining = 1.0
bs.chargeDate = new Date()
DataProvider.setBatteryState(bs)
... with error:
qrc:///main.qml:34: ReferenceError: BatteryState is not defined
I can emit a BatteryStatus struct from C++ to QML, but I would like to send one back as a single parameter to a slot.
Here is 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);
}
I register this type in main.cpp:
qRegisterMetaType<BatteryState>();
Recommendations?