In my SQL table a have three columns:
id, Start, End
Here I store dates as Unix timestamps. In my result QTableView I want to see five columns:
- id
- Start (only date)
- Start (only time)
- End (only time)
- Length (End - Start)
For this I override:
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &item, int role = Qt::DisplayRole) const override;
int MyModel::columnCount(const QModelIndex &parent) const
{
Q_UNUSED(parent)
return 5;
}
QVariant MyModel::data(const QModelIndex &item, int role) const
{
if( !item.isValid() ) return {};
if( role == Qt::DisplayRole )
{
if( item.column() == 1 )
{
QDateTime dt = QDateTime::fromSecsSinceEpoch(record(item.row()).field("Start").value().toUInt());
return dt.toString(QStringLiteral("dd.MM.yyyy"));
}
if( item.column() == 2 )
{
QDateTime dt = QDateTime::fromSecsSinceEpoch(record(item.row()).field("Start").value().toUInt());
return dt.toString(QStringLiteral("hh:mm:ss"));
}
if( item.column() == 3 )
{
QDateTime dt = QDateTime::fromSecsSinceEpoch(record(item.row()).field("Start").value().toUInt());
return dt.toString(QStringLiteral("hh:mm:ss"));
}
if( item.column() == 4 )
{
QDateTime dtbegin = QDateTime::fromSecsSinceEpoch(record(item.row()).field("Start").value().toUInt());
QDateTime dtend = QDateTime::fromSecsSinceEpoch(record(item.row()).field("End").value().toUInt());
return secondsToTimeString(dtbegin.secsTo(dtend), true);
}
}
return QSqlTableModel::data(item, role);
}
//-----------------------------------------------------------------------------
It is works fine. But when I click on table header to sort by Time begin and length, nothing happens. I see that is virtual columns. How to make sorting by virtual column?
Thanks.