0

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:

  1. id
  2. Start (only date)
  3. Start (only time)
  4. End (only time)
  5. 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.

MCoder
  • 126
  • 2
  • 6
  • Since QSqlTableModel::sort() reimplements the sorting by adding the appropriate `where`clause and your columns are not in there you have to reimplement sort() by yourself or use a QSortFilterProxyModel. – chehrlic Jul 27 '23 at 15:51

0 Answers0