QQmlComponent Class
QQmlComponent 클래스는 QML 컴포넌트 정의를 캡슐화합니다. 더 보기...
Header: | #include <QQmlComponent> |
CMake: | find_package(Qt6 REQUIRED COMPONENTS Qml) target_link_libraries(mytarget PRIVATE Qt6::Qml) |
qmake: | QT += qml |
QML에서: | Component |
상속합니다: | QObject |
공용 유형
enum | CompilationMode { PreferSynchronous, Asynchronous } |
enum | Status { Null, Ready, Loading, Error } |
속성
공공 기능
QQmlComponent(QQmlEngine *engine, QObject *parent = nullptr) | |
QQmlComponent(QQmlEngine *engine, const QString &fileName, QObject *parent = nullptr) | |
QQmlComponent(QQmlEngine *engine, const QUrl &url, QObject *parent = nullptr) | |
QQmlComponent(QQmlEngine *engine, const QString &fileName, QQmlComponent::CompilationMode mode, QObject *parent = nullptr) | |
QQmlComponent(QQmlEngine *engine, const QUrl &url, QQmlComponent::CompilationMode mode, QObject *parent = nullptr) | |
(since 6.5) | QQmlComponent(QQmlEngine *engine, QAnyStringView uri, QAnyStringView typeName, QObject *parent = nullptr) |
(since 6.5) | QQmlComponent(QQmlEngine *engine, QAnyStringView uri, QAnyStringView typeName, QQmlComponent::CompilationMode mode, QObject *parent = nullptr) |
virtual | ~QQmlComponent() override |
virtual QObject * | beginCreate(QQmlContext *context) |
virtual void | completeCreate() |
virtual QObject * | create(QQmlContext *context = nullptr) |
void | create(QQmlIncubator &incubator, QQmlContext *context = nullptr, QQmlContext *forContext = nullptr) |
QObject * | createWithInitialProperties(const QVariantMap &initialProperties, QQmlContext *context = nullptr) |
QQmlContext * | creationContext() const |
QQmlEngine * | engine() const |
QList<QQmlError> | errors() const |
(since 6.5) bool | isBound() const |
bool | isError() const |
bool | isLoading() const |
bool | isNull() const |
bool | isReady() const |
qreal | progress() const |
void | setInitialProperties(QObject *object, const QVariantMap &properties) |
QQmlComponent::Status | status() const |
QUrl | url() const |
공용 슬롯
(since 6.5) void | loadFromModule(QAnyStringView uri, QAnyStringView typeName, QQmlComponent::CompilationMode mode = PreferSynchronous) |
void | loadUrl(const QUrl &url) |
void | loadUrl(const QUrl &url, QQmlComponent::CompilationMode mode) |
void | setData(const QByteArray &data, const QUrl &url) |
신호
void | progressChanged(qreal progress) |
void | statusChanged(QQmlComponent::Status status) |
상세 설명
컴포넌트는 잘 정의된 인터페이스를 갖춘 재사용 가능한 캡슐화된 QML 유형입니다.
QQmlComponent 인스턴스는 QML 파일에서 만들 수 있습니다. 예를 들어 다음과 같은 main.qml
파일이 있습니다:
import QtQuick 2.0 Item { width: 200 height: 200 }
다음 코드는 이 QML 파일을 컴포넌트로 로드하고 create()를 사용하여 이 컴포넌트의 인스턴스를 생성한 다음 Item 의 width 값을 쿼리합니다:
QQmlEngine *engine = new QQmlEngine; QQmlComponent component(engine, QUrl::fromLocalFile("main.qml")); QObject *myObject = component.create(); QQuickItem *item = qobject_cast<QQuickItem*>(myObject); int width = item->width(); // width = 200
QQmlEngine 인스턴스를 사용할 수 없는 코드에서 컴포넌트의 인스턴스를 만들려면 qmlContext() 또는 qmlEngine()를 사용하면 됩니다. 예를 들어 아래 시나리오에서는 QQuickItem 하위 클래스 내에서 자식 항목이 생성됩니다:
void MyCppItem::init() { QQmlEngine *engine = qmlEngine(this); // Or: // QQmlEngine *engine = qmlContext(this)->engine(); QQmlComponent component(engine, QUrl::fromLocalFile("MyItem.qml")); QQuickItem *childItem = qobject_cast<QQuickItem*>(component.create()); childItem->setParentItem(this); }
이 함수는 QObject 하위 클래스의 생성자 내부에서 호출하면 null
인스턴스가 아직 컨텍스트나 엔진을 가지고 있지 않으므로 반환됩니다.
네트워크 컴포넌트
QQmlComponent에 전달된 URL이 네트워크 리소스이거나 QML 문서가 네트워크 리소스를 참조하는 경우, QQmlComponent는 객체를 생성하기 전에 네트워크 데이터를 가져와야 합니다. 이 경우 QQml 컴포넌트에는 Loading status . 애플리케이션은 QQmlComponent::create()을 호출하기 전에 컴포넌트가 Ready 가 될 때까지 기다려야 합니다.
다음 예는 네트워크 리소스에서 QML 파일을 로드하는 방법을 보여줍니다. QQml 컴포넌트를 생성한 후 컴포넌트가 로드 중인지 테스트합니다. 로드 중이면 QQmlComponent::statusChanged() 신호에 연결하고 그렇지 않으면 continueLoading()
메서드를 직접 호출합니다. 컴포넌트가 캐시되어 즉시 준비된 경우 네트워크 컴포넌트에 대해 QQmlComponent::isLoading()가 거짓일 수 있다는 점에 유의하세요.
MyApplication::MyApplication() { // ...component = new QQmlComponent(엔진, QUrl("http://www.example.com/main.qml")); if (component->isLoading()) { QObject::connect(component, &QQmlComponent::statusChanged, this, &MyApplication::continueLoading); } else { continueLoading(); } }void MyApplication::continueLoading() { if (component->isError()) { qWarning() << component->errors(); } else { QObject *myObject = component->create(); } }
멤버 타입 문서
enum QQmlComponent::CompilationMode
QQmlComponent 컴포넌트를 즉시 로드할지, 비동기식으로 로드할지 지정합니다.
Constant | 값 | 설명 |
---|---|---|
QQmlComponent::PreferSynchronous | 0 | 컴포넌트를 즉시 로드/컴파일하여 스레드를 차단하는 것을 선호합니다. 항상 가능한 것은 아니며, 예를 들어 원격 URL은 항상 비동기적으로 로드됩니다. |
QQmlComponent::Asynchronous | 1 | 백그라운드 스레드에서 컴포넌트를 로드/컴파일합니다. |
enum QQmlComponent::Status
QQmlComponent 의 로딩 상태를 지정합니다.
Constant | 값 | 설명 |
---|---|---|
QQmlComponent::Null | 0 | 이 QQmlComponent 에는 데이터가 없습니다. QML 콘텐츠를 추가하려면 loadUrl() 또는 setData()를 호출하세요. |
QQmlComponent::Ready | 1 | QQmlComponent 이 준비되었으며 create()를 호출할 수 있습니다. |
QQmlComponent::Loading | 2 | 이 QQmlComponent 은 네트워크 데이터를 로드하는 중입니다. |
QQmlComponent::Error | 3 | 오류가 발생했습니다. errors ()를 호출하여 errors 목록을 검색하세요. |
속성 문서
[read-only]
progress : const qreal
0.0(아무것도 로드되지 않음)에서 1.0(완료)까지의 컴포넌트 로드 진행률입니다.
액세스 기능:
qreal | progress() const |
알림 신호:
void | progressChanged(qreal progress) |
[read-only]
status : const Status
컴포넌트의 현재 status.
기능에 액세스합니다:
QQmlComponent::Status | status() const |
알림 신호:
void | statusChanged(QQmlComponent::Status status) |
[read-only]
url : const QUrl
컴포넌트 URL입니다. 생성자나 loadUrl() 또는 setData() 메서드에 전달되는 URL입니다.
액세스 함수:
QUrl | url() const |
멤버 함수 문서
QQmlComponent::QQmlComponent(QQmlEngine *engine, QObject *parent = nullptr)
데이터가 없는 QQml 컴포넌트를 생성하고 지정된 engine 및 parent 을 제공합니다. setData ()로 데이터를 설정합니다.
QQmlComponent::QQmlComponent(QQmlEngine *engine, const QString &fileName, QObject *parent = nullptr)
주어진 fileName 에서 QQml 컴포넌트를 생성하고 지정된 parent 및 engine 을 지정합니다.
loadUrl()도 참조하세요 .
QQmlComponent::QQmlComponent(QQmlEngine *engine, const QUrl &url, QObject *parent = nullptr)
주어진 url 에서 QQml 컴포넌트를 생성하고 지정된 parent 및 engine 을 지정합니다.
특히 로컬 파일 시스템에서 파일을 로드할 때는 QUrl::fromLocalFile()를 사용하여 제공된 URL이 완전하고 올바른지 확인하세요.
상대 경로는 지정하지 않는 한 현재 작업 디렉터리인 QQmlEngine::baseUrl()를 기준으로 확인됩니다.
loadUrl()도 참조하세요 .
QQmlComponent::QQmlComponent(QQmlEngine *engine, const QString &fileName, QQmlComponent::CompilationMode mode, QObject *parent = nullptr)
주어진 fileName 에서 QQmlComponent를 생성하고 지정된 parent 및 engine 을 지정합니다. mode 이 Asynchronous 인 경우 컴포넌트는 비동기적으로 로드 및 컴파일됩니다.
loadUrl()도 참조하세요 .
QQmlComponent::QQmlComponent(QQmlEngine *engine, const QUrl &url, QQmlComponent::CompilationMode mode, QObject *parent = nullptr)
주어진 url 에서 QQml 컴포넌트를 생성하고 지정된 parent 과 engine 을 지정합니다. mode 이 Asynchronous 인 경우 컴포넌트는 비동기적으로 로드 및 컴파일됩니다.
특히 로컬 파일 시스템에서 파일을 로드할 때는 QUrl::fromLocalFile()를 사용하는 등 제공된 URL이 완전하고 올바른지 확인하세요.
상대 경로는 지정하지 않는 한 현재 작업 디렉터리인 QQmlEngine::baseUrl()를 기준으로 확인됩니다.
loadUrl()도 참조하세요 .
[explicit, since 6.5]
QQmlComponent::QQmlComponent(QQmlEngine *engine, QAnyStringView uri, QAnyStringView typeName, QObject *parent = nullptr)
주어진 uri 및 typeName 에서 QQmlComponent를 생성하고 지정된 parent 및 engine 을 지정합니다. 가능하면 컴포넌트가 동기식으로 로드됩니다.
이것은 오버로드된 함수입니다.
이 함수는 Qt 6.5에 도입되었습니다.
loadFromModule()도 참조하십시오 .
[explicit, since 6.5]
QQmlComponent::QQmlComponent(QQmlEngine *engine, QAnyStringView uri, QAnyStringView typeName, QQmlComponent::CompilationMode mode, QObject *parent = nullptr)
주어진 uri 및 typeName 에서 QQmlComponent를 생성하고 지정된 parent 및 engine 을 지정합니다. mode 이 Asynchronous 인 경우 컴포넌트는 비동기적으로 로드 및 컴파일됩니다.
이것은 오버로드된 함수입니다.
이 함수는 Qt 6.5에 도입되었습니다.
loadFromModule()도 참조하십시오 .
[override virtual noexcept]
QQmlComponent::~QQmlComponent()
QQmlComponent 을 파괴합니다.
[virtual]
QObject *QQmlComponent::beginCreate(QQmlContext *context)
지정된 context 내에서 이 컴포넌트에서 객체 인스턴스를 생성합니다. 생성에 실패하면 nullptr
을 반환합니다.
참고: 이 메서드는 컴포넌트 인스턴스 생성에 대한 고급 제어 기능을 제공합니다. 일반적으로 프로그래머는 QQmlComponent::create()를 사용하여 객체 인스턴스를 생성해야 합니다.
QQmlComponent 이 인스턴스를 생성할 때는 세 단계로 이루어집니다:
- 객체 계층 구조가 생성되고 상수 값이 할당됩니다.
- 속성 바인딩이 처음으로 평가됩니다.
- 해당되는 경우 객체에서 QQmlParserStatus::componentComplete()가 호출됩니다.
QQmlComponent::beginCreate()는 1단계만 수행한다는 점에서 QQmlComponent::create()와 다릅니다. 2단계와 3단계를 완료하려면 QQmlComponent::completeCreate()를 호출해야 합니다.
이 중단점은 속성 바인딩이 적용되기 전에 초기 값을 구성할 수 있기 때문에 연결된 속성을 사용하여 인스턴스화된 컴포넌트에 정보를 전달할 때 유용할 때가 있습니다.
반환된 객체 인스턴스의 소유권은 호출자에게 이전됩니다.
참고: 바인딩을 상수 값과 실제 바인딩으로 분류하는 것은 의도적으로 지정되지 않았으며, Qt 버전에 따라 그리고 qmlcachegen 사용 여부와 방법에 따라 변경될 수 있습니다. 특정 바인딩에 의존하여 startCreate() 반환 전이나 후에 평가해서는 안 됩니다. 예를 들어 MyType.EnumValue와 같은 상수 표현식은 컴파일 시 이를 인식하거나 바인딩으로 실행되도록 지연될 수 있습니다. -(5) 또는 "a" + " 상수 문자열"과 같은 상수 표현식도 마찬가지입니다.
completeCreate() 및 QQmlEngine::ObjectOwnership 을참조하세요 .
[virtual]
void QQmlComponent::completeCreate()
이 메서드는 컴포넌트 인스턴스 생성에 대한 고급 제어 기능을 제공합니다. 일반적으로 프로그래머는 컴포넌트를 생성할 때 QQmlComponent::create()를 사용해야 합니다.
이 함수는 QQmlComponent::beginCreate()로 시작된 컴포넌트 생성을 완료하며 이후 반드시 호출해야 합니다.
beginCreate()도 참조하세요 .
[virtual]
QObject *QQmlComponent::create(QQmlContext *context = nullptr)
지정된 context 내에서 이 컴포넌트에서 객체 인스턴스를 생성합니다. 생성에 실패하면 nullptr
을 반환합니다.
context 가 nullptr
(기본값)인 경우 엔진의 root context 에 인스턴스를 생성합니다.
반환된 객체 인스턴스의 소유권은 호출자에게 이전됩니다.
이 컴포넌트에서 생성되는 객체가 시각적 항목인 경우 QQuickItem::setParentItem()를 호출하여 설정할 수 있는 시각적 부모가 있어야 합니다. 자세한 내용은 Qt Quick 의 개념 - 시각적 부모를 참조하세요.
QQmlEngine::ObjectOwnership 를참조하세요 .
void QQmlComponent::create(QQmlIncubator &incubator, QQmlContext *context = nullptr, QQmlContext *forContext = nullptr)
제공된 incubator 을 사용하여 이 컴포넌트에서 객체 인스턴스를 생성합니다. context 은 객체 인스턴스를 생성할 컨텍스트를 지정합니다.
context 가 nullptr
(기본값)인 경우 엔진의 root context 에 인스턴스를 생성합니다.
forContext 는 이 객체 생성이 의존하는 컨텍스트를 지정합니다. forContext 이 비동기적으로 생성되고 QQmlIncubator::IncubationMode 이 QQmlIncubator::AsynchronousIfNested 인 경우 이 객체도 비동기적으로 생성됩니다. forContext 가 nullptr
(기본값)인 경우 context 가 이 결정에 사용됩니다.
생성된 객체와 생성 상태는 incubator 에서 확인할 수 있습니다.
QQmlIncubator도 참조하세요 .
QObject *QQmlComponent::createWithInitialProperties(const QVariantMap &initialProperties, QQmlContext *context = nullptr)
지정된 context 내에 이 컴포넌트의 객체 인스턴스를 생성하고 최상위 프로퍼티를 initialProperties 으로 초기화합니다.
initialProperties 중 하나라도 설정할 수 없으면 경고가 표시됩니다. 설정되지 않은 필수 속성이 있는 경우 객체 생성이 실패하고 nullptr
을 반환하며, 이 경우 isError()은 true
을 반환합니다.
QQmlComponent::create도 참조하세요 .
QQmlContext *QQmlComponent::creationContext() const
컴포넌트가 생성된 QQmlContext 을 반환합니다. 이 함수는 QML에서 직접 생성된 컴포넌트에만 유효합니다.
QQmlEngine *QQmlComponent::engine() const
이 컴포넌트의 QQmlEngine 를 반환합니다.
QList<QQmlError> QQmlComponent::errors() const
마지막 컴파일 또는 생성 작업 중에 발생한 오류 목록을 반환합니다. isError ()가 설정되지 않은 경우 빈 목록이 반환됩니다.
[since 6.5]
bool QQmlComponent::isBound() const
컴포넌트가 pragma ComponentBehavior: Bound
을 지정하는 QML 파일에서 생성된 경우 참을 반환하고, 그렇지 않으면 거짓을 반환합니다.
이 함수는 Qt 6.5에 도입되었습니다.
bool QQmlComponent::isError() const
status() == QQmlComponent::Error 이면 참을 반환합니다.
bool QQmlComponent::isLoading() const
status() == QQmlComponent::Loading 이면 참을 반환합니다.
bool QQmlComponent::isNull() const
status() == QQmlComponent::Null 이면 참을 반환합니다.
bool QQmlComponent::isReady() const
status() == QQmlComponent::Ready 이면 참을 반환합니다.
[slot, since 6.5]
void QQmlComponent::loadFromModule(QAnyStringView uri, QAnyStringView typeName, QQmlComponent::CompilationMode mode = PreferSynchronous)
uri 모듈에서 typeName 에 대한 QQmlComponent 을 로드합니다. 유형이 QML 파일을 통해 구현된 경우 mode 을 사용하여 로드합니다. C++로 지원되는 타입은 항상 동기식으로 로드됩니다.
QQmlEngine engine; QQmlComponent component(&engine); component.loadFromModule("QtQuick", "Item"); // once the component is ready std::unique_ptr<QObject> item(component.create()); Q_ASSERT(item->metaObject() == &QQuickItem::staticMetaObject);
이 함수는 Qt 6.5에 도입되었습니다.
loadUrl()도 참조하십시오 .
[slot]
void QQmlComponent::loadUrl(const QUrl &url)
제공된 url 에서 QQmlComponent 을 로드합니다.
특히 로컬 파일 시스템에서 파일을 로드할 때는 QUrl::fromLocalFile()를 사용하는 등 제공된 URL이 완전하고 올바른지 확인하세요.
상대 경로는 지정하지 않는 한 현재 작업 디렉터리인 QQmlEngine::baseUrl()를 기준으로 확인됩니다.
[slot]
void QQmlComponent::loadUrl(const QUrl &url, QQmlComponent::CompilationMode mode)
제공된 url 에서 QQmlComponent 을 로드합니다. mode 이 Asynchronous 인 경우 컴포넌트가 비동기적으로 로드되고 컴파일됩니다.
특히 로컬 파일 시스템에서 파일을 로드할 때는 QUrl::fromLocalFile()를 사용하는 등 제공된 URL이 완전하고 올바른지 확인하세요.
상대 경로는 지정되지 않는 한 현재 작업 디렉터리인 QQmlEngine::baseUrl()를 기준으로 확인됩니다.
[signal]
void QQmlComponent::progressChanged(qreal progress)
컴포넌트의 로딩 진행률이 변경될 때마다 발생합니다. progress 현재 진행률은 0.0(아무것도 로드되지 않음)에서 1.0(완료) 사이입니다.
참고: 프로퍼티 progress 에 대한 알림 신호.
[slot]
void QQmlComponent::setData(const QByteArray &data, const QUrl &url)
주어진 QML data 을 사용하도록 QQmlComponent 을 설정합니다. url 이 제공되면 컴포넌트 이름을 설정하고 이 컴포넌트에서 확인되는 항목의 기본 경로를 제공하는 데 사용됩니다.
void QQmlComponent::setInitialProperties(QObject *object, const QVariantMap &properties)
QQmlComponent 에서 생성된 object 의 최상위 수준 properties 을 설정합니다.
이 방법은 컴포넌트 인스턴스 생성에 대한 고급 제어 기능을 제공합니다. 일반적으로 프로그래머는 컴포넌트에서 객체 인스턴스를 생성할 때 QQmlComponent::createWithInitialProperties 을 사용해야 합니다.
beginCreate 이후 completeCreate 이 호출되기 전에 이 메서드를 사용하세요. 제공된 프로퍼티가 존재하지 않으면 경고가 표시됩니다.
이 메서드에서는 초기 중첩 프로퍼티를 직접 설정할 수 없습니다. 대신 중첩된 속성이 있는 값 유형 속성의 초기값을 설정하려면 해당 값 유형을 생성하고 중첩된 속성을 지정한 다음 생성할 객체의 초기 속성으로 값 유형을 전달할 수 있습니다.
예를 들어 fond.bold를 설정하려면 QFont 를 생성하고 가중치를 굵게로 설정한 다음 글꼴을 초기 속성으로 전달하면 됩니다.
[signal]
void QQmlComponent::statusChanged(QQmlComponent::Status status)
컴포넌트의 상태가 변경될 때마다 발생하며 status 이 새 상태가 됩니다.
참고: 프로퍼티에 대한 알림 신호 status.
© 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.