Skip to content

Instantly share code, notes, and snippets.

@timsueberkrueb
Created August 16, 2017 10:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timsueberkrueb/59909355699ba72c45a673439c14a8ef to your computer and use it in GitHub Desktop.
Save timsueberkrueb/59909355699ba72c45a673439c14a8ef to your computer and use it in GitHub Desktop.
Simple C++-QObject with QML children (using the "data" property only)
#include "childrencontainer.h"
ChildrenContainer::ChildrenContainer(QObject *parent) : QObject(parent)
{
}
QQmlListProperty<QObject> ChildrenContainer::data()
{
return QQmlListProperty<QObject>(
this, this,
&ChildrenContainer::dataAppend,
&ChildrenContainer::dataCount,
&ChildrenContainer::dataAt,
&ChildrenContainer::dataClear
);
}
void ChildrenContainer::dataAppend(QObject *object)
{
_children.append(object);
}
int ChildrenContainer::dataCount() const
{
return _children.count();
}
QObject *ChildrenContainer::dataAt(int idx) const
{
return _children.at(idx);
}
void ChildrenContainer::dataClear()
{
_children.clear();
}
void ChildrenContainer::dataAppend(QQmlListProperty<QObject> *list, QObject *object)
{
reinterpret_cast<ChildrenContainer*>(list->data)->dataAppend(object);
}
int ChildrenContainer::dataCount(QQmlListProperty<QObject> *list)
{
return reinterpret_cast<ChildrenContainer*>(list->data)->dataCount();
}
QObject *ChildrenContainer::dataAt(QQmlListProperty<QObject> *list, int idx)
{
return reinterpret_cast<ChildrenContainer*>(list->data)->dataAt(idx);
}
void ChildrenContainer::dataClear(QQmlListProperty<QObject> *list)
{
reinterpret_cast<ChildrenContainer*>(list->data)->dataClear();
}
#ifndef CHILDRENCONTAINER_H
#define CHILDRENCONTAINER_H
#include <QObject>
#include <QQmlListProperty>
class ChildrenContainer : public QObject
{
Q_OBJECT
Q_PROPERTY(QQmlListProperty<QObject> data READ data)
Q_CLASSINFO("DefaultProperty", "data")
public:
explicit ChildrenContainer(QObject *parent = nullptr);
QQmlListProperty<QObject> data();
void dataAppend(QObject* object);
int dataCount() const;
QObject* dataAt(int idx) const;
void dataClear();
private: // members
QList<QObject*> _children;
private: // methods
static void dataAppend(QQmlListProperty<QObject>* list, QObject* object);
static int dataCount(QQmlListProperty<QObject>* list);
static QObject* dataAt(QQmlListProperty<QObject>* list, int idx);
static void dataClear(QQmlListProperty<QObject>* list);
};
#endif // CHILDRENCONTAINER_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment