There are a number of ways to integrate QML into QWidget -based UI applications, depending on the characteristics of your existing UI code.
If you have an existing QWidget -based UI, QML widgets can be integrated into it using QDeclarativeView . QDeclarativeView 是子类化的 QWidget so you can add it to your user interface like any other QWidget 。使用 QDeclarativeView::setSource () to load a QML file into the view, then add the view to your UI:
QDeclarativeView *qmlView = new QDeclarativeView; qmlView->setSource(QUrl::fromLocalFile("myqml.qml")); QWidget *widget = myExistingWidget(); QVBoxLayout *layout = new QVBoxLayout(widget); layout->addWidget(qmlView);
The one drawback to this approach is that QDeclarativeView is slower to initialize and uses more memory than a QWidget , and creating large numbers of QDeclarativeView objects may lead to performance degradation. If this is the case, it may be better to rewrite your widgets in QML, and load the widgets from a main QML widget instead of using QDeclarativeView .
Keep in mind that QWidgets were designed for a different type of user interface than QML, so it is not always a good idea to port a QWidget -based application to QML. QWidgets are a better choice if your UI is comprised of a small number of complex and static elements, and QML is a better choice if your UI is comprised of a large number of simple and dynamic elements.
If you have an existing UI based on the 图形视图框架 , you can integrate QML widgets directly into your QGraphicsScene 。使用 QDeclarativeComponent to create a QGraphicsObject from a QML file, and place the graphics object into your scene using QGraphicsScene::addItem (), or reparent it to an item already in the QGraphicsScene .
例如:
QGraphicsScene* scene = myExistingGraphicsScene(); QDeclarativeEngine *engine = new QDeclarativeEngine; QDeclarativeComponent component(engine, QUrl::fromLocalFile("myqml.qml")); QGraphicsObject *object = qobject_cast<QGraphicsObject *>(component.create()); scene->addItem(object);
下列 QGraphicsView options are recommended for optimal performance of QML UIs:
An alternative approach is to expose your existing QGraphicsWidget objects to QML and construct your scene in QML instead. See the graphics layouts example which shows how to expose Qt's graphics layout classes to QML in order to use QGraphicsWidget with classes like QGraphicsLinearLayout and QGraphicsGridLayout .
To expose your existing QGraphicsWidget classes to QML, use qmlRegisterType ()。见 使用 C++ 扩展 QML 功能 for further information on how to use C++ types in QML.