以下内容是根据docs完成的。
我的项目结构(简化):
./
│
├── qml/
│ ├── misc/
│ │ ├── SplashScreen.qml
│ │ └── qmldir
│ │
│ ├── main/
│ │ ├── Main.qml
│ │ └── qmldir
│ │
│ └ qmldir
qml/文件夹下的qmldir
module qml
qml/misc/文件夹下的qmldir:
module qml.misc
SplashScreen 1.0 SplashScreen.qml
qml/main/文件夹下的qmldir:
module qml.main
资源.qrc:
<!DOCTYPE RCC><RCC version="1.0">
<qresource>
<file alias="main">qml/main/Main.qml</file>
<file>qml/main/qmldir</file>
</qresource>
<qresource prefix="/qml">
<file>qmldir</file>
</qresource>
</RCC>
然后我将 qml 路径添加到 main.py 中的引擎路径中:
path = "C:/Users/Bob/Repos/TestApp/qml"
self.engine.addImportPath(QUrl.fromLocalFile(path).toString())
print(self.engine.importPathList()) # I make sure it's there at the beginning
...
self.engine.load(QUrl("qrc:/main"))
最后,我在 Main.qml 中导入 SplashScreen:
import QtCore
import QtQuick
import qml.misc
错误:qrc:/main:3:1:模块“qml.misc”未安装
我做错了什么?
//编辑
已修复,通过编辑并手动输入 resources.qrc 中的所有文件路径,我确信我必须只列出 qmldir 文件,但自从在那里添加所有 .qml 文件后,错误就消失了。
首先是模块。这里要注意的最重要的事情是它们有文件夹名称。子文件夹用
.
展开。例如:qml
文件夹。如果展开,则必须在末尾添加子文件夹。 qml.main
。当然这只是一个例子。
module qml.main
Main 1.0 Main.qml
可以使用
import qml.misc
导入 SplashScreen
module qml.misc
SplashScreen 1.0 SplashScreen.qml
这个 qmldir 导入其他两个模块,可以与
import qml
一起使用。 (但是将 main 放在模块中是没有意义的,但我将在此处展示它以进行演示)
module qml
import qml.misc auto
import qml.main auto
使整个事情顺利进行。应添加导入路径。如果您想让您的生活更轻松,请使用此:
engine.addImportPath(":/");
在这个例子中,网址是const QUrl url(QStringLiteral("qrc:/qml/main/Main.qml"));
(如果有人感兴趣的话)
<RCC>
<qresource prefix="/">
<file>qml/qmldir</file>
<file>qml/main/Main.qml</file>
<file>qml/main/qmldir</file>
<file>qml/misc/qmldir</file>
<file>qml/misc/SplashScreen.qml</file>
</qresource>
</RCC>
您不必将路径插入
.pro
本身
这是一个工作示例:
SplashScreen.qml
import QtQuick 2.15
Rectangle {
width: 100
height: 100
color: "green"
}
Main.qml
import QtQuick
import qml.misc 1.0 // or import qml 1.0
Window {
width: 640
height: 480
visible: true
SplashScreen{
x: 10
y: 10
}
SplashScreen{
x: 120
y: 10
}
}