开发者

Show other data in QTableView with QItemDelegate

开发者 https://www.devze.com 2022-12-15 11:16 出处:网络
I have a QTableView connected with an QSqlTableModel. In the first column, there are only dates at this format: 2010-01-02

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 exi开发者_如何学运维sting data and overwrite it with something different. You have any idea how to manage that?


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));


An item delegate doesn't necessarily change the data, it just renders the data. Also, if you're using Qt 4.4 or newer, look at QStyledItemDelegate instead--it's theme-aware and will look nicer.

There's an example of item delegates in this article (which seems to be a mirror of official documentation that is now down or gone).

Since all you really want to do is customize the text, have you considered using a proxy model instead and just returning your custom QString for the date column's DisplayRole?

0

精彩评论

暂无评论...
验证码 换一张
取 消