PDA

View Full Version : How to format QDate in QTableWidgetWiev



omci
12th April 2012, 18:31
Hi;

I have QTableWidgetView that displays data from database. I have enabled sorting the data by columns (clicking on the header row). I have solved the problem of integers and date data with QTableWidgetItem::setData(Qt::DisplayRole, int) and QTableWidgetItem::setData(Qt::DisplayRole, QDate). That works perfectly but date is displayed in format "d MMM yyyy" while I need it in "dd'.'MM'.'yyyy" or similar format. Is it possible and how?

Regards; Luka

AlekseyOk
13th April 2012, 09:05
try to use toString("dd.MM.'yyyy") method from QDate that returns QString

omci
13th April 2012, 18:33
That sets data type for that coloumn as QString instead of QDate. I need to have data type of QDate to enable sorting by date. Example:

01.01.2012
03.05.2011
04.03.2012

should be sorted as:

03.05.2011
01.01.2012
04.03.2012

ChrisW67
14th April 2012, 05:31
Use a custom item delegate applied to the date column of the view. Something like:


class DateDelegate: public QStyledItemDelegate {
Q_OBJECT
public:
QString displayText(const QVariant &value, const QLocale &locale) const {
if (value.type() == QVariant::Date) {
return value.toDate().toString("...");
}
return QStyledItemDelegate::displayText(value, locale);
}
};

and QTableView::setItemDelegateForColumn()

omci
14th April 2012, 19:50
Thank for the tip. However I can not make it compile with error: expected primary-expression before ‘.’ token:

ui->myTable->setItemDelegateForColumn(0, DateDelegate.displayText(QVariant::Date, QLocale::Slovenian));

What I did wrong?

ChrisW67
15th April 2012, 03:50
The arguments for QTableView::setItemDelegateForColumn() are a column number and pointer to an instance of a QItemDelegate. The view later calls the functions in the delegate with the appropriate arguments at the appropriate time.


class DateDelegate: public QStyledItemDelegate {
Q_OBJECT
public:
DateDelegate(QObject * parent = 0):
QStyledItemDelegate(parent)
{ }
// ^^^ I have given the delegate class a constructor to ensure object ownership is captured.

QString displayText(const QVariant &value, const QLocale &locale) const {
if (value.type() == QVariant::Date) {
return value.toDate().toString("...");
}
return QStyledItemDelegate::displayText(value, locale);
}
};

...

DateDelegate *delegate = new DateDelegate(this);
ui->myTable->setItemDelegateForColumn(0, delegate);

omci
15th April 2012, 08:10
Works like a charm! Thank you