QML与C++之间自定义对象输出

1.定义暴露的C++类 Message.h

#ifndef MESSAGE_H
#define MESSAGE_H

#include "QObject"
#include "MessageAuthor.h"

class Message : public QObject
{
    Q_OBJECT
    Q_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_OBJECT
    Q_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", 1, 0, "Message");

4.在main.qml文件中使用

import QtQuick 2.15
import QtQuick.Window 2.15
import Message 1.0
import QtQuick.Controls 2.15

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    Message{
        id:message
             
    }


    Button{
        id: button1
        text:"点击1"
        onClicked: {
            message.author.name = "zhangsan"
            message.author.email = "zhangsan.162.com"

        }
    }

    Button{

        id: button2
        text:"点击2"
        anchors.top: button1.bottom
        anchors.topMargin: 20
        onClicked: {

            message.author.name = "lisi"
            message.author.email = "lisi.162.com"

        }

    }

    Label{

        text: message.author.name + message.author.email
        anchors.top: button2.bottom
        anchors.topMargin: 10
    }
}

5.运行结果

QML与C++之间自定义对象输出_第1张图片

你可能感兴趣的:(QT,c++,java,数据结构,qt,QML)