1

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.

3
  • Does it work if you use engine.loadFromModule("MainApp", "Main.qml"); instead of engine.load? Commented Nov 25 at 16:06
  • It was indeed helpful!but why : ( Commented Nov 26 at 11:29
  • Your problem with engine.load is an import path problem. It's a common area of confusion, because internally Qt wants to look in qt/qml for imports. I think you could set a policy option in your cmake file to change this (See this link for more info). But it's much easier to not worry about paths and just use loadFromModule. Commented Nov 26 at 16:55

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.