C++의 상태를 QML에 노출하기
특정 컴포넌트 내의 모든 QML 요소, 모듈 내의 모든 QML 요소, 또는 전체 QML 요소에 C++의 일부 속성을 노출시키는 것이 종종 바람직합니다. 이를 위해서는 싱글톤을 도입하거나, 선택한 컴포넌트의 루트 객체에 속성을 추가하면 됩니다.
싱글톤 사용
모듈 내의 모든 요소나 전체 QML 요소에 여러 전역 속성을 노출하려면 C++에서 싱글톤을 정의할 수 있습니다. 이를 위해, 노출하려는 속성을 ` Q_PROPERTY ` 선언으로 포함하는 클래스에 ` QML_ELEMENT ` 또는 ` QML_NAMED_ELEMENT ` 매크로와 ` QML_SINGLETON ` 매크로를 추가합니다:
// 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 코드에서 싱글톤의 ` thing ` 속성에 접근할 수 있습니다:
import QtQml
QtObject {
objectName: "The thing is " + Singleton.thing
}QML 파일을 모듈과 동일한 디렉터리에 배치한 경우(이 방법을 적극 권장합니다), 모듈 내의 암시적 임포트를 통해 싱글톤을 사용할 수 있습니다. 별도로 명시적으로 임포트할 필요가 없습니다. 그렇지 않은 경우, 또는 다른 모듈에서 thing 속성에 접근하려는 경우에는 싱글톤이 속한 모듈을 명시적으로 임포트해야 합니다.
C++에서 속성의 값을 설정하려면 싱글톤 인스턴스를 가져와야 할 수 있습니다. 이를 위해 ` QQmlEngine::singletonInstance`를 사용할 수 있습니다. 가장 권장되는 방법은 모듈과 유형 이름을 매개변수로 전달하는 것입니다:
Singleton *singleton
= engine->singletonInstance<Singleton *>("MyModule", "Singleton");
singleton->setThing(77);객체 속성 사용
특정 컴포넌트 내의 QML 요소에만 일부 속성을 노출하려면, 해당 속성을 컴포넌트의 루트 객체에 일반 속성으로 추가할 수 있습니다. 모든 경우에 해당 속성이 실제로 설정되도록 하려면, 이를 필수 속성(Required Properties) 으로 지정할 수 있습니다. 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 임포트 경로에 존재한다고 가정합니다.
© 2026 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.