[solved]QSqlTableModel converting time to unixtime and QDateTime
-
Hi,
time is stored in the databse as unixtime, and it should be displayed as QDateTime with a format of dd/MM/yyyy. So the following function is used@QVariant MyModel::data(const QModelIndex &index, int role) const
{
QVariant value = QSqlRelationalTableModel::data(index, role);
if (value.isValid() && role == Qt::DisplayRole)
{
if(index.column() == 1)
{
return QDateTime::fromTime_t(value.toInt());
}
}
return value;
}@it converts to QDateTime format, but when edited in the table how to convert it back to unixtime?
The following delgate is used
@WDelegate::WDelegate(QObject *parent)
: QItemDelegate(parent)
{
}QWidget *MyDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
if(index.column() == 1)
{
QDateTimeEdit *editor = new QDateTimeEdit(parent);
editor->setDisplayFormat("dd/MM/yyyy");
editor->setCalendarPopup(true);
return editor;
}
}void MyDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QLineEdit edit = qobject_cast<QLineEdit>(editor);
if (edit)
{
edit->setText(index.model()->data(index, Qt::EditRole).toString());
}
else
{
QDateTimeEdit *dateEditor = qobject_cast<QDateTimeEdit *>(editor);
if (dateEditor)
{
dateEditor->setDate(QDate::fromString(
index.model()->data(index, Qt::EditRole).toString(),
"dd/MM/yyyy"));
}//if (dateEditor)
}
}void MyDelegate::setModelData(QWidget *editor, QAbstractItemModel *model,
const QModelIndex &index) const
{
QLineEdit *edit = qobject_cast<QLineEdit *>(editor);
if (edit)
{
model->setData(index, edit->text());
}
else
{
QDateTimeEdit *dateEditor = qobject_cast<QDateTimeEdit *>(editor);
if (dateEditor)
{
model->setData(index, dateEditor->date().toString("dd/MM/yyyy"));
}
}
}@ -
After you've got a new QDateTime, then you can use toTime_t() to get it back to unix time.