Chapter 6: Writing an Extension Plugin
Currently the PieChart and PieSlice types are used by app.qml, which is displayed using a QQuickView in a C++ application. An alternative way to use our QML extension is to create a plugin library to make it available to the QML engine. This would allow the PieChart and PieSlice types to be registered into a type namespace which could be imported by any QML application, instead of restricting these types to be only used by the one application.
The setps for creating a plugin are described in Creating C++ Plugins for QML. To start with, we create a plugin class named ChartsPlugin. It subclasses QQmlExtensionPlugin and registers our QML types in the inherited registerTypes() method.
Here is the ChartsPlugin definition in chartsplugin.h:
#include <QQmlExtensionPlugin> class ChartsPlugin : public QQmlExtensionPlugin { Q_OBJECT Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface") public: void registerTypes(const char *uri); };
And its implementation in chartsplugin.cpp:
#include "piechart.h" #include "pieslice.h" #include <qqml.h> void ChartsPlugin::registerTypes(const char *uri) { qmlRegisterType<PieChart>(uri, 1, 0, "PieChart"); qmlRegisterType<PieSlice>(uri, 1, 0, "PieSlice"); }
Then, we write a .pro project file that defines the project as a plugin library and specifies with DESTDIR that library files should be built into a "lib" subdirectory:
TEMPLATE = lib CONFIG += plugin QT += qml quick DESTDIR = Charts TARGET = chartsplugin OBJECTS_DIR = tmp MOC_DIR = tmp HEADERS += piechart.h \ pieslice.h \ chartsplugin.h SOURCES += piechart.cpp \ pieslice.cpp \ chartsplugin.cpp
Finally, we add a qmldir file that is parsed by the QML engine. In this file, we specify that a plugin named "chapter6-plugin" (the name of the example project) can be found in the "lib" subdirectory:
module Charts plugin chartsplugin
Now we have a plugin, and instead of having a main.cpp and an executable, we can build the project and then load the QML file using the qmlscene tool, setting the import path to the current directory so that it finds the qmldir file:
qmlscene -I . app.qml
The module "Charts" will be loaded by the QML engine, and the types provided by that module will be available for use in any QML document which imports it.
Files:
- tutorials/extending/chapter6-plugins/app.qml
- tutorials/extending/chapter6-plugins/chartsplugin.cpp
- tutorials/extending/chapter6-plugins/chartsplugin.h
- tutorials/extending/chapter6-plugins/piechart.cpp
- tutorials/extending/chapter6-plugins/piechart.h
- tutorials/extending/chapter6-plugins/pieslice.cpp
- tutorials/extending/chapter6-plugins/pieslice.h
- tutorials/extending/chapter6-plugins/chapter6-plugins.pro
- tutorials/extending/chapter6-plugins/Charts/qmldir