Important: Please read the Qt Code of Conduct -

Setting Header Data with QSqlQueryModel does not work

  • Hi,

    I'm working with a "QSqlQueryModel ": display data from a SQL query. Ususally the column header is taken from the column names returned by the query. As I'd like them to be always the same regardless of the underlying query I tried setting the column captions by using setHeaderData(...) but that does not work out and the captions are taken from the query.

    Here's what I'm currently doing:
    void RecipeListWidget::setModel(QAbstractItemModel *model)
    qDebug() << "RecipeLisWidget::setModel(" << model << ")" << endl;
    model->setHeaderData(0, Qt::Horizontal, tr("Name"));
    model->setHeaderData(1, Qt::Horizontal, tr("Score"));

    The could is designed to run with any kind of model so I'm using "QAbstractItemModel ": the function signature, but a QSqlQueryModel is passed as argument.

    Thanks for any advice on that one :)

  • Make a QAbstractProxyModel or QSortFilterProxyModel which only reimplements headerData() to return the header strings you want. All other stuff shall be forwarded (QSortFilterProxyModel already does the forwarding for you. Just disable the filtering by reimplementing acceptsRow/Column to always return true).

    //EDIT: Oh yes, and then use the proxy model between the model and the view with setSourceModel ;). If you want to tie the proxy model to the view, you can of course integrate the proxy model into the view and reimplement the setModel method of your view to call setSourceModel on the internal proxy, and then call the base class setModel function with the proxy as parameter.

Log in to reply