QML导入自定义组件no such directory

问题

QML导入自定义组件no such directory

QQmlApplicationEngine failed to load component
qrc:/test/main.qml:2:1: "Box.qml": no such directory

代码

main.qml

import QtQuick
import 'Box.qml' as Box

Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")
}

Box.qml

import QtQuick 2.0

Item {

}

main.cpp

#include 
#include 


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

    QQmlApplicationEngine engine;
    const QUrl url(u"qrc:/test/main.qml"_qs);
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
        if (!obj && url == objUrl)
            QCoreApplication::exit(-1);
    }, Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}

test.pro

QT += quick

SOURCES += \
        main.cpp

resources.files = main.qml 
resources.prefix = /$${TARGET}
RESOURCES += resources

# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =

# Additional import path used to resolve QML modules just for Qt Quick Designer
QML_DESIGNER_IMPORT_PATH =

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

DISTFILES += \
    Box.qml

环境

Qt 6.2
Qt Creator 6.0.2
Desktop_Qt_6_2_3_MinGW_64_bit-Debug

文件目录

解决方法

  1. 新建Qt Resource File
    QML导入自定义组件no such directory_第1张图片
    QML导入自定义组件no such directory_第2张图片

  2. 添加前缀
    QML导入自定义组件no such directory_第3张图片

  3. 添加文件
    QML导入自定义组件no such directory_第4张图片
    QML导入自定义组件no such directory_第5张图片

  4. 修改项目配置(如果需要的话)

QML导入自定义组件no such directory_第6张图片

RESOURCES += resource.qrc \
    resources.qrc
  1. 修改main.cpp(如果需要的话)
    QML导入自定义组件no such directory_第7张图片

  2. 修改main.qml
    QML导入自定义组件no such directory_第8张图片

  3. 编译成功
    QML导入自定义组件no such directory_第9张图片

总结

有大佬知道为什么要这样做吗?
这种方法挺麻烦的,请问还有其他方法吗?

你可能感兴趣的:(qt)