如何在QML文件中导入QML组件资源



我有以下目录结构:

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

resources.qrc内容:

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

MyPresenter.qml内容:

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内容:

import "."
MyPresenter {
id: root
}

main.cpp内容:

#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();
}

当我运行应用程序时,我得到

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

如果我在main_window_presenter.qml删除import ".",我会得到

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

我认为我不需要import语句,因为它们在同一目录中。我正在使用介子构建系统,该系统与meson.build中的相关部分有关(前面定义了exe_moc_headers(:

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

正如@eyllanesc建议的那样,QQuickView可以代替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();
}

如果错误消息不是通过说"MyPresenter不是类型">来指示找不到类型,我可能已经自己想好了。这让我相信这是一个参考问题。

最新更新