Files
prodejna/core/autoform.h
T

102 lines
2.2 KiB
C++
Raw Normal View History

2015-11-10 20:16:30 +01:00
#ifndef AUTOFORM_H
#define AUTOFORM_H
#include <QWidget>
#include <QList>
#include <QLineEdit>
#include <QSharedPointer>
#include <QMetaMethod>
#include <QDebug>
2015-11-17 22:24:00 +01:00
#include <QVariant>
2015-11-10 20:16:30 +01:00
2015-11-17 22:24:00 +01:00
#include "iform.h"
2015-11-10 20:16:30 +01:00
#include "service.h"
2015-11-10 22:39:58 +01:00
#include "ivalidator.h"
2015-11-10 20:16:30 +01:00
2015-11-17 22:24:00 +01:00
2015-11-10 20:16:30 +01:00
template <class T>
2015-11-17 22:24:00 +01:00
class AutoForm : public IForm
2015-11-10 20:16:30 +01:00
{
public:
2015-11-17 22:24:00 +01:00
explicit AutoForm(QWidget *parent = 0) : IForm(parent) {
2015-11-10 20:16:30 +01:00
m_newRec = false;
}
2015-11-10 22:39:58 +01:00
virtual ~AutoForm() {
foreach (IValidator *val, m_validators) {
delete val;
m_validators.clear();
}
}
2015-11-10 20:16:30 +01:00
void setEntity(QSharedPointer<T> entity) {
m_entity = entity;
bindToUi();
}
2015-11-17 22:24:00 +01:00
QSharedPointer<T> entity() {
return m_entity;
}
void setNewRec(bool isNew) {
m_newRec = isNew;
}
2015-11-10 20:16:30 +01:00
void registerBinding(QWidget *widget) {
if (!m_bindWidgets.contains(widget)) {
m_bindWidgets.append(widget);
}
}
2015-11-10 22:39:58 +01:00
void registerValidator(IValidator *validator) {
m_validators.append(validator);
}
2015-11-10 20:16:30 +01:00
private:
QSharedPointer<T> m_entity;
QList<QWidget*> m_bindWidgets;
2015-11-10 22:39:58 +01:00
QList<IValidator*> m_validators;
2015-11-10 20:16:30 +01:00
bool m_newRec;
void bindToUi() {
foreach (QWidget *widget, m_bindWidgets) {
const char* prop = widget->metaObject()->userProperty().name();
widget->setProperty(prop, ((QObject*)m_entity.data())->property(widget->objectName().toStdString().c_str()));
}
}
2015-11-10 22:39:58 +01:00
bool bindToData() {
foreach (IValidator *val, m_validators) {
if (!val->validate()) {
emit validationError(val->errMessage());
return false;
}
}
2015-11-10 20:16:30 +01:00
foreach (QWidget *widget, m_bindWidgets) {
const char* prop = widget->metaObject()->userProperty().name();
((QObject*)m_entity.data())->setProperty(widget->objectName().toStdString().c_str(), widget->property(prop));
}
2015-11-10 22:39:58 +01:00
return true;
2015-11-10 20:16:30 +01:00
}
public slots:
2015-11-10 22:39:58 +01:00
bool saveRecord() {
if (!bindToData())
{
return false;
}
2015-11-10 20:16:30 +01:00
if (m_newRec) {
2015-11-17 22:24:00 +01:00
emit recordAdded();
2015-11-10 20:16:30 +01:00
} else {
2015-11-17 22:24:00 +01:00
emit recordUpdated();
2015-11-10 20:16:30 +01:00
}
2015-11-10 22:39:58 +01:00
return true;
2015-11-10 20:16:30 +01:00
}
};
#endif // AUTOFORM_H