用c++定义qml的类

注册可实例化的类型的QML类型
如果一个C++类继承自QObject,如果需要在QML中使用创建对象,则需要注册为可实例化的QML类型。
使用qmlRegisterType()注册可实例化的QML类型,具体查看qmlRegisterType()的文档说明。

//Message.cpp
class 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 <QtQml>
...
qmlRegisterType<Message>("com.mycompany.messaging", 1, 0, "Message");
...

//aQmlFile.qml
import com.mycompany.messaging 1.0

Message {
   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.cpp
class 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.cpp
class 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.cpp
class MessageBoard : public QObject
{
   Q_OBJECT
public:
   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 been
published!")
}

//main.cpp
...
Message *msg = someMessageInstance();
MessageBoardAttachedType *attached =
   qobject_cast<MessageBoardAttachedType*>(qmlAttachedPropertiesObject<MessageBoard>(msg));
qDebug() << "Value of MessageBoard.expired:" << attached->expired();
...