PDA

View Full Version : can't get right data after sort



wirasto
28th June 2009, 16:45
I realize that after the sorting process by clicking on the header in the tableView, making the data in the table to be inaccurate

example

1 | "Si a"
5 | "Si e"
2 | "Si b"

After click table header and data sorted

1 | "Si a"
2 | "Si b" <- click this row
5 | "Si e"

I still get old data. Still 5 | "Si e", not 2 | "si b"



model=new QSqlQueryModel();
model->setQuery("select * from almari");

QSortFilterProxyModel *proxyModel = new QSortFilterProxyModel(this);
proxyModel->setSourceModel(model);

ui->tableView->setModel(proxyModel);
ui->tableView->setSortingEnabled(TRUE);

connect(ui->tableView, SIGNAL(pressed(const QModelIndex &)), this, SLOT(clickForEdit(const QModelIndex &)));





void Dialog::clickForEdit(const QModelIndex &index)
{
int row = index.row();
qDebug() << " ID : " << model->record(row).value("id").toInt();
qDebug() << " Nama : " << model->record(row).value("nama").toString();
}



Sorry, my english is bad :o

Lykurg
28th June 2009, 16:55
Not tested, but you have to convert the index of your sort model to your source model:



int row = proxyModel->mapToSource(index).row(); // proxyModel must be a member variable!

EDIT: Or use ui->tableView->model()->mapToSource(index)...

faldzip
28th June 2009, 16:57
void Dialog::clickForEdit(const QModelIndex &index)
{
int row = index.row();
qDebug() << " ID : " << model->record(row).value("id").toInt();
qDebug() << " Nama : " << model->record(row).value("nama").toString();
}



after the sort only proxy model's indexes changed so:


model->record(row).value("id").toInt();
would return same value as long as you click on same row and sorting has nothing to do with this, because you have index from proxy model, taking it row in proxy model, and than taking value from source model at row which is valid only in proxy model.
What you have to do is to map proxy index to source index:


QModelIndex sourceIndex = proxyModel->mapToSource(index);

and then take the source row:


int row = sourceIndex.row();

and now you can use the row to get proper data.

wirasto
28th June 2009, 17:08
Ok, solved. Thank's

But, how about use QSqlTableModel and sort enabled too.

/home/wirasto/qt4/proxy/dialog.cpp:56: error: 'class QSqlTableModel' has no member named 'mapToSource'

faldzip
28th June 2009, 18:39
Ok, solved. Thank's

But, how about use QSqlTableModel and sort enabled too.

/home/wirasto/qt4/proxy/dialog.cpp:56: error: 'class QSqlTableModel' has no member named 'mapToSource'
QSqlTableModel IS your source model and mapToSource is proxy model method so you have to use it on proxy model, and you get the QSqlTableModel's index;

wirasto
28th June 2009, 19:19
OK. Solved.

Thank's