PDA

View Full Version : Find data in QCombobox invisible column



Gretsch
29th June 2013, 16:01
Hi all,

I'm trying to find a method of selecting an item of a combo box populated from a SQL query model.


QSqlQueryModel * query1 = new QSqlQueryModel;
query1->setQuery("SELECT ID, Name FROM Cat order by Name");
myQComboBox->setModel(query1);
myQComboBox->setModelColumn(1);


Now I want to find data in the invisible column 0 that matches a given ID so I can set the combo box text from the index that's returned from the found record. I can't find a way of doing this. Is it possible ?

anda_skoa
29th June 2013, 16:19
You iterate through the model and access its data using the data() method.
Once you've found what you are looking for you take the row() value of the model index and use setCurrentIndex() on the combobox.

Cheers,
_

Gretsch
29th June 2013, 16:49
I worked out a solution:

QModelIndex index;
QAbstractItemModel * model = myQComboBox->model();
int ndx = 0;
for (int i = 0; i < model->rowCount(); ++i)
{
index = myQComboBox->model()->index(i,0);
if (model->data(index)==id)
{
ndx = i;
break;
}
}
myQComboBox->setCurrentIndex(ndx);

ChrisW67
30th June 2013, 22:30
You can also use QAbstractItemModel::match()

Gretsch
1st July 2013, 03:38
You can also use QAbstractItemModel::match()

That's handy to know, it's a one liner compared to a for...loop, not sure which method would be more efficient though.

ChrisW67
1st July 2013, 04:26
match() can search the entire column in table or tree from an arbitrary starting index, optionally wrapping, so it is probably more involved internally.

anda_skoa
1st July 2013, 08:45
Efficiency probably depends on the model's implementation of match. Since it is virtual a model could have a non-linear way of looking for the value, e.g. some form of index or lookup-table.

It also doesn't necessarily have to go through data() every time, which, as a public method, has to check its arguments for validity on every call.

The explicit loop allows more flexibility on how the matching is done though, e.g. how to compare the values, whether to do any weighting of match results, etc.

Cheers,
_