1.定义暴露的C++类 Message.h
#ifndef MESSAGE_H
#define MESSAGE_H#include "QObject"
#include "MessageAuthor.h"class Message : public QObject
{Q_OBJECTQ_PROPERTY(MessageAuthor* author READ author )public:explicit Message(QObject *parent = nullptr): QObject(parent){m_author = new MessageAuthor();}MessageAuthor* author() const {return m_author;}private:MessageAuthor* m_author;
};#endif // MESSAGE_H
2.定义自定义的属性对象类MessageAuthor
#ifndef MESSAGEAUTHOR_H
#define MESSAGEAUTHOR_H#include "QObject"class MessageAuthor : public QObject
{Q_OBJECTQ_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)Q_PROPERTY(QString email READ email WRITE setEmail NOTIFY emailChanged )
public:explicit MessageAuthor(QObject *parent = nullptr): QObject(parent){}void setName(const QString &a) {if (a != m_name) {m_name = a;emit nameChanged();}}QString name() const {return m_name;}void setEmail(const QString &a) {if (a != m_email) {m_email = a;emit emailChanged();}}QString email() const {return m_email;}private:QString m_name;QString m_email;signals:void emailChanged();void nameChanged();
};#endif // MESSAGEAUTHOR_H
3.main.cpp中注册类型
#include "Message.h" //引用头文件//在main函数代码中注册
qmlRegisterType<Message>("Message", 1, 0, "Message");
4.在main.qml文件中使用
import QtQuick 2.15
import QtQuick.Window 2.15
import Message 1.0
import QtQuick.Controls 2.15Window {width: 640height: 480visible: truetitle: qsTr("Hello World")Message{id:message}Button{id: button1text:"点击1"onClicked: {message.author.name = "zhangsan"message.author.email = "zhangsan.162.com"}}Button{id: button2text:"点击2"anchors.top: button1.bottomanchors.topMargin: 20onClicked: {message.author.name = "lisi"message.author.email = "lisi.162.com"}}Label{text: message.author.name + message.author.emailanchors.top: button2.bottomanchors.topMargin: 10}
}
5.运行结果