本页内容

入门指南Qt Quick Controls

此处展示了一个使用控件的 QML 文件的基本示例:

import QtQuick
import QtQuick.Controls

ApplicationWindow {
    title: "My Application"
    width: 640
    height: 480
    visible: true

    Button {
        text: "Push Me"
        anchors.centerIn: parent
    }
}

从 C++ 设置控件

虽然QQuickView 传统上被用于在C++应用程序中显示QML文件,但这样做意味着您只能从C++设置窗口属性。

使用Qt Quick Controls 时,请将ApplicationWindow 声明为应用程序的根项,并改用QQmlApplicationEngine 来启动它。这样可以确保您能够从QML中控制顶级窗口的属性。

以下是一个使用控件的源文件的基本示例:

#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char *argv[])
{
    QGuiApplication app(argc, argv);
    QQmlApplicationEngine engine;
    engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
    return app.exec();
}

从 QML 使用 C++ 数据

若需注册一个 C++ 类以便在 QML 中使用,可在声明QQmlApplicationEngine 之前调用qmlRegisterType()。更多信息请参阅《从 C++ 定义 QML 类型》。

若需向 QML 组件公开数据,则需确保这些数据可在当前 QML 引擎的环境中使用。更多信息请参阅《QQmlContext 》。

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