Important: Please read the Qt Code of Conduct -

[Solved] C++ plugin for QML

  • Hi, everybody! I have an application that consists of a QML part and C++ part (a lot of classes that can be accessed from QML). The QML files are located in a qrc.
    I want to detach the C++ part and make a shared (or static) library named 'engine' to use with other projects.
    I have read some tutorials and detached the C++ files. Also I've added a file "plugin.cpp" with the following code:
    @#include <QtPlugin>
    #include <QDeclarativeExtensionPlugin>
    #include "version.h"
    #include "headers.h"

    class Plugin: public QDeclarativeExtensionPlugin
    void registerTypes(const char *uri)
    #include ""

    Q_EXPORT_PLUGIN2(engine, Plugin)@

    headers.h and are autogenerated files that do the registration. The example line of
    @qmlRegisterType<Printer>(uri, VERSION_MAJOR, VERSION_MINOR, "Printer");@

    The library compiles OK, I get the file

    Please help me with importing the plugin into the QML program! I've tried many different ways, but I didn't succeed.
    Where should I put the shared library? Should I link my executable with the library? Should I write the qmldir file and where should I put it? Should I do addImportPath()?

  • I've succeeded in importing my plugin from qmlviewer. To do that I had to add header file plugin.h with the definition of class Plugin to let the MOC process the class. Without that step the qmlviewer was unable to load the shared library.
    The directory structure is:

    @plugin engine@

    @import QtQuitck 1.1
    import engine 0.1

    Rectangle {
    color: "red"
    Printer {
    id: printer

    The command to run qmlviewer is:
    @qmlviewer -I . main.qml@

    Now I'm going to try importing the plugin from my executable.

  • To do importing the plugin from my application I had to add import path to the main view:
    @mv->engine()->addImportPath("."); // mv is an object of class derived from QDeclarativeView@

Log in to reply