2
我可以發出帶有標記Q_GADGET從C++到QML的結構的信號。如何在QML中創建Q_GADGET結構的新實例?
是否有可能將這樣的結構從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一個電池狀態結構,但我想將一個參數作爲單個參數發送到一個插槽。
這裏是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>();
建議?
http://doc.qt.io/qt-5/qtqml-cppintegration-definetypes.html#registering-an-instantiable-object-type? – bipll