QML modules have become more powerful and easier to use in Qt 6. The following sections describe how to modernize QML modules that already use qt_add_qml_module .
另请参阅 Port QML modules to CMake on how to port a QML module to the qt_add_qml_module CMake API.
qt_standard_project_setup
sets up
Qt CMake 策略
needed for modern QML modules, among other things. To modernize your QML module and follow best practices, call
qt_standard_project_setup
in the project's top-level
CMakeLists.txt
file before any
qt_add_qml_module
call:
qt_standard_project_setup(REQUIRES 6.8)
The standard resource path for QML modules moved from
:/
to
:/qt/qml
with
QTP0001
. Don't use custom resource prefixes nor extend import paths in the engine. Remove all
RESOURCE_PREFIX
arguments from all
qt_add_qml_module
calls, as well as all calls to
QQmlEngine::addImportPath
or similar. Change all qrc paths in your C++ and QML code to use the new resource path prefix:
// C++ usages like:
QUrl someUrl("qrc:/MyQmlModule/MyResource1.png");
// need to be changed to
QUrl someUrl("qrc:/qt/qml/MyQmlModule/MyResource1.png");
// QML usages like:
":/MyQmlModule/MyResource1.png"
// need to be changed to
":/qt/qml/MyQmlModule/MyResource1.png"
另请参阅 Using the Qt Resource System with QML .
With the default import path, you can use the
loadFromModule
methods, like
QQmlApplicationEngine::loadFromModule
,
QQuickView::loadFromModule
,或
QQmlComponent::loadFromModule
,例如。
使用
loadFromModule
to load your QML file, for example:
engine.load(QUrl(QStringLiteral("qrc:/MyQmlModule/Main.qml")));
// becomes
engine.loadFromModule("MyQmlModule", "Main");
Avoid setting an
IMPORT_PATH
在
qt_add_qml_module
. Instead, use
DEPENDENCIES TARGET
to declare dependencies to other QML modules that can't be found in the current import path.
使用
DEPENDENCIES TARGET
also eliminates the need for the
QT_QML_OUTPUT_DIRECTORY
CMake variable and the
OUTPUT_DIRECTORY
自变量对于
qt_add_qml_module
, so remove their definitions and usages.
例如:
### in the CMakeLists.txt file defining the dependent QML module:
# don't set QT_QML_OUTPUT_DIRECTORY and remove lines like these:
set(QT_QML_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/qml)
qt_add_qml_module(MyThirdPartyQmlLibraryDependency
URI MyThirdPartyQmlLibraryDependency
....
# custom output paths are obsolete due to DEPENDENCIES TARGET below, so remove:
OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/qml
}
### in the CMakeLists.txt file defining the QML module that uses the dependency:
qt_add_qml_module(MyQmlLibrary
URI MyQmlModule
...
# replace import paths like these:
IMPORT_PATH ${CMAKE_CURRENT_BINARY_DIR}/thirdparty/qml
# with:
DEPENDENCIES TARGET MyThirdPartyQmlLibraryDependency
}
注意:
You might need to call
add_subdirectory()
before calling
qt_add_qml_module
in your CMakeLists.txt for
DEPENDENCIES TARGET
to find the target.
For more information on how to declare module dependencies, see Declaring module dependencies .
另请参阅 Changes to Qt QML and Port QML modules to CMake .