找不到QML组件,即使在同一目录中也是如此 我正在创建C++ /QML应用程序。在调试版本中,我希望直接从文件加载QML,在发布版本中,我希望从资源加载QML。我想为此使用QDir::setSearchPath: void GuiController::initQmlPath() { #ifdef QT_DEBUG QDir dir( QApplication::applicationDirPath() ); const bool success = dir.cd( "../../Game/Qml" ); // Depends on project structure Q_ASSERT( success ); QDir::setSearchPaths( "qml", QStringList( dir.absolutePath() ) ); #else QDir::setSearchPaths( "qml", QStringList( ":/Game/Qml" ) ); #endif }

找不到QML组件,即使在同一目录中也是如此 我正在创建C++ /QML应用程序。在调试版本中,我希望直接从文件加载QML,在发布版本中,我希望从资源加载QML。我想为此使用QDir::setSearchPath: void GuiController::initQmlPath() { #ifdef QT_DEBUG QDir dir( QApplication::applicationDirPath() ); const bool success = dir.cd( "../../Game/Qml" ); // Depends on project structure Q_ASSERT( success ); QDir::setSearchPaths( "qml", QStringList( dir.absolutePath() ) ); #else QDir::setSearchPaths( "qml", QStringList( ":/Game/Qml" ) ); #endif },qt,qml,Qt,Qml,我将以下一种方式加载组件: connect( component, &QQmlComponent::statusChanged, stateSlot ); //component->loadUrl( QUrl( "qml:/MainWindow.qml" ) ); // Not working component->loadUrl( QUrl::fromLocalFile( "C:/Projects/Launcher/Game/Qml/MainWindow.qml" ) );

我将以下一种方式加载组件:

connect( component, &QQmlComponent::statusChanged, stateSlot );
//component->loadUrl( QUrl( "qml:/MainWindow.qml" ) ); // Not working
component->loadUrl( QUrl::fromLocalFile( "C:/Projects/Launcher/Game/Qml/MainWindow.qml" ) ); // OK
QUrl::fromLocalFile( QFileInfo( "qml:/MainWindow.qml" ).absoluteFilePath() );
当我在
loadUrl
中使用完整路径时-一切正常,但当我使用
qml:/main窗口时。找到了qml
-文件,但无法加载放在同一文件夹中的组件(简化):

主窗口.qml

Window {
  id: root
  visible: true
  CustomComponent {
  }
}
Rectangle {
  id: root
  color: "red"
}
CustomComponent.qml

Window {
  id: root
  visible: true
  CustomComponent {
  }
}
Rectangle {
  id: root
  color: "red"
}

如何解决?(如何通过searchPath在qml引擎中设置查找文件夹)

通过下一步创建url解决:

connect( component, &QQmlComponent::statusChanged, stateSlot );
//component->loadUrl( QUrl( "qml:/MainWindow.qml" ) ); // Not working
component->loadUrl( QUrl::fromLocalFile( "C:/Projects/Launcher/Game/Qml/MainWindow.qml" ) ); // OK
QUrl::fromLocalFile( QFileInfo( "qml:/MainWindow.qml" ).absoluteFilePath() );

检查
QUrl(“qml:/MainWindow.qml”)
是否生成有效的url。我不确定
QUrl
是否支持搜索路径。奇怪的是,找到了该文件,因为它显示了正确的错误(“qml:/MainWindow.qml:28 CustomComponent不是一种类型”),如果您回答了自己的问题,请将答案标记为已接受,以表明它解决了您的问题。确定。这以前是不可能的。