Most databases store dates in the format
YYYY-MM-DD. When using a
QTableView to display a database table in PyQt it’s useful to be able to display this in a different format. Being from the UK I’d rather have the date displayed in the UK style –
DD/MM/YYYY. This is where
QStyledItemDelegate comes in.
I’d put off looking into this for a while because whenever I tried to look in to using
QStyledItemDelegate I saw people mentioning paint methods. I know nothing about painting in PyQt and get quite scared when I see it mentioned. I really need to get over that.
Not to worry though, because it’s not needed…
QStyledItemDelegate and have it take the variable date_format in its
class DateFormatDelegate(QStyledItemDelegate): def __init__(self, date_format): QStyledItemDelegate.__init__(self) self.date_format = date_format def displayText(self, value, locale): return value.toDate().toString(self.date_format)
This way we can customise the date format without changing the class making it a little more portable.
setItemDelegateForColumn() and pass it your column index and a new instance of your subclassed
QStyledItemDelegate with a date format:
Much easier than I expected.