我们会经常做一些表格显示信息,其中经常有日期时间信息。
当使用Qt的Model/View时,如果你用view自带的delegate,显示的时间可能不能符合要求。
这就需要我们编写新的delegate类。以下是一个专门用于显示日期时间的delegate类“TimeEditDelegate”,取自Qt Wiki,我做了改动。
.h文件
1. #ifndef TIMEEDITDELEGATE_H
2. #define TIMEEDITDELEGATE_H
3. #include
4. class TimeEditDelegate : public QItemDelegate
5. {
6. Q_OBJECT
7. public:
8. const QString timeFormat = "dd.MM.yyyy hh:mm:ss",QObject *parent = 0) : QItemDelegate(parent)
9. this->timeformat = timeFormat;};
10. void paint(QPainter *painter, const QStyleOptionViewItem &option,
11. const QModelIndex &index) const;
12. private:
13. QString timeformat;
14. };
15. #endif // TIMEEDITDELEGATE_H
.cpp文件
1. #include "timeeditdelegate.h"
2. #include
3. #include
4. #include
5. #include
6. #include
7. void TimeEditDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option,
8. const QModelIndex &index) const
9. {
10. QDateTime dtval = index.model()->data(index, Qt::DisplayRole).toDateTime();
11. "Date not set");
12. if(dtval.isValid())
13. {
14. indexvalue = dtval.toString(timeformat);
15. }
16. Q_ASSERT(index.isValid());
17. QStyleOptionViewItemV3 opt = setOptions(index, option);
18. const QStyleOptionViewItemV2 *v2 = qstyleoption_cast(&option);
19. opt.features = v2 ? v2->features
20. : QStyleOptionViewItemV2::ViewItemFeatures(QStyleOptionViewItemV2::None);
21. const QStyleOptionViewItemV3 *v3 = qstyleoption_cast(&option);
22. opt.locale = v3 ? v3->locale : QLocale();
23. opt.widget = v3 ? v3->widget : 0;
24. // prepare
25. painter->save();
26. painter->setClipRect(opt.rect);
27. // get the data and the rectangles
28. QVariant value;
29. QPixmap pixmap;
30. QRect decorationRect;
31. value = index.data(Qt::DecorationRole);
32. QString text;
33. QRect displayRect;
34. value = index.data(Qt::DisplayRole);
35. if (value.isValid()) {
36. text = indexvalue;
37. displayRect = textRectangle(painter, option.rect, opt.font, text);
38. }
39. QRect checkRect;
40. Qt::CheckState checkState = Qt::Unchecked;
41. value = index.data(Qt::CheckStateRole);
42. if (value.isValid()) {
43. static_cast<:checkstate>(value.toInt());
44. checkRect = check(opt, opt.rect, value);
45. }
46. // do the layout
47. false);
48. // draw the item
49. drawBackground(painter, opt, index);
50. drawCheck(painter, opt, checkRect, checkState);
51. drawDecoration(painter, opt, decorationRect, pixmap);
52. drawDisplay(painter, opt, displayRect, text);
53. drawFocus(painter, opt, displayRect);
54. // done
55. painter->restore();
56. }
使用方法
1. 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
服务器托管,北京服务器托管,服务器租用 http://www.fwqtg.net
机房租用,北京机房租用,IDC机房托管, http://www.e1idc.net