[英]Changing members of Q_GADGET from QML
我正在尝试将Q_GADGET
作为Q_PROPERTY
传播到 QML 中,在那里更改它并将其传递回 C++ 。 我有 class 派生自Q_OBJECT
,它有Q_GADGET
class 作为成员。
class Foo : public QObject
{
Q_OBJECT
Q_PROPERTY(QGadgetClass bar READ bar WRITE setBar NOTIFY barChanged)
public:
...
QGadgetClass bar() const { return bar_; }
void setBar(const QGadgetClass &bar) { bar_ = bar; emit barChanged(); }
...
signals:
void barChanged();
private:
QGadgetClass bar_;
}
Q_GADGET
class 看起来像这样:
class QGadgetClass
{
Q_GADGET
Q_PROPERTY(AnotherQGadgetClass test READ test WRITE setTest)
... // there are also properties ID & name
public:
...
// QGadgetClass getMyself() const { return *this; } // function explained later
AnotherQGadgetClass test() const { return test; }
void setTest(const AnotherQGadgetClass &test) { test_ = test; }
...
private:
AnotherQGadgetClass test_;
}
Q_DECLARE_METATYPE(QGadgetClass)
我正在尝试从 QML 经典方式访问Q_GADGET
,例如访问Q_OBJECT
,但未调用设置器。 如果我通过 getter 获得AnotherQGadgetClass
并更改它的属性,则会调用 setter 并且一切正常,但由于某种原因我无法操作QGadgetClass
。 我在 QML 中的代码如下所示:
Item {
property var bar: foo.bar
function changeBar()
{
console.log(bar.name) // works
console.log(bar.id) // works
bar.name = "New name" // the WRITE function of Q_PROPERTY(name ...) is not called
console.log(bar.name) // shows old name
console.log(bar.test) // prints out AnotherQGadgetClass correctly
var temp = bar.test // copies AnotherQGadgetClass correctly
console.log(temp.name) // prints AnotherQGadgetClass's name
temp.name = "New temp name" // setter is called
console.log(temp.name) // prints new name
bar.test = temp // constructor is NOT called
console.log(bar.test) // prints out old AnotherQGadgetClass
// following code works and will be explained bellow this code
var aa = bar.getMyself() // calls the "hackish" method
console.log(aa.name) // prints out name of QGadgetClass
aa.name = "New name" // calls the setter
console.log(aa.name) // prints out new name
}
}
我已经做了一些研究,但除了这个页面什么也没找到。 我也在这里找到了一些非常不漂亮的解决方案并且它起作用了,但我发现它非常 hacky。
请注意,每个Q_GADGET
都通过Q_DECLARE_METATYPE(...)
声明为元类型,并在使用前通过qRegisterMetaType<...>("...")
注册。
有没有更漂亮的解决方案可以直接从 QML 访问QGadgetClass
,而不需要调用getMyself()
方法? 为什么不调用Q_GADGET
class 设置器?
Q_GADGET 在 QML 中始终被视为值类型:它必须通过复制传递。 因此,您在 QML 中操作的 object 与您在 C++ 中创建的实例不同,并且属性更改在原始实例中不可见。 许多相关问题链接自https://bugreports.qt.io/browse/QTBUG-82443
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.