qtqmlqt5qqmlapplicationengine

how to import a QML Component resource in a QML file


I have the following directory structure:

ui/
  |- resources.qrc
  |- qml/
    |- main_window_presenter.qml
    |- MyPresenter.qml

resources.qrc contents:

<RCC>
    <qresource prefix="/">
        <file>qml/MyPresenter.qml</file>
        <file>qml/main_window_presenter.qml</file>
    </qresource>
</RCC>

MyPresenter.qml contents:

import QtQuick 2.11

FocusScope {
  id: root

  property Item view
  property QtObject model

  Component.onCompleted: {
    root.view.anchors.fill = root
    root.view.focus = true
  }
}

main_window_presenter.qml contents:

import "."

MyPresenter {
  id: root
}

main.cpp contents:

#include <QGuiApplication>
#include <QQmlApplicationEngine>

int main(int argc, char **argv)
{
  QGuiApplication app(argc, argv);

  QQmlApplicationEngine engine;
  engine.load(":/qml/main_window_presenter.qml");

  return app.exec();
}

When I run the application I get

QQmlApplicationEngine failed to load component
file::/qml/main_window_presenter.qml:1 import "." has no qmldir and no namespace

If I delete import "." at main_window_presenter.qml I get

QQmlApplicationEngine failed to load component                                                                                                                             
file::/qml/main_window_presenter.qml:3 MyPresenter is not a type

I think I shouldn't need an import statement because they are in the same directory. I am using meson build system with this relevant part in meson.build(exe_moc_headers are defined before):

qt5_module = import('qt5')
exe_processed = qt5_module.preprocess(moc_headers : exe_moc_headers, qresources : 'ui/resources.qrc')

Solution

  • As @eyllanesc suggested QQuickView works instead of QQmlApplicationEngine:

    #include <QGuiApplication>
    #include <QQuickView>
    
    int main(int argc, char **argv)
    {
      QGuiApplication app(argc, argv);
    
      QQuickView* view{new QQuickView};
      view->setSource(QUrl("qrc:///qml/main_window_presenter.qml"));
      view->show();
    
      return app.exec();
    }
    

    I might have figured it myself if the error message wasn't indicating that type is not found by saying "MyPresenter is not a type". This led me to believe that its a referencing issue.