If I use import MyModule 1.0 I got an error message what MyModule is not installed.
QQmlApplicationEngine failed to load component
qrc:/main.qml:3:1: module "MyModule" is not installed
But I correctly wrote qmldir file and resources file. And if I use import "MyModule" all is Ok. But I need to use import without quotes and import my modules in all files in different directories.
How to correctly import custom Qml element?
File structure
QMLDIRTEST
│ CMakeLists.txt
│ main.cpp
│ main.qml
│ qml.qrc
│
└───MyModule
qmldir
RedRectangle.qml
CMakeLists.txt
cmake_minimum_required(VERSION 3.14)
project(QmlDirTest VERSION 0.1 LANGUAGES CXX)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(QT NAMES Qt5 COMPONENTS Core Quick REQUIRED)
find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core Quick REQUIRED)
set(PROJECT_SOURCES main.cpp qml.qrc)
add_executable(QmlDirTest ${PROJECT_SOURCES})
target_link_libraries(QmlDirTest PRIVATE Qt${QT_VERSION_MAJOR}::Core Qt${QT_VERSION_MAJOR}::Quick)
qml.qrc
<RCC>
<qresource prefix="/">
<file>main.qml</file>
<file>MyModule/RedRectangle.qml</file>
<file>MyModule/qmldir</file>
</qresource>
</RCC>
main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
int main(int argc, char *argv[])
{
#if QT_VERSION < QT_VERSION_CHECK(6, 0, 0)
QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);
#endif
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
const QUrl url(QStringLiteral("qrc:/main.qml"));
QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
&app, [url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
}, Qt::QueuedConnection);
engine.addImportPath("qrc:/Ui");
engine.load(url);
return app.exec();
}
main.qml
import QtQuick 2.15
import QtQuick.Window 2.15
import MyModule 1.0
//import "MyModule"
Window {
width: 640
height: 480
visible: true
title: qsTr("Hello World")
RedRectangle { anchors.centerIn: parent }
}
RedRectangle.qml
import QtQuick 2.15
Rectangle {
width: 200
height: 100
color: "red"
}
qmldir
Module MyModule
RedRectangle 1.0 RedRectangle.qml
engine.addImportPath("qrc:/");.modulekeyword must be lowercase