QML documents are loaded and executed by the QML runtime. This includes the Declarative UI engine along with the built-in QML elements and plugin modules, and it also provides access to third-party QML elements and modules.
Applications that use QML need to invoke the QML runtime in order to execute QML documents. This can be done by creating a
QDeclarativeView
或
QDeclarativeEngine
, as described below. In addition, the Declarative UI package includes the
Qt QML Viewer
tool, which loads
.qml
files. This tool is useful for developing and testing QML code without the need to write a C++ application to load the QML runtime.
To deploy an application that uses QML, the QML runtime must be invoked by the application. This is done by writing a Qt C++ application that loads the QDeclarativeEngine by either:
QDeclarativeView
是
QWidget
-based class that is able to load QML files. For example, if there is a QML file,
application.qml
,像这样:
import QtQuick 1.0 Rectangle { width: 100; height: 100; color: "red" }
It can be loaded in a Qt application's
main.cpp
文件像这样:
#include <QApplication> #include <QDeclarativeView> int main(int argc, char *argv[]) { QApplication app(argc, argv); QDeclarativeView view; view.setSource(QUrl::fromLocalFile("application.qml")); view.show(); return app.exec(); }
This creates a
QWidget
-based view that displays the contents of
application.qml
.
The application's
.pro
project file
must specify the
declarative
module for the
QT
variable. For example:
TEMPLATE += app QT += gui declarative SOURCES += main.cpp
若
application.qml
does not have any graphical components, or if it is preferred to avoid
QDeclarativeView
for other reasons, the
QDeclarativeEngine
can be constructed directly instead. In this case,
application.qml
is loaded as a
QDeclarativeComponent
instance rather than placed into a view:
#include <QApplication> #include <QDeclarativeEngine> #include <QDeclarativeContext> #include <QDeclarativeComponent> int main(int argc, char *argv[]) { QApplication app(argc, argv); QDeclarativeEngine engine; QDeclarativeContext *objectContext = new QDeclarativeContext(engine.rootContext()); QDeclarativeComponent component(&engine, "application.qml"); QObject *object = component.create(objectContext); // ... delete object and objectContext when necessary return app.exec(); }
见 在 C++ 应用程序中使用 QML 绑定 for more information about using QDeclarativeEngine , QDeclarativeContext and QDeclarativeComponent , as well as details on including QML files through Qt's Resource system .
The Declarative UI package includes a QML runtime tool, the Qt QML Viewer , which loads and displays QML documents. This is useful during the application development phase for prototyping QML-based applications without writing your own C++ applications to invoke the QML runtime.
见 QML 查看器 文档编制了解更多细节。