[英]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.