Show other data in QTableView using QItemDelegate

I have a QTableView related to QSqlTableModel.
The first column contains only dates in this format: 2010-01-02
I want the date in this format to be displayed in this column (but without changing the real data): 02.01.2010
I know that I need to create a QItemDelegate for this column, but I do not know how I can read existing data and overwrite it with something else. Do you know how to do this?

+6
c ++ qt qt4 qtableview qitemdelegate
source share
2 answers

An element delegate does not necessarily modify the data; it simply displays the data. Also, if you are using Qt 4.4 or later, look at QStyledItemDelegate instead - this is a theme and will look better.

Here is an example of delegate elements in this article (which seems to be a mirror of the official documentation that is now missing or gone).

Since all you really want to do is customize the text, did you consider using the proxy model and just return your custom QString for the DisplayRole date column?

+4
source share

The simplest solution is to subclass QStyledItemDelegate and reimplement displayText(...) i.e.

 class DateFormatDelegate : public QStyledItemDelegate { public: DateFormatDelegate (QString dateFormat, QObject *parent = 0) : QStyledItemDelegate(parent), m_dateFormat(dateFormat) { } virtual QString displayText(const QVariant & value, const QLocale & locale ) const { Q_UNUSED(locale); return value.toDate().toString(m_dateFormat); } private: QString m_dateFormat; }; 

Then, in your opinion,

 setItemDelegateForColumn(/*date column*/, new DateFormatDelegate("MM.dd.yyyy", this)); 
+14
source share

All Articles