如果一个C++类继承自QObject,如果需要在QML中使用创建对象,则需要注册为可实例化的QML类型。
使用qmlRegisterType()注册可实例化的QML类型,具体查看qmlRegisterType()的文档说明。
//Message.cppclass Message : public QObject{ Q_OBJECT Q_PROPERTY(QString author READ author WRITE setAuthor NOTIFY authorChanged) Q_PROPERTY(QDateTime creationDate READ creationDate WRITE setCreationDate NOTIFY creationDateChanged)public: // …};//main.cpp#include …qmlRegisterType(“com.mycompany.messaging”, 1, 0, “Message”);…//aQmlFile.qmlimport com.mycompany.messaging 1.0Message { author: “Amelie” creationDate: new Date()}注册不实例化的QML类型1. qmlRegisterType()不带参数 这种方式无法使用引用注册的类型,所以无法在QML中创建对象。
2. qmlRegisterInterface() 这种方式用于注册C++中的虚基类。
3. qmlRegisterUncreatableType()
4. qmlRegisterSingletonType() 这种方法可以注册一个能够在QML中使用的单例类型。
附带属性在QML语法中有一个附带属性的概念。
这里使用C++自定义QML类型的时候,也可以定义附带属性。
核心的亮点就是
static *qmlAttachedProperties(QObject *object);
和
QML_DECLARE_TYPEINFO() 中声明 QML_HAS_ATTACHED_PROPERTIES标志
例如:
//Message.cppclass Message : public QObject{ Q_OBJECT Q_PROPERTY(QString author READ author WRITE setAuthor NOTIFY authorChanged) Q_PROPERTY(QDateTime creationDate READ creationDate WRITE setCreationDate NOTIFY creationDateChanged)public: // …};//MessageBoardAttachedType.cppclass MessageBoardAttachedType : public QObject{ Q_OBJECT Q_PROPERTY(bool expired READ expired WRITE expired NOTIFY expiredChanged)public: MessageBoardAttachedType(QObject *parent); bool expired() const; void setExpired(bool expired);signals: void published(); void expiredChanged();};//MessageBoard.cppclass MessageBoard : public QObject{ Q_OBJECTpublic: static MessageBoard *qmlAttachedProperties(QObject *object) { return new MessageBoardAttachedType(object); }};QML_DECLARE_TYPEINFO(MessageBoard, QML_HAS_ATTACHED_PROPERTIES)//在QML中的使用Message { author: “Amelie” creationDate: new Date() MessageBoard.expired: creationDate < new Date(“January 01, 2015 10:45:00”) MessageBoard.onPublished: console.log(“Message by”, author, “has beenpublished!”)}//main.cpp…Message *msg = someMessageInstance();MessageBoardAttachedType attached = qobject_cast<MessageBoardAttachedType>(qmlAttachedPropertiesObject(msg));qDebug() << “Value of MessageBoard.expired:” << attached->expired();…MessageBoard这个类中首先实现了static *qmlAttachedProperties(QObject *object),然后又用QML_DECLARE_TYPEINFO(MessageBoard, QML_HAS_ATTACHED_PROPERTIES)声明MessageBoard为附带属性。