下面的例子演示如何向利用C++自定义QML类型及自定义类型List
在Person类中用到name 和shoeSize属性,故在person.h中使用:
Q_PROPERTY(QString name READ name WRITE setName)
Q_PROPERTY(int shoeSize READ shoeSize WRITE setShoeSize)
在BirthdayParty中类中用到Person类对象和一个以Person为元素的List对象 guests 作为属性且guests只读,故使用:
Q_PROPERTY(Person *host READ host WRITE setHost)
Q_PROPERTY(QDeclarativeListProperty<Person> guests READ guests)
person.h ---------------------------------------- #ifndef PERSON_H #define PERSON_H #include
person.cpp -------------------------------------------- #include "person.h" Person::Person(QObject * parent) : QObject(parent), m_shoeSize(0) { } QString Person::name() const { return m_name; } void Person::setName(const QString &n) { m_name = n; } int Person::shoeSize() const{ return m_shoeSize; } void Person::setShoeSize(int s) { m_shoeSize = s; }
birthday.h ----------------------------------------------- #ifndef BIRTHDAYPARTY_H #define BIRTHDAYPARTY_H #include
birthday.cpp ------------------------------------------ #include "birthdayparty.h" BirthdayParty::BirthdayParty(QObject *parent) : QObject(parent), m_host(0) { } Person *BirthdayParty::host() const { return m_host; } void BirthdayParty::setHost(Person * c) { m_host = c; } QDeclarativeListProperty
main.cpp ------------------------------------------ #include
example.qml ----------------------------------------------- import People 1.0 BirthdayParty { host : Person { name: "Lavy Liu" shoeSize: 12 } guests: [ Person { name: "Sglaze"; shoeSize: 18}, Person { name: "liuhongwei"; shoeSize: 23}, Person { name: "liuhw"} ] }
输出:
"Lavy Liu" is having a birthday!
They are inviting:
"Sglaze" 18
"liuhongwei" 23
"liuhw" 0