我的 QML 文件有一个类似的目录结构:
qml.qrc
main.qml
LockScreen/
LockScreen.qml
QuickMenu/
QuickMenu.qml
misc/
KeyboardInput.qml
Run Code Online (Sandbox Code Playgroud)
(我排除了其他文件,但这无关紧要)
我已将上述所有文件添加到我的 qrc 文件中,并为每个目录添加前缀:
<RCC>
<qresource prefix="/">
<file>main.qml</file>
<file>qtquickcontrols2.conf</file>
<file>MessagePopup.qml</file>
<file>MessagePopupForm.ui.qml</file>
</qresource>
<qresource prefix="/LockScreen">
<file>LockScreen/LockScreen.qml</file>
<file>LockScreen/fingerprint.png</file>
<file>LockScreen/fingerprint_highlighted.png</file>
</qresource>
<qresource prefix="/MainPages">
<file>MainPages/LibraryPage.qml</file>
<file>MainPages/CameraPage.qml</file>
<file>MainPages/MessagesPage.qml</file>
<file>MainPages/HomePage.qml</file>
<file>MainPages/saturn.jpg</file>
</qresource>
<qresource prefix="/QuickMenu">
<file>QuickMenu/QuickMenu.qml</file>
</qresource>
<qresource prefix="/misc">
<file>misc/KeyboardInput.qml</file>
</qresource>
</RCC>
Run Code Online (Sandbox Code Playgroud)
我的问题是,当我像这样导入每个前缀时
import "misc"
import "MainPages"
import "QuickMenu"
import "LockScreen"
Run Code Online (Sandbox Code Playgroud)
在我的 main.qml 中,我收到一条错误消息,指出我的一个 QML 对象不是类型。
QQmlApplicationEngine failed to load component
qrc:/main.qml:67 LockScreen is not a type
Run Code Online (Sandbox Code Playgroud)
奇怪的是,我可以使用 QtCreator 的智能感知访问我的所有对象,在我构建并运行应用程序之前,一切似乎都可以正常导入。有没有办法让 qrc 路径过时?还是旧的缓存文件?
该问题是由似乎在路径中添加级别的前缀引起的,因此在您的情况下,导入应该是:
import "./LockScreen/LockScreen"
Run Code Online (Sandbox Code Playgroud)
尽管编辑器失去了自动完成功能并抛出警告。因此,问题似乎在于编辑器在解释 qresource 别名时遇到问题。
更好的选择是使用 .qml 文件的别名:
...
<qresource prefix="/LockScreen">
<file alias="LockScreen.qml">LockScreen/LockScreen.qml</file>
...
Run Code Online (Sandbox Code Playgroud)
主.qml
import "LockScreen"
LockScreen{
// ...
}
Run Code Online (Sandbox Code Playgroud)
注意:别名必须具有 .qml 扩展名,否则 Qt Creator 将无法正确识别它