C++에서 QML로 상태 노출하기

특정 컴포넌트의 모든 QML 요소, 모듈의 모든 QML 요소 또는 전체 QML 요소에 C++의 일부 프로퍼티를 노출하는 것이 바람직한 경우가 종종 있습니다. 싱글톤을 도입하거나 선택한 컴포넌트의 루트 객체에 프로퍼티를 추가하여 이를 수행할 수 있습니다.

싱글톤 사용

모듈의 모든 요소 또는 전체 요소에 여러 글로벌 프로퍼티를 노출하려면 C++에서 싱글톤을 정의할 수 있습니다. 이렇게 하려면 QML_ELEMENT 또는 QML_NAMED_ELEMENT 매크로와 QML_SINGLETON 매크로를 Q_PROPERTY 선언으로 노출하려는 프로퍼티가 포함된 클래스에 추가합니다:

// Singleton.h
class Singleton : public QObject
{
    Q_OBJECT
    Q_PROPERTY(int thing READ thing WRITE setThing NOTIFY thingChanged FINAL)
    QML_ELEMENT
    QML_SINGLETON

public:
    Singleton(QObject *parent = nullptr) : QObject(parent) {}

    int thing() const { return m_value; }
    void setThing(int v)
    {
        if (v != m_value) {
            m_value = v;
            emit thingChanged();
        }
    }

signals:
    void thingChanged();

private:
    int m_value = 12;
};

이제 이 모듈을 임포트하는 모든 QML 코드에서 싱글톤의 사물 프로퍼티에 액세스할 수 있습니다:

import QtQml

QtObject {
    objectName: "The thing is " + Singleton.thing
}

모듈과 동일한 디렉터리에 QML 파일을 배치한 경우(적극 권장) 모듈 내 암시적 임포트를 통해 싱글톤을 사용할 수 있습니다. 명시적으로 아무것도 가져오지 않아도 됩니다. 그렇지 않은 경우 또는 다른 모듈에서 사물 속성에 액세스하려는 경우 싱글톤이 속한 모듈을 임포트해야 합니다.

C++에서 속성 값을 설정하려면 싱글톤 인스턴스를 검색해야 할 수도 있습니다. 이를 위해 QQmlEngine::singletonInstance 을 사용할 수 있습니다. 이 작업을 수행하는 가장 좋은 방법은 모듈과 유형 이름을 매개변수로 지정하는 것입니다:

    Singleton *singleton
            = engine->singletonInstance<Singleton *>("MyModule", "Singleton");
    singleton->setThing(77);

객체 속성 사용하기

특정 컴포넌트의 QML 요소에만 일부 속성을 노출하려면 해당 속성을 컴포넌트의 루트 개체에 일반 속성으로 추가하면 됩니다. 모든 경우에 실제로 설정되도록 하려면 해당 프로퍼티를 필수 프로퍼티로 만들면 됩니다. 다음과 같이 QML 컴포넌트를 작성할 수 있습니다:

pragma ComponentBehavior: Bound

import QtQuick

Window {
    id: root
    visible: true

    required property int thing

    Text {
        anchors.fill: parent
        text: "The thing is " + root.thing
    }

    component Inner: QtObject {
        objectName: "I can see " + root.thing + " because I'm bound."
    }
}

컴포넌트의 루트 요소에 ID를 사용하고 모든 내부 객체에서 ID와 이름으로 프로퍼티를 참조합니다. 중첩된 컴포넌트에서 루트 엘리먼트의 ID를 안전하게 사용할 수 있도록 하기 위해 ComponentBehavior를 사용합니다.

그런 다음 C++에서 이러한 컴포넌트에서 객체를 만들 때 QQmlComponent::createWithInitialProperties, QQmlApplicationEngine::setInitialProperties 또는 QQuickView::setInitialProperties 를 호출하여 프로퍼티를 초기화해야 합니다. 예를 들어

    QQmlEngine engine;

    QQmlComponent component(&engine, "MyModule", "RequiredProperties");
    QScopedPointer<QObject> o(component.createWithInitialProperties({
            {"thing", 11}
    }));

모듈 URI가 MyModule이고 모듈이 QML 가져오기 경로에서 사용 가능하다고 가정합니다.

© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.