Show other data in QTableView with QItemDelegate

Berschi picture Berschi · Jan 6, 2010 · Viewed 8.3k times · Source

I have a QTableView connected with an QSqlTableModel.
In the first column, there are only dates at this format: 2010-01-02
I want this column to show the date at this format (but without changing the real data): 02.01.2010
I know that I have to create an QItemDelegate for this column, but I don't know how I can read the existing data and overwrite it with something different. You have any idea how to manage that?

Answer

Noah picture Noah · Feb 16, 2010

The simplest solution is to create a QStyledItemDelegate subclass and reimplement displayText(...) ie

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 view -

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