即使直接从官方示例中复制,也找不到未知类型名称QML_ELEMENT和 QML 模块

Unknown type name QML_ELEMENT and QML module can't be found even though copied straight from a official example

本文关键字:QML 类型 未知 找不到 ELEMENT 模块 官方 复制      更新时间:2023-10-16

当我想运行这个集成 QML 的示例时,C++我收到一个错误(在 backend.h 中(,QML_ELEMENT不是定义的类型。我知道这里已经提出了类似的问题,但是由于我从官方示例中复制粘贴,因此我确实#include <qqml.h>.这意味着我的错误原因必须是不同的。
此外,导入io.qt.examples.backend 1.0还会给我一个错误,找不到这个 QML 模块。我使用 Qt 5.9 和 Qt Quick Application。

我的后端.cpp,backend.h和main.qml的内容是从示例中复制粘贴的,所以我不会重新发布它们。我的项目文件只是默认文件,其中包含示例中的添加内容:

QT += quick
CONFIG += c++11 qmltypes
# The following define makes your compiler emit warnings if you use
# any Qt feature that has been marked deprecated (the exact warnings
# depend on your compiler). Refer to the documentation for the
# deprecated API to know how to port your code away from it.
DEFINES += QT_DEPRECATED_WARNINGS
# You can also make your code fail to compile if it uses deprecated APIs.
# In order to do so, uncomment the following line.
# You can also select to disable deprecated APIs only up to a certain version of Qt.
#DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0
SOURCES += 
backend.cpp 
main.cpp
RESOURCES += qml.qrc
QML_IMPORT_NAME = io.qt.examples.backend
QML_IMPORT_MAJOR_VERSION = 1
# Additional import path used to resolve QML modules in Qt Creator's code model
QML_IMPORT_PATH =
# Additional import path used to resolve QML modules just for Qt Quick Designer
QML_DESIGNER_IMPORT_PATH =
# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target
HEADERS += 
backend.h
QML_ELEMENT

可从Qt>= 5.15获得,因为您使用的是Qt 5.9,因此您必须使用qmlRegisterType<BackEnd>("io.qt.examples.backend", 1, 0, "BackEnd");作为Qt 5.9文档的要点

我遇到了您在Qt 5.15中描述的相同问题。以下为我解决了问题:在磁盘上的项目目录中,找到Qt自动生成的.qmltypes文件,并将该文件添加到调试文件夹(也由Qt自动创建(。这将使Qt Creator中的红色错误消息消失。在这篇博文中,提到

QML C++类型的这种静态注册不仅会生成 QML类型文件用于插件,也用于您的主应用程序。这 后一个文件称为"app.qmltypes",应放在 您的应用程序二进制文件,与"plugins.qmltypes"相同的方式应该是 放置在他们引用的插件旁边。

因此,这只是确保 .qmltypes 文件位于正确位置(在应用程序二进制文件旁边(的问题。