Search code examples
qtqmlqt6

How create a custom componemt in Qt 6.2?


I've been having that problem since I upgrade my Qt to 6.2 version. If I create a project in 5.15 version (like the project "untitled1" in the picture) I can create a new QML component ("Meutexto.qml" file) and call that in the main file. But, if I create the same thing in a 6.2 version project ("untitled"), I got the error: qrc:/untitled/main.qml:9:5: Meutexto is not a type.

The 6.2 version create a QML projec folder automatically and the 5.15 version use the Resources project folder to QML files. Can that problem be related to that?

More details:

I am having problem with the example in the picture and code below. I got that error in Qt 6.2:QQmlApplicationEngine failed to load component qrc:/untitled/main.qml:9:5: Meutexto is not a type. I don't get that error with the 5.15 version.

Project files

enter image description here

Code of main.qml:

import QtQuick
Window {
    width: 640
    height: 480
    visible: true
    title: qsTr("Hello World")

    Meutexto {}
}

Code of Meutexto.qml:

import QtQuick 2.0
Item {
    Text {
        anchors.centerIn: parent
        text: "My Text"
    }
}

Code of untitle.pro:

QT += quick

SOURCES += \
        main.cpp

resources.files = main.qml 
resources.prefix = /$${TARGET}
RESOURCES += resources \
    qml.qrc

# 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 += \
    Meutexto.qml

Code of qml.qrc:

<RCC>
    <qresource prefix="/">
        <file>main.qml</file>
        <file>Meutexto.qml</file>
    </qresource>
</RCC>

Solution

  • You didn't provide your main.cpp file, but I created a new project and noticed the default one that it generates uses a URL that looks like this:

    const QUrl url(u"qrc:/my_project/main.qml"_qs);
    

    It makes more sense to me to change it to this:

    const QUrl url(u"qrc:/main.qml"_qs);
    

    After that change, there are two ways to make your code work:

    1. Use the qml.qrc file the same way you did in Qt 5.15. With the change in main.cpp, You should not need to make any changes in your .qrc file.

    untitled.pro:

    RESOURCES += qml.qrc
    
    1. The other method seems to be a new way to automatically create resource files from within a .pro file. I'm not as familiar with this method, but it's documented here. In your .pro file, do this:
    resources.files = \
        main.qml \
        Meutexto.qml
    resources.prefix = /
    RESOURCES += resources
    

    This looks a little bit nicer since you no longer need to manually create a .qrc file.