我正在尝试将 Q_GADGET
作为Q_PROPERTY
传播到QML中,并在那里进行更改并将其传递回C++。我有一个派生自Q_OBJECT
的类,它将Q_GADGET
类作为成员。
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 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
}
}
我已经做了一些研究,但是除了此页什么都没有发现。我还找到了一些非常不好看的解决方案这里,它是有效的,但我发现它非常麻烦。
注意,每个Q_GADGET
都是通过Q_DECLARE_METATYPE(...)
声明为元类型的&在使用之前通过qRegisterMetaType<...>("...")
注册。
是否有更好的解决方案可以直接从QML访问QGadgetClass
,而不需要调用getMyself()
方法?为什么没有调用Q_GADGET
类设置器?
发布于 2022-02-15 13:01:38
在QML中,Q_GADGET始终被视为值类型:它必须通过复制传递。因此,您在QML中操作的对象与您在C++中创建的实例不同,属性更改在原始对象中不可见。许多相关问题都与https://bugreports.qt.io/browse/QTBUG-82443相关联。
https://stackoverflow.com/questions/70968519
复制相似问题