Can't insertColumn to an QSqlTableModel



  • Hi,

    I have a SQlTableModel on a database that returns 4 columns displayed in a QTableView.
    This works fine so long.

    But I wan't to add an extra column to my model, to display some database-independent data on it.
    But that doesn't work. I only see my 4 columns got from database. Any ideas, whats wrong?
    Thanks for help:

    @ _model = new QSqlTableModel();
    _model->setTable("machines");
    _model->select(); // Get column 0..3 out from database correctly

    _model->insertColumn(4); // Without any effect
    _model->setHeaderData(4, Qt::Horizontal, "MyExtraData"); // Without any effect

    _tableView = new QTableView();
    _tableView->setModel(_model);
    @



  • Obviously you can't add columns to a model which is showing SQL data. Use a proxy model instead.



  • I can't believe.
    Then the method QSqlTableModel::insertColumn() would be quite useless! ??



  • Of course. The insertColumn is inherited from QAbstractItemModel, and is needed for other uses of the item view system. But Qt's support does not extend to modifying the database structure, and that also extends to the SQL based model-view classes. If you want to do that, you will need to implement that yourself.

    Edit:
    What do you want to achieve exactly? Do you really want to add columns to your actual table in your database, or do you just want to show additional columns with data coming from somewhere else?



  • I only want to display an image (located on file-system) in the extra-column, depending on the values out of the database (columns before).
    (I don't want to add a column to the database itself).



  • OK, in that case, you have to go with a proxy model. There are several examples of using a proxy model here on the forum to add or modify data.

    Start out with subclassing QSortFilterProxyModel (Qt 4.7) or QIdentityProxyModel (Qt 4.8) as your starting point. Then, reimplement the columnCount() method to return the columnCount of your base model + 1. Then, you'll need to handle the calls to data(), headerData() and flags() for your new column.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.