Access QObject Item from a QList



  • Hi
    I got a class inherited from QObject like this:
    champion.h
    @#ifndef CHAMPION_H
    #define CHAMPION_H

    #include <QObject>

    class Champions : public QObject
    {
    Q_OBJECT
    Q_PROPERTY(QString name READ name)
    Q_PROPERTY(QString color READ color)

    public:

    Champions(QObject *parent=0);
    Champions(const QString &name, const QString &color,QObject *parent=0);
    QString name() const;
    
    QString color() const;
    

    private:
    QString c_name;
    QString cc_name;

    };
    #endif // DATAOBJECT_H@

    champion.cpp
    @#include "champion.h"
    #include <QDebug>

    Champions::Champions(QObject *parent)
    : QObject(parent)
    {
    }

    Champions::Champions(const QString &name, const QString &color, QObject parent)
    : QObject(parent), c_name(name), cc_name(color)
    {
    }
    QString Champions::name() const
    {
    return c_name;
    }
    QString Champions::color() const
    {
    return cc_name;
    }
    @
    In my main.cpp, I created a @QList<QObject
    > dataList@ to add some Champions class in. Now because I want to access c_name and cc_name so I try some code like :
    @datalist.at(2).name()@
    or
    @datalist[2].name()@
    but neither of them works. Is there any method to get these items ?



  • You need to cast the pointer to the correct type, recommended ways are: dynamic_cast or (because you have a QObject) "qobject_cast":http://qt-project.org/doc/qt-5/qobject.html#qobject_cast:
    @
    Champions* item2 = qobject_cast<Champions*>(datalist.at(2));
    if(item2)
    item2->name();
    @


  • Lifetime Qt Champion

    Since it's a QObject, the correct way is qobject_cast



  • [quote author="Zlatomir" date="1405190039"]You need to cast the pointer to the correct type, recommended ways are: dynamic_cast or (because you have a QObject) "qobject_cast":http://qt-project.org/doc/qt-5/qobject.html#qobject_cast:
    @
    Champions* item2 = qobject_cast<Champions*>(datalist.at(2));
    if(item2)
    item2->name();
    @
    [/quote]

    Thanks a lot ! It works well for me !


Log in to reply
 

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