I wrote a simple example while learning QML and CMake. The main purpose is to demonstrate how to use `qt_add_qml_module` and how to register C++ classes in QML.
the key code is as follows:
**//CMakeLists.txt**
add_subdirectory(mybackend)
qt_add_executable(appMyMain
main.cpp
)
qt_add_qml_module(appMyMain
URI "MainApp"
RESOURCE_PREFIX /mycompany/mainapp
VERSION 1.0
QML_FILES Main.qml
)
target_link_libraries(appMyMain PRIVATE Qt6::Quick BackendLib)
qt_finalize_executable(appMyMain)
**//main.cpp**
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
engine.addImportPath(":/mycompany/imports");
const QUrl url(u"qrc:/mycompany/mainapp/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();
}
**//Main.qml**
import QtQuick
import QtQuick.Controls
import MyCompany.Backend
**//mybackend/CMakeLists.txt**
qt_add_library(BackendLib STATIC)
set_target_properties(BackendLib PROPERTIES AUTOMOC ON)
qt_add_qml_module(BackendLib
URI "MyCompany.Backend"
RESOURCE_PREFIX /mycompany/mainapp
VERSION 1.0
SOURCES
MyBackend.h
MyBackend.cpp
)
target_link_libraries(BackendLib PRIVATE Qt6::Quick)
**//mybackend/Mybackend.h**
#include <QObject>
#include <QtQml>
class MyBackend : public QObject
{
Q_OBJECT
QML_ELEMENT
Q_PROPERTY(QString userName READ userName WRITE setUserName NOTIFY userNameChanged)
Then I received the following error message:
QQmlComponent: attempted to load via a relative URL 'qrc:qt/qml/mycompany/mainapp/Main.qml' in resource file system. This is not fully supported and may not work
QQmlApplicationEngine failed to load component
qrc:qt/qml/mycompany/mainapp/Main.qml: No such file or directory
I have already asked the AI, but it didn't provide me with any effective solutions.
engine.loadFromModule("MainApp", "Main.qml");instead ofengine.load?