0

I'm using Qt 5.1.0 and QtQuick 2.0. I've just learned how to exchange data and method between qml and C++. In detail, I want to expose a (nested) structure, so I created classes which contains the required properties and methods.

It works, but I cannot share the very same instance between C++ and qml. Changing something from C++ side leads to no changes in qml side.

A short example:

main.cpp

#include <QtGui/QGuiApplication>
#include <QtQml>
#include "qtquick2applicationviewer.h"
#include "myclass.h"

int main(int argc, char *argv[]) {
    QGuiApplication app(argc, argv);
    qmlRegisterType<MyClass>("MyLibrary", 1, 0, "MyClass");

    MyClass *myclass = new MyClass();
    Category *cat = new Category();
    cat->setName("foo");
    myclass->append(cat);
    qDebug() << myclass->categoriesCount(); // returns 1 OK!

    QtQuick2ApplicationViewer viewer;
    viewer.setMainQmlFile(QStringLiteral("qml/main.qml"));
    viewer.show();

    return app.exec();
}

myclass.h

#include <QObject>

class Category : public QObject {
    Q_OBJECT
    Q_PROPERTY(QString name READ name WRITE setName)

public:
    Category() {}
    QString name() const { return m_name; }
    void setName(QString name) { m_name = name; }

private:
    QString m_name;
};

class MyClass : public QObject {
    Q_OBJECT
    Q_PROPERTY(QList<QObject*> categories READ categories NOTIFY categoriesChanged)
    Q_PROPERTY(int categoriesCount READ categoriesCount)

public:
    QList<QObject*> categories() const { return m_categories; }
    void clear() { m_categories.clear(); }
    void append(Category *category) { m_categories.append(category); }
    int categoriesCount() const { return m_categories.count(); }

private:
    QList<QObject*> m_categories;

signals:
    void categoriesChanged();
};

main.qml

import QtQuick 2.0
import MyLibrary 1.0

Item {
    id: root
    width: 360
    height: 360

    Text {
        id: foo
        text: myclass.categoriesCount // writes 0 -> should be 1
    }

    MyClass {
        id: myclass
    }    
}

I'm afraid the qml engine accesses to a different instance of the class myclass created in the main file.

4

0 回答 0