Using a QML model from a QDeclarativeItem subclass



  • Hi! I'm creating a QDeclarativeItem subclass:

    @class MyGraphic : public QDeclarativeItem
    {
    Q_OBJECT
    Q_PROPERTY(????? model READ model SET model)

    public:
    MyGraphic(QDeclarativeItem *parent = 0);
    void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
    ...
    };@

    I would like to use it in QML like this:

    @Rectangle {
    ListModel {
    id: mymodel
    ListElement { type: "Oranges"; amount: 35 }
    ListElement { type: "Apples"; amount: 27 }
    ListElement { type: "Peaches"; amount: 12 }
    }

    MyGraphic {
        width: 300; height: 200
        model: mymodel
    }
    

    }@

    There are plenty of examples on how to make a C++ model available in the QML world but I have found nothing on how to access a QML model from C++.

    How can I access mymodel from MyGraphic (the C++ class)? Should I use QAbstractItemModel* directly in the Q_PROPERTY?

    I mean something like:

    @void MyGraphic::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
    {
    QString type = model->data(...); // model would be "mymodel" from QML
    int amount = model->data(...);
    // paint a graphic using the "type" and "amount" variables
    }@



  • Sounds like the same question as "this":http://developer.qt.nokia.com/forums/viewthread/2926/.

    Short answer: AFAIK, this is not yet possible*, as the QML model API is private API.

    *) in a supported way.



  • Thanks! Seems like I will have to use a QAbstractItemModel and set it in C++. Doesn't look so pretty either but that's life.



  • This is something that would be very useful.
    The workaround would be too complicated.
    For now, do it (i mean the model) in the C++ and then it is much easier to manipulate both in QML and C++.



  • I have did the same as in this example, I replaced the qlist with standard model but in vain

    @#include <QAbstractListModel>
    #include <QStringList>

    //![0]
    class Animal
    {
    public:
    Animal(const QString &type, const QString &size);
    //![0]

    QString type() const;
    QString size() const;
    

    private:
    QString m_type;
    QString m_size;
    //![1]
    };

    class AnimalModel : public QAbstractListModel
    {
    Q_OBJECT
    public:
    enum AnimalRoles {
    TypeRole = Qt::UserRole + 1,
    SizeRole
    };

    AnimalModel(QObject *parent = 0);
    

    //![1]

    void addAnimal(const Animal &animal);
    
    int rowCount(const QModelIndex & parent = QModelIndex()) const;
    
    QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const;
    

    private:
    QList<Animal> m_animals;
    //![2]
    };@


Log in to reply
 

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