简体   繁体   English

通过属性在C ++和QML之间共享数组或列表

[英]Share array or list between C++ and QML via property

There's a list of unsigned ints in C++ class. C ++类中有一个未签名的整数列表。 The list can be modified inside the class in some way. 列表可以在类中以某种方式进行修改。 There's a QML object that has to use this list. 有一个QML对象必须使用此列表。 How should I declare the list to make the object able to use the values from the list and after changing the content of the list inside C++ get appropriate values in QML? 我应该如何声明列表以使对象能够使用列表中的值,并在C ++中更改列表的内容后在QML中获得适当的值?

Currently the list is defined as: 当前该列表定义为:

QVariantList cards; Q_PROPERTY(QVariantList cards MEMBER cards NOTIFY setChanged) void setChanged ( QVariantList const &cards );

But QML takes only cards initial value (empty list) and does not "notice" any changes inside it later on. 但是QML只接受cards初始值(空列表),以后不“注意”其中的任何更改。

The need for NOTIFY signal is optional. 是否需要NOTIFY信号是可选的。 I guess it is for when we need to deliberately let QML know that the data is ready but the data will be consumed when it READs data. 我猜这是因为我们需要有意识地让QML知道数据已经准备好,但是在读取数据时会消耗掉数据。 Aside from this we can almost always avoid programming NOTIFY. 除此之外,我们几乎总是可以避免编写NOTIFY。 I even do rootItem->setProperty("propertyName", value) for occasional push in of new value to QML especially if there onPropertyNameChanged handler is ready. 我什至执行rootItem-> setProperty(“ propertyName”,value)偶尔将新值推入QML,尤其是当准备好onPropertyNameChanged处理程序时。

The below will likely do what you want. 下面可能会做您想要的。 Or it is required and adding NOTIFY to that won't hurt as well but adds 'inoperability'. 或者它是必需的,并且向其添加NOTIFY也不会造成伤害,但会增加“不可操作性”。

class MyMsgBoard : public QObject
{
public:
    Q_PROPERTY(QVariantList cards READ cards WRITE setCards)
    const QVariantList & cards() const { return qvList; }
    void setCards(const QVariantList & v) { qvList = v; }
private:
    QVariantList qvList;
};

More detailed explanation . 更详细的解释 I use message board concept from there. 我从那里开始使用留言板的概念。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM