2

下面的代码:

Item{
    onDataChanged: console.log("Data changed")
}

Item{
    onResourcesChanged: console.log("Resources changed")
}

分别抛出Cannot assign to non-existent property "onDataChanged"Cannot assign to non-existent property "onResourcesChanged"

信号不是这种情况childrenChanged()。这样做的原因是,在 中qtdeclarative/src/quick/items/qquickitem.hchildren属性声明为:

Q_PRIVATE_PROPERTY(QQuickItem::d_func(), QQmlListProperty<QQuickItem> children READ children NOTIFY childrenChanged DESIGNABLE false)

但这不是dataor的情况resources。它们被声明为:

Q_PRIVATE_PROPERTY(QQuickItem::d_func(), QQmlListProperty<QObject> data READ data DESIGNABLE false)
Q_PRIVATE_PROPERTY(QQuickItem::d_func(), QQmlListProperty<QObject> resources READ resources DESIGNABLE false)

没有changed()信号。为什么这种设计选择是为了特别隐藏对不可见儿童所做的更改?此外,如何data从 QML 中检测到变化?

4

1 回答 1

3

你为什么需要这个?

一种可能的解决方法是监听子事件。我写了一个快速附加类型 PoC :

ChildListener.h:

#ifndef CHILDLISTENER_H
#define CHILDLISTENER_H

#include <QObject>
#include <QtQml>

class ChildListener : public QObject {
    Q_OBJECT

public:
    ChildListener(QObject *object) : QObject(object) {
        if (object)
            object->installEventFilter(this);
    }

    static ChildListener *qmlAttachedProperties(QObject *object) {
        return new ChildListener(object);
    }

signals:
    void childAdded(QObject* child);
    void childRemoved(QObject* child);

protected:
      bool eventFilter(QObject *obj, QEvent *event) override {
          Q_UNUSED(obj)
          if (QChildEvent *childEvent = dynamic_cast<QChildEvent*>(event)) {
              if (childEvent->added())
                  emit childAdded(childEvent->child());
              if (childEvent->removed())
                  emit childRemoved(childEvent->child());
          }
          return false;
      }
};

QML_DECLARE_TYPEINFO(ChildListener, QML_HAS_ATTACHED_PROPERTIES)

#endif // CHILDLISTENER_H

注册它,qmlRegisterUncreatableType<ChildListener>("fr.grecko.ChildListener", 1, 0, "ChildListener", "ChildListener can only be accessed as an attached type.");您现在可以像这样使用它:

import fr.grecko.ChildListener 1.0
/* ... */
Timer {
    id: foo
    objectName: "My name is foo"
}
Item {
    ChildListener.onChildAdded: print("child added : ", child)
    data: [foo];
}

这输出:qml: child added : QQmlTimer(0x7ffe22f538e0, "My name is foo")在控制台中

于 2017-03-27T10:08:56.653 回答