如何在QML中创建Q_GADGET结构的新实例?

pix*_*ase 4 c++ qt struct signals-slots qml

我可以发出带有Q_GADGET标记的结构信号,从C++到QML.

是否有可能将这样的结构从QML发送到C++插槽?我的代码在第一步失败:在QML中创建实例.

这段代码在第一行失败了......

var bs = new BatteryState()
bs.percentRemaining = 1.0
bs.chargeDate = new Date()
DataProvider.setBatteryState(bs)
Run Code Online (Sandbox Code Playgroud)

......有错误:

qrc:///main.qml:34: ReferenceError: BatteryState is not defined
Run Code Online (Sandbox Code Playgroud)

我可以从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);
}
Run Code Online (Sandbox Code Playgroud)

我在main.cpp中注册了这个类型:

qRegisterMetaType<BatteryState>();
Run Code Online (Sandbox Code Playgroud)

建议?

dte*_*ech 6

您不需要Q_GADGET在QML中创建s,需要QObject派生QML对象,并且不是通过new- 仅用于JS对象创建的.小工具只是生成元数据,以便您可以从QML访问其成员并传递,这就是它.

是否有可能将这样的结构从QML发送到C++插槽?

可以发送,但不会在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
    }
Run Code Online (Sandbox Code Playgroud)