矩形作为 QML 中的根元素

Rectangle as a root element in QML

我使用 Qt 5.5.0 MSVC 2013,32 位。
我想创建最小的 QtQuick 应用程序。当我选择 New Project - Qt Quick Application 时,我得到了包含 2 个 QML 文件的项目:main.qmlMainForm.ui.qml。因为我不需要它们,所以我删除了第二个并粘贴到 main.qml:

Import QtQuick 2.4

Rectangle{
    id: root
    visible: true
    color: "gray"
    width: 400
    height: 800
}

但是当我 运行 项目时,我一无所获。我在 任务管理器 中看到应用程序,但没有应用程序 window。
问题:是否可以创建以 Rectangle 作为根元素的 .qml 文件?

Solution 是在官方 Qt 论坛上找到的。

The template for creating Qt Quick Application adds QQmlApplicationEngine to launch the QML. But QQmlApplicationEngine dont work directly with Rectangle or Item as root element but requires any window like Window or ApplicationWindow. So to make it work for Rectangle use QQuickView instead of QQmlApplicationEngine.

我将 main.cpp 的内容更改为

#include <QGuiApplication>
#include <QQuickView>

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

    QQuickView *view = new QQuickView;
    view->setSource(QUrl("qrc:/main.qml"));

    view->show();

    return app.exec();
}

它解决了我的问题。