本页内容

初始化QML Runtime

QML文档由QML Runtime加载并运行。QML Runtime还提供了对其他Qt或第三方QML模块及类型的访问。

此外,Qt 框架还提供了qml 工具,该工具可加载.qml 文件。此工具有助于开发和测试 QML 代码,而无需编写 C++ 应用程序来加载 QML Runtime。

要运行使用 QML 的应用程序,您的应用程序必须调用 QML Runtime。要调用 QML Runtime:

在 C++ 应用程序中初始化QML Runtime

使用 QQuickView 进行初始化

QQuickView 是一个基于QWindow 的类,可以加载QML文件。例如,如果有一个QML文件application.qml ,其代码将如下所示:

import QtQuick

Rectangle { width: 100; height: 100; color: "red" }

可以在 Qt 应用程序的main.cpp 文件中按如下方式加载它:

#include <QGuiApplication>
#include <QQuickView>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQuickView view;
    view.setSource(QUrl::fromLocalFile("application.qml"));
    view.show();

    return app.exec();
}

这将创建一个基于QWindow 的视图,用于显示application.qml 的内容。

构建文件

使用find_package() 命令在Qt6 包中查找所需的模块组件:

find_package(Qt6 REQUIRED COMPONENTS Quick)
target_link_libraries(mytarget PRIVATE Qt6::Quick)

更多详细信息,请参阅《使用 CMake 构建》概述。

要配置该模块以便使用 qmake 进行构建,请在项目的 .pro 文件中将该模块作为QT 变量的值添加:

QT += quick

有关更多信息,请参阅《创建项目文件》。

直接创建 QQmlEngine

如果application.qml 中没有图形组件,或者出于其他原因希望避免使用QQuickView ,则可以直接构建QQmlEngine 。在这种情况下,application.qml 将作为QQmlComponent 实例加载,而不是放置在视图中:

#include <QGuiApplication>
#include <QQmlEngine>
#include <QQmlContext>
#include <QQmlComponent>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);

    QQmlEngine engine;
    QQmlContext *objectContext = new QQmlContext(engine.rootContext());

    QQmlComponent component(&engine, "application.qml");
    QObject *object = component.create(objectContext);

    // ... delete object and objectContext when necessary

    return app.exec();
}

如果您未使用Qt Quick 中的任何图形控件,可以在上述代码中将QGuiApplication 替换为QCoreApplication 。这样,您就可以将 QML 作为一种语言来使用,而无需依赖 Qt GUI 模块。

© 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.