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 <QGuiApplication>
#include <QQmlApplicationEngine>


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
    在这里插入图片描述
    在这里插入图片描述

  2. 添加前缀
    在这里插入图片描述

  3. 添加文件
    在这里插入图片描述
    在这里插入图片描述

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

在这里插入图片描述

RESOURCES += resource.qrc \
    resources.qrc
  1. 修改main.cpp(如果需要的话)
    在这里插入图片描述

  2. 修改main.qml
    在这里插入图片描述

  3. 编译成功
    在这里插入图片描述

总结

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

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值