1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140
|
#include "datawidgetmapper.h"
#include <QAbstractItemModel>
#include <QWidget>
#include <QDebug>
DataWidgetMapper::DataWidgetMapper(QObject *parent) :
QObject(parent)
{
}
QAbstractItemModel* DataWidgetMapper::getModel() const
{
return model;
}
void DataWidgetMapper::setModel(QAbstractItemModel* value)
{
model = value;
}
void DataWidgetMapper::addMapping(QWidget* widget, int modelColumn, const QString& propertyName)
{
MappingEntry* entry = new MappingEntry;
entry->columnIndex = modelColumn;
entry->widget = widget;
entry->propertyName = propertyName;
mappings[widget] = entry;
}
void DataWidgetMapper::clearMapping()
{
for (MappingEntry* entry : mappings.values())
delete entry;
mappings.clear();
}
int DataWidgetMapper::getCurrentIndex() const
{
return currentIndex;
}
int DataWidgetMapper::mappedSection(QWidget* widget) const
{
if (mappings.contains(widget))
return mappings[widget]->columnIndex;
return -1;
}
void DataWidgetMapper::loadFromModel()
{
QModelIndex idx;
QVariant data;
for (MappingEntry* entry : mappings.values())
{
idx = model->index(currentIndex, entry->columnIndex);
data = model->data(idx, Qt::EditRole);
entry->widget->setProperty(entry->propertyName.toLatin1().constData(), data);
}
}
DataWidgetMapper::SubmitFilter DataWidgetMapper::getSubmitFilter() const
{
return submitFilter;
}
void DataWidgetMapper::setSubmitFilter(const SubmitFilter& value)
{
submitFilter = value;
}
void DataWidgetMapper::setCurrentIndex(int rowIndex)
{
if (!model)
return;
if (rowIndex < 0)
return;
if (rowIndex >= model->rowCount())
return;
if (model->rowCount() == 0)
return;
currentIndex = rowIndex;
loadFromModel();
emit currentIndexChanged(rowIndex);
}
void DataWidgetMapper::toFirst()
{
setCurrentIndex(0);
}
void DataWidgetMapper::toLast()
{
if (!model)
return;
setCurrentIndex(model->rowCount() - 1);
}
void DataWidgetMapper::toNext()
{
setCurrentIndex(currentIndex + 1);
}
void DataWidgetMapper::toPrevious()
{
setCurrentIndex(currentIndex - 1);
}
void DataWidgetMapper::submit()
{
QModelIndex idx;
QVariant value;
for (MappingEntry* entry : mappings.values())
{
if (submitFilter && !submitFilter(entry->widget))
continue;
idx = model->index(currentIndex, entry->columnIndex);
value = entry->widget->property(entry->propertyName.toLatin1().constData());
//qDebug() << "copying from form view for idx" << idx << "value:" << value;
model->setData(idx, value, Qt::EditRole);
}
}
void DataWidgetMapper::revert()
{
if (!model)
return;
if (currentIndex < 0)
return;
loadFromModel();
}
|