Qt

Q_PROPERTY()의 이해 및 사용 방법

desafinado 2024. 1. 25. 16:36
728x90

 

//main.cpp

#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "message.h"

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);//c++에서 구현한 message클래스
    QQmlApplicationEngine engine;;//c++에서 구현한 message클래스

    Message msg;//main.qml
    engine.rootContext()->setContextProperty("msg", &msg)//main.qml//첫번째 qml에서 쓸 object이름
    //2번째는 Message msg객체 의미

    engine.load(QUrl("qrc:/main.qml"));
    return app.exec();
}

/***
 * QuickView 클래스를 사용하는 방식
 * - 위의 소스코드 주석처리 하고 아래 주석 제거 후 사용.
 */

//#include <QGuiApplication>
//#include <QQmlApplicationEngine>

//#include <QQuickView>
//#include <QQmlContext>
//#include "message.h"

//int main(int argc, char *argv[])
//{
//    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

//    QGuiApplication app(argc, argv);

//    QQuickView viewer;
//    Message msg;
//    viewer.engine()->rootContext()->setContextProperty("msg", &msg);
//    viewer.setSource(QUrl( "qrc:/main.qml" ) );

//    return app.exec();
//}
//main.qml
import QtQuick
import QtQuick.Controls

Window {

    width : 200; height: 100; visible: true

    Text {
        id : myText;
        anchors.centerIn: parent
        text: msg.author

        Component.onCompleted: {
            msg.author = "Hello"
            myText.text = msg.author
        }
    }
}
#ifndef MESSAGE_H
#define MESSAGE_H

//message.h
#include <QObject>
#include <QQmlProperty>
#include <QDebug>
#include <QTimer>

class Message : public QObject {
    Q_OBJECT
    Q_PROPERTY(QString author READ author WRITE setAuthor NOTIFY authorChanged)

public:
    explicit Message(QObject *parent = nullptr);
    void setAuthor(const QString &a);
    QString author() const;

signals:
    void authorChanged();

private:
    QString m_author;
};


#endif // MESSAGE_H
//message.cpp
#include "message.h"

Message::Message(QObject *parent) : QObject(parent)
{
    m_author = ":)";
}

void Message::setAuthor(const QString &a)
{
    m_author = QString("%1 world.").arg(a);
    emit authorChanged();
}

QString Message::author() const
{
    return m_author;
}
728x90