Search code examples
c++qtqt5qtableviewqstandarditemmodel

Is there a way to Convert QTableView model to QStandardItemModel


As you know QTableView->model() returns QAbstractItemModel. is there a way to fill an instance of QStandardItemModel with QTableView->model()? or convert QAbstractItemModel to QStandardItemModel? i need some of QStandardItemModel mothods like clear() and there is no such thing in QAbstractItemModel.

QStandardItemModel *model = new QStandardItemModel();
model = tblView->model();

error: invalid conversion from ‘QAbstractItemModel*’ to ‘QStandardItemModel*’ [-fpermissive]

For create table i use this code:

QStandardItemModel *model = new QStandardItemModel(0, 3, this);

for (int = 0; i < 100; i++) {
    model->setRowCount(model->rowCount() + 1);
    model->setData(model->index(i, 0), "...");
    model->setData(model->index(i, 1), "...");
    model->setData(model->index(i, 2), "...");
}
tblView->model() = model;

Solution

  • If that model is different from QStandardItemModel then you must create your own clear() method, so you should provide the code for that model. On the other hand, if it is a QStandardItemModel you can just cast it:

    model = qobject_cast<QStandardItemModel*>(tblView->model());