Retrieve the content of a specific column from a QTableView

Viewed 809

I want to retrieve the content of a specific column from a qTableView which contains 2 columns; the problem is that i can't find a way to access it; i also tried to writing the following code(inspired by another question) but it doesn't solve the problem:

for(int i = 0; i < ui->table->model->rowCount(); i++) {
       QAbstractItemModel index = ui->table->model()->data(ui->table->model()->index(0,i));
       qDebug() << index;
}

What i'm doing wrong?

1 Answers

The return value of QAbstractItemModel::data() is of type QVariant.

The data in the returned QVariant depends on the role (the second parameter of data() which is per default Qt::DisplayRole), i.e. in this case QString (according to Qt::ItemDataRole).

Furthermore, the usage of QAbstractItemModel::index() looks wrong as well:
First parameter is row index, second parameter is column index.

Putting this alltogether, I recommend the following fix (without having tested):

for (int i = 0; i < ui->table->model->rowCount(); ++i) {
  QString value = ui->table->model()->data(ui->table->model()->index(i, 0));
  qDebug() << value;
}

to access data of the 1st column or

for (int i = 0; i < ui->table->model->rowCount(); ++i) {
  QString value = ui->table->model()->data(ui->table->model()->index(i, 1));
  qDebug() << value;
}

to access data of the 2nd column.

Related