SQLite 使用动态类型系统,即它没有数据类型。您应该实现自定义委托并手动设置它。
QDateTimeEdit 的自定义委托:
#include <QItemDelegate>
#include <QDateTimeEdit>
class DateTimeEditDelegate: public QItemDelegate
{
Q_OBJECT
public:
DateTimeEditDelegate(QObject *parent = 0);
QWidget *createEditor( QWidget *parent,
const QStyleOptionViewItem &option,
const QModelIndex &index ) const;
void setEditorData( QWidget *editor,
const QModelIndex &index ) const;
void setModelData( QWidget *editor,
QAbstractItemModel *model,
const QModelIndex &index ) const;
void updateEditorGeometry( QWidget *editor,
const QStyleOptionViewItem &option,
const QModelIndex &index ) const;
mutable QDateTimeEdit *dataTimeEdit;
private slots:
void setData(QDateTime val);
};
DateTimeEditDelegate::DateTimeEditDelegate(QObject *parent ):QItemDelegate(parent)
{
}
QWidget *DateTimeEditDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
dataTimeEdit = new QDateTimeEdit( parent );
QObject::connect(dataTimeEdit,SIGNAL(dateTimeChanged(QDateTime)),this,SLOT(setData(QDateTime)));
return dataTimeEdit;
}
void DateTimeEditDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const
{
QVariant dateTime = index.model()->data( index, Qt::DisplayRole );
(static_cast<QDateTimeEdit*>( editor ))->setDateTime(dateTime.toDateTime());
}
void DateTimeEditDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const
{
model->setData( index, static_cast<QDateTimeEdit*>( editor )->dateTime() );
}
void DateTimeEditDelegate::updateEditorGeometry(QWidget *editor, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
editor->setGeometry( option.rect );
}
void DateTimeEditDelegate::setData(QDateTime val)
{
emit commitData(dataTimeEdit);
}
您可以将委托的实例设置为列:
ui->tableView->setItemDelegateForColumn(0, new DateTimeEditDelegate(ui->tableView));