When developing your application to Qt may happen a situation where required in an application written in QWidgets implement functional written in QML. To solve such a problem can be used QQuickWidget class that is used to render QML .
Write a simple hello world, which will draw the code written in QML widget that is placed in the window, based on QWidget . To make it look as follows:
Configuration of Pro file
To use this object class, you need to connect a Pro project file quickwidgets module. Also add a resource file, which will contain qml files, namely QmlLabel.qml file.
QT += core gui quickwidgets greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = qmlwidget TEMPLATE = app DEFINES += QT_DEPRECATED_WARNINGS SOURCES += main.cpp\ widget.cpp HEADERS += widget.h FORMS += widget.ui RESOURCES += \ qml.qrc
widget.h
In the header file of the application window to include the header file of QQuickWidget and declare an object of this class.
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QQuickWidget> namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = 0); ~Widget(); private: Ui::Widget* ui; QQuickWidget* m_quickWidget; }; #endif // WIDGET_H
widget.cpp
The project was created with the help of interface designer, so the code will only be present in addition QQuickWidget object placement Grid Layout , which is responsible for the layout of the widgets in the window.
#include "widget.h" #include "ui_widget.h" Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); m_quickWidget = new QQuickWidget(this) ; m_quickWidget->setSource(QUrl("qrc:/QmlLabel.qml")); m_quickWidget->setResizeMode(QQuickWidget::SizeRootObjectToView); ui->gridLayout->addWidget(m_quickWidget, 1, 0); } Widget::~Widget() { delete ui; }
QmlLabel.qml
Content of the Hello World on the QML
import QtQuick 2.5 import QtQuick.Controls 2.1 Item { Text { id: text text: qsTr("Hello world") anchors.centerIn: parent } }