开始使用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++ 数据

如果你需要从 QML 注册一个 C++ 类,你可以在声明QQmlApplicationEngine 之前调用qmlRegisterType() 。详见从 C++ 定义 QML 类型

如果你需要向 QML 组件公开数据,你需要让它们在当前 QML 引擎的上下文中可用。更多信息,请参阅QQmlContext

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