2017-03-14 59 views
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>(); 

建議?

+0

http://doc.qt.io/qt-5/qtqml-cppintegration-definetypes.html#registering-an-instantiable-object-type? – bipll

回答

2

不創建Q_GADGET S IN QML,QML對象必須是QObject導出,並創建通過new - 這對JS對象只。小工具只是生成元數據,以便您可以從QML訪問其成員等,並傳遞信息,就是這樣。

Is it possible send such a struct from QML to a C++ slot?

可以發送,但不會在QML中創建。它可以從C++函數返回到QML,也可以作爲某個對象的屬性公開。

struct Test { 
    Q_GADGET 
    Q_PROPERTY(int test MEMBER test) 
    public: 
    Test() : test(qrand()) {} 
    int test; 
    Q_SLOT void foo() { qDebug() << "foo"; } 
}; 

class F : public QObject { // factory exposed as context property F 
    Q_OBJECT 
    public slots: 
    Test create() { return Test(); } 
    void use(Test t) { qDebug() << t.test; } 
}; 


    // from QML 
    property var tt: F.create() 

    Component.onCompleted: { 
     F.use(F.create()) // works 
     var t = F.create() 
     console.log(t.test) // works 
     F.use(t) // works 
     console.log(tt.test) // works 
     F.use(tt) // works 
     tt.test = 555 
     F.use(tt) // works 
     t.test = 666 
     F.use(t) // works 
     t.foo() // works 
    }