我们会经常做一些表格显示信息,其中经常有日期时间信息。
当使用Qt的Model/View时,如果你用view自带的delegate,显示的时间可能不能符合要求。
这就需要我们编写新的delegate类。以下是一个专门用于显示日期时间的delegate类“TimeEditDelegate”,取自Qt Wiki,我做了改动。
.h文件
#ifndef TIMEEDITDELEGATE_H #define TIMEEDITDELEGATE_H #include <QItemDelegate> class TimeEditDelegate : public QItemDelegate { Q_OBJECT public: TimeEditDelegate(const QString timeFormat = "dd.MM.yyyy hh:mm:ss",QObject *parent = 0) : QItemDelegate(parent) {this->timeformat = timeFormat;}; void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const; private: QString timeformat; }; #endif // TIMEEDITDELEGATE_H
.cpp文件
#include "timeeditdelegate.h" #include <QModelIndex> #include <QPainter> #include <QDateTime> #include <QStyleOptionViewItemV3> #include <QStyleOptionViewItemV2> void TimeEditDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QDateTime dtval = index.model()->data(index, Qt::DisplayRole).toDateTime(); QString indexvalue = tr("Date not set"); if(dtval.isValid()) { indexvalue = dtval.toString(timeformat); } Q_ASSERT(index.isValid()); QStyleOptionViewItemV3 opt = setOptions(index, option); const QStyleOptionViewItemV2 *v2 = qstyleoption_cast<const QStyleOptionViewItemV2 *>(&option); opt.features = v2 ? v2->features : QStyleOptionViewItemV2::ViewItemFeatures(QStyleOptionViewItemV2::None); const QStyleOptionViewItemV3 *v3 = qstyleoption_cast<const QStyleOptionViewItemV3 *>(&option); opt.locale = v3 ? v3->locale : QLocale(); opt.widget = v3 ? v3->widget : 0; // prepare painter->save(); painter->setClipRect(opt.rect); // get the data and the rectangles QVariant value; QPixmap pixmap; QRect decorationRect; value = index.data(Qt::DecorationRole); QString text; QRect displayRect; value = index.data(Qt::DisplayRole); if (value.isValid()) { text = indexvalue; displayRect = textRectangle(painter, option.rect, opt.font, text); } QRect checkRect; Qt::CheckState checkState = Qt::Unchecked; value = index.data(Qt::CheckStateRole); if (value.isValid()) { checkState = static_cast<Qt::CheckState>(value.toInt()); checkRect = check(opt, opt.rect, value); } // do the layout doLayout(opt, &checkRect, &decorationRect, &displayRect, false); // draw the item drawBackground(painter, opt, index); drawCheck(painter, opt, checkRect, checkState); drawDecoration(painter, opt, decorationRect, pixmap); drawDisplay(painter, opt, displayRect, text); drawFocus(painter, opt, displayRect); // done painter->restore(); }
使用方法
View->setItemDelegateForColumn(c, new TimeEditDelegate("yyyy-dd-MM"));
其中,c是需要显示日期时间的列号。"yyyy-dd-MM"是显示的格式。两个中文常用格式为:
yyyy-dd-MM 例子:2009-12-25
yyyy-dd-MM hh:mm:ss 例子:2009-12-25 12:25:32