How to access qml object from one C++ extensionplugin



  • I just try the following code in my extensionplugin:
    @class QExampleQmlPlugin : public QQmlExtensionPlugin
    {
    Q_OBJECT
    Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QQmlExtensionInterface")

    public:

    void registerTypes(const char *uri) {
    qmlRegisterType<ClickHandler>(uri, 1, 0, "MyClick");
    QString str = objectName();
    QObject * p = parent();
    // QString str2 = p->objectName();
    int i = 0;
    }

    void initializeEngine(QQmlEngine * engine, const char * uri) {
    QQmlApplicationEngine* app_engine = qobject_cast<QQmlApplicationEngine*>(engine);
    QList<QObject *> roots = app_engine->rootObjects();
    int i = 0;
    }
    };
    @

    but the roots is empty:
    @(gdb) p roots
    $1 = {{p = {static shared_null = {ref = {atomic = {_q_value = -1}}, alloc = 0, begin = 0, end = 0, array = {0x0}}, d = 0x7ffff6355da0 QListData::shared_null}, d = 0x7ffff6355da0 QListData::shared_null}}
    (gdb) [Thread 0x7fffe2304700 (LWP 19788) exited]@

    In my main app project, in main.cpp file, I use QQmlApplicationEngine to load main.qml file, in main.qml file, I load my plugin. Code snippet from main.cpp
    @ QQmlApplicationEngine engine;
    engine.addImportPath(imports_dir_path);
    engine.load(QUrl("qrc:/qmls/main.qml"));

    QObject * topLevel = engine.rootObjects().value(0);
    QQuickWindow * window = qobject_cast<QQuickWindow*>(topLevel);
    if (!window) {
      qWarning("Error: Your root item has to be a Window.");
      return -1;
    }
    window->showMaximized();
    return app->exec&#40;&#41;;@
    

    code from main.qml
    @import demo 1.0 // import types from the plugin
    import QtQuick.Window 2.1
    import QtQuick.Controls 1.1
    import QtQuick.XmlListModel 2.0
    import QtQuick 2.2

    // this class is defined in QML (imports/demo/hello.qml)
    Window {
    Hello {
    // this class is defined in C++ (plugin.cpp)
    MyClick {
    id: click
    }

        Text {
            text: click.value
        }
    }
    

    }@



  • How and where are you calling initializeEngine ?



  • My class is a sub-class of QQmlExtensionPlugin
    initializeEngine is a virtual method inherited from QQmlExtensionPlugin class.
    After testing this, I find this method will be called by Qt while my extensionplugin is loaded by qml.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.