How to map QDataWidgetMapper and QDateEdit or QDateTimeEdit?
From QT Wikipedia
Recently needed sutch thing, because QDataWidhetMapper does not support it. So had to figure it out how to map it.
Contents |
[edit] Possible solutions
Actualy there are couple solutions:
- 1. Subclass QSqlRelationalDelegate and make appropriate changes in setEditorData and setModelData methods.
- 2. Extend QDateEdit and make it handle timestamp data and convert to QDate object.
I have chosen second solution. Because it does not make any in fluent to all items in rows and should be faster. So header declaration of my QDateEdit field with timestamp support.
[edit] Header file
timestampdateedit.h
#ifndef TIMESTAMPDATEEDIT_H #define TIMESTAMPDATEEDIT_H #include <QDateEdit> class TimeStampDateEdit : public QDateEdit { Q_OBJECT Q_PROPERTY(int date READ date WRITE setDate NOTIFY dateChanged USER true) public: TimeStampDateEdit(QWidget *parent = 0); TimeStampDateEdit( const QDate & date, QWidget * parent = 0 ); void setDate(const int &time); int date(); }; #endif
[edit] Explanation
If you wonder what for is row
Q_PROPERTY(int date READ date WRITE setDate NOTIFY dateChanged USER true)
Like i found out looking at some core of Qt library Q_PROPERTY This line i declare that object attribute can be changed using this attributes. And appropriate methods are called then working with model and other things. Generaly you should pay attention to trolltech writteln line:
- The USER attribute indicates whether the property is designated as the user-facing or user-editable property for the class. Normally, there is only one USER property per class (default false). e.g., QAbstractButton::checked is the user editable property for (checkable) buttons. Note that QItemDelegate gets and sets a widget's USER property.
And this exaplins all, because QSqlRelationalDelegate calls method
QItemDelegate::setModelData(editor, model, index);
So finnally our function get's called "setDate" and "date".
[edit] CPP Code
timestampdateedit.cpp
#include "timestampdateedit.h" TimeStampDateEdit::TimeStampDateEdit(QWidget *parent) : QDateEdit(parent) { } TimeStampDateEdit::TimeStampDateEdit( const QDate & date, QWidget * parent) : QDateEdit(date,parent) { }; int TimeStampDateEdit::date() { QDateTime dtime = QDateTime(QDateEdit::date()); return dtime.toTime_t(); } void TimeStampDateEdit::setDate(const int &time) { QDateTime dtime = QDateTime(); dtime.setTime_t(time); QDateEdit::setDate(dtime.date()); }
[edit] Conclusions
Such method of implementing support for mapper is kinda good i ques. Because such way i can make support for any date type and make conversion in subclasses. For example it now supports timestamp stored date. And you can make it handle other specific database format and so on...
