groenhen groenhen - 1 month ago 9
SQL Question

How to replace numeric values of a column of a SQL table view with text aliases?

I am using Qt5.
I managed to connect to a sql database and using

QtCreator
I have now a
QTableView
that is nicely populated using
SELECT * ...
from a test table I previously defined with MS SQL Manager...

Only one thing I would like to change:

...One column named "Error" has now numeric/integer values like: -101, -102, -105, and so on. To be honest I would prefer to have "Error opening file" instead of -101, also "Socket error" instead of -105, etc. you get the point.
Also, this "modification" must not affect the table in the database, but only the table-view.

Please, do you have any idea how I can do this?

Answer

You should create a subclass of QSortFilterProxyModel and reimplement its data virtual method. It can be something like this:

QVariant MyModel::data(const QModelIndex & index, int role = Qt::DisplayRole) const {
  QVariant result = QSortFilterProxyModel::data(index, role);
  if (index.column() == ERROR_COLUMN) {
    result = error_to_string(result.toInt());
  }
  return result;    
}

See the documentation to learn how to use proxy models.

Comments