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>("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.运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值