Repeater.cpp Example File
repeater/src/Repeater.cpp
#include "Repeater.hpp"
#include <bb/cascades/DataModel>
using namespace bb::cascades;
Repeater::Repeater(Container *parent)
: CustomControl(parent)
, m_model(0)
, m_delegate(0)
{
setVisible(false);
}
Repeater::~Repeater()
{
}
QVariant Repeater::model() const
{
return m_model;
}
void Repeater::setModel(const QVariant &model)
{
if (m_model == model)
return;
m_model = model;
clear();
regenerate();
emit modelChanged();
}
QDeclarativeComponent* Repeater::delegate() const
{
return m_delegate;
}
void Repeater::setDelegate(QDeclarativeComponent *delegate)
{
if (m_delegate == delegate)
return;
m_delegate = delegate;
clear();
regenerate();
emit delegateChanged();
}
void Repeater::clear()
{
Container *container = qobject_cast<Container*>(parent());
foreach (Control *control, m_controls) {
container->remove(control);
}
qDeleteAll(m_controls);
m_controls.clear();
}
void Repeater::regenerate()
{
if (!m_delegate)
return;
Container *container = qobject_cast<Container*>(parent());
const int repeaterPosition = container->indexOf(this);
if (m_model.type() == QVariant::Int || m_model.type() == QVariant::Double) {
const int counter = m_model.toInt();
for (int i = 1; i <= counter; ++i) {
QDeclarativeContext *context = new QDeclarativeContext(m_delegate->creationContext(), this);
context->setContextProperty("index", i);
context->setContextProperty("modelData", i);
QObject *object = m_delegate->create(context);
Control *control = qobject_cast<Control*>(object);
container->insert(repeaterPosition + i, control);
m_controls.append(control);
}
} else if (m_model.type() == QVariant::List) {
const QVariantList list = m_model.toList();
for (int i = 0; i < list.count(); ++i) {
QDeclarativeContext *context = new QDeclarativeContext(m_delegate->creationContext(), this);
context->setContextProperty("index", i + 1);
context->setContextProperty("modelData", list.at(i));
QObject *object = m_delegate->create(context);
Control *control = qobject_cast<Control*>(object);
container->insert(repeaterPosition + i + 1, control);
m_controls.append(control);
}
} else {
QObject *model = m_model.value<QObject*>();
bb::cascades::DataModel *dataModel = qobject_cast<bb::cascades::DataModel*>(model);
if (dataModel) {
for (int i = 0; i < dataModel->childCount(QVariantList()); ++i) {
QDeclarativeContext *context = new QDeclarativeContext(m_delegate->creationContext(), this);
context->setContextProperty("index", i + 1);
const QVariantMap map = dataModel->data(QVariantList() << i).toMap();
foreach (const QString &key, map.keys()) {
context->setContextProperty(key, map.value(key));
}
QObject *object = m_delegate->create(context);
Control *control = qobject_cast<Control*>(object);
container->insert(repeaterPosition + i + 1, control);
m_controls.append(control);
}
}
}
}