一、QML之default(关键字)
An object definition can have a single default property. A default property is the property to which a value is assigned if an object is declared within another object’s definition without declaring it as a value for a particular property.
- 一个对象有且只有一个default属性
- 在对象中定义一个不是属性的对象时,会把该对象赋值给默认属性。
-
ChildItem.qml
import QtQuick 2.0Item { property string name: "" } import QtQuick 2.0
-
ParentItem.qml
Item { default property alias contentchild: _private.elements; QtObject{ id:_private; property list<ChildItem> elements } Component.onCompleted: { for(var i in _private.elements){ console.log(_private.elements[i].name) } } }
-
main.qml
import QtQuick 2.12 import QtQuick.Window 2.12 Window { visible: true width: 640 height: 480 title: qsTr("Hello World") ParentItem{ ChildItem{ name:qsTr("apple") } ChildItem{ name:qsTr("ege") } }
二、C++如何使用对象和属性列表扩展QML
以下例子是QQmlListProperty的使用
#ifndef QMLWINDOWPROP_H
#define QMLWINDOWPROP_H
#include <QObject>
#include <QQmlListProperty>
class QMLWindowProp : public QObject
{
Q_OBJECT
Q_PROPERTY(QQmlListProperty<QObject> guests READ guests)
Q_CLASSINFO("DefaultProperty", "guests") //声明为默认属性
public:
QMLWindowProp(QObject *parent = nullptr);
QQmlListProperty<QObject> guests();
void appendGuest(QObject* );
int guestCount() const;
QObject *guest(int) const;
void clearGuests();
private:
static void appendGuest(QQmlListProperty<QObject>*, QObject*);
static int guestCount(QQmlListProperty<QObject>* );
static QObject* guest(QQmlListProperty<QObject>*, int);
static void clearGuests(QQmlListProperty<QObject>*);
QList<QObject *> m_guests;
};
#endif // QMLWINDOWPROP_H
#include "qmlwindowprop.h"
QMLWindowProp::QMLWindowProp(QObject *parent)
: QObject(parent)
{
}
QQmlListProperty<QObject> QMLWindowProp::guests()
{
// return {this, this,
// &QMLWindowProp::appendGuest,
// &QMLWindowProp::guestCount,
// &QMLWindowProp::guest,
// &QMLWindowProp::clearGuests};
return {this, m_guests};
}
void QMLWindowProp::appendGuest(QObject *p)
{
m_guests.append(p);
}
int QMLWindowProp::guestCount() const
{
return m_guests.count();
}
QObject *QMLWindowProp::guest(int index) const
{
return m_guests.at(index);
}
void QMLWindowProp::clearGuests()
{
m_guests.clear();
}
void QMLWindowProp::appendGuest(QQmlListProperty<QObject> *list, QObject *p)
{
reinterpret_cast< QMLWindowProp* >(list->data)->appendGuest(p);
}
int QMLWindowProp::guestCount(QQmlListProperty<QObject> *list)
{
return reinterpret_cast< QMLWindowProp* >(list->data)->guestCount();
}
QObject *QMLWindowProp::guest(QQmlListProperty<QObject> *list, int i)
{
return reinterpret_cast< QMLWindowProp* >(list->data)->guest(i);
}
void QMLWindowProp::clearGuests(QQmlListProperty<QObject> *list)
{
reinterpret_cast< QMLWindowProp* >(list->data)->clearGuests();
}