问题
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
文件目录
解决方法
-
新建Qt Resource File
-
添加前缀
-
添加文件
-
修改项目配置(如果需要的话)
RESOURCES += resource.qrc \
resources.qrc
-
修改main.cpp(如果需要的话)
-
修改main.qml
-
编译成功
总结
有大佬知道为什么要这样做吗?
这种方法挺麻烦的,请问还有其他方法吗?