qml 附加属性

今天看qml的例子程序,看到一个attached例子,为qml添加附加对象,这个概念有点难于理解:附加对象主要用来提供附加属性,附加属性是相对静态属性而言的,比如在C++类中用Q_PROPERTY申明的属性属于静态属性。附加属性却可以在尽量不破坏原有类型的基础上,为其添加扩展属性。其应用场景还有待进一步的研究。


添加附加属性的方法

  • 定义自己的附加属性类型:和一般的类型定义一模一样
class ClassAttached : public QObject
{
    Q_OBJECT
    Q_PROPERTY(QDate rsvp READ rsvp WRITE setRsvp)
public:
    ClassAttached (QObject *object);

    QDate rsvp() const;
    void setRsvp(const QDate &);

private:
    QDate m_rsvp;
}; 
  • 对需要添加附加属性的类型稍作改动:
    1. 实现static ClassAttached *qmlAttachedProperties(QObject *);接口;
    2. 申明该类拥有附加属性:QML_DECLARE_TYPEINFO(ClassAttatee, QML_HAS_ATTACHED_PROPERTIES)
class ClassAttatee: public QObject
{
    Q_OBJECT
    Q_PROPERTY(Person *host READ host WRITE setHost)
    Q_PROPERTY(QQmlListProperty guests READ guests)
    Q_CLASSINFO("DefaultProperty", "guests")
public:
    ClassAttatee(QObject *parent = 0);

    Person *host() const;
    void setHost(Person *);

    QQmlListProperty guests();
    int guestCount() const;
    Person *guest(int) const;

    //! [static attached]
    static ClassAttached *qmlAttachedProperties(QObject *);
    //! [static attached]
private:
    Person *m_host;
    QList m_guests;
};

//! [declare attached]
QML_DECLARE_TYPEINFO(ClassAttatee, QML_HAS_ATTACHED_PROPERTIES)
//! [declare attached]

//qmlAttachedProperties(QObject *)实现如下:
ClassAttached *BirthdayParty::qmlAttachedProperties(QObject *object)
{
    return new ClassAttached (object);
}

这样在qml中就可以用如下方式定义附加属性了:

ClassAttatee{
//! [begin]
    ClassAttached .rsvp: "2009-07-02"
//! [rsvp]
    Boy {
        name: "Robert Campbell"
        ClassAttached .rsvp: "2009-07-01"
    }
//! [rsvp]
    // ![1]
    Boy {
        name: "Leo Hodges"
        shoe { size: 10; color: "black"; brand: "Reebok"; price: 59.95 }

        ClassAttached .rsvp: "2009-07-06"
    }
    // ![1]
    host: Boy {
        name: "Jack Smith"
        shoe { size: 8; color: "blue"; brand: "Puma"; price: 19.95 }
    }
//! [end]
}

总结:

如果在后期需要为ClassAttatee添加属性,就可以在不破坏ClassAttatee类型的前提下,只需在ClassAttatee中添加即可。并且ClassAttatee可以作为多个类型的附加类型,这样就可以统一为多个类型添加附加属性,而不需要为每个类型单独添加。

qml类型提供的默认附加对象

在qml的默认类型中,提供了一些默认的附加类型,典型的有Keys类型:

Item {
      width: 100; height: 100

      focus: true
      Keys.enabled: false
      Keys.onReturnPressed: console.log("Return key was pressed")
  }

我们在定义Item时,可以访问Keys的属性和信号。

你可能感兴趣的:(qml 附加属性)