QML与C++之间自定义对象输出
2023-12-14 00:01:25
    		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.运行结果

    			文章来源:https://blog.csdn.net/huzhifei/article/details/134855654
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
    	本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!