March 21, 2012

betmens betmens
Lab Rat
18 posts

QSqlTableModel column to QStringList

 

I have QSqlTableModel:
id|name|data
0|name1|data1
1|name2|data2
2|name2|data
How I can get QstringList from column name with result: (“name1”, “name2”, “name3”)

5 replies

March 21, 2012

Volker Volker
Robot Herder
5428 posts

  1. QStringList nameList;
  2.  
  3. // make sure the complete result set is fetched
  4. while (myModel->canFetchMore())
  5.      myModel->fetchMore();
  6.  
  7. for (int r = 0; r < model->rowCount(); ++r) {
  8.     nameList << model->data(model->index(r,1));
  9. }

[Brain to terminal, not tested]

March 21, 2012

betmens betmens
Lab Rat
18 posts

Thanks. I wanted simplest, but with little function works good.

  1. QStringList get_str_col(QSqlTableModel *tm, QString col_name){
  2.  int i, rc = tm->rowCount();
  3.  QStringList list;
  4.  for (i = 0; i < rc; i++) list << tm->data(tm->index(i, tm->fieldIndex(col_name))).toString();
  5.  return list;
  6. }
  7. QSqlTableModel *myModel;
  8. QStringList column_list;
  9. column_list = get_str_col(myModel, "name");

March 21, 2012

Volker Volker
Robot Herder
5428 posts

Some remarks:

  • save the index of the field in a variable. It will speed up your method, as you do not need to look up the index for each row (it doesn’t change!)
  • rowCount() is not guaranteed to return the number of rows in the result set. If the database driver does not support returning the number of rows in a query (which is the case for Oracle, for example), you do get only the number of rows already fetched. In that case you are likely to miss rows

March 21, 2012

betmens betmens
Lab Rat
18 posts

About index I agree. And in Your example “model->rowCount()” should also be declare. At least in php works faster. Tested myself.
rowCount() fetch probably be useful in future.
How You think is here a difference between ++r vs r++?

March 21, 2012

Volker Volker
Robot Herder
5428 posts

What do you gain, if you method is fast, but wrong? Nothing than pain in the future!

Premature optimization is the cause of many evil! Make your method work correctly first, and then do optimizations and only if you run into performance issues!

++r or r++ is negligible in that case. Ask Google for the myriads of performance discussions on this topic please.

 
  ‹‹ Stylesheet not being applied to children of custom widget which subclasses QWidget      Problem in calling user defined class in dialog. ››

You must log in to post a reply. Not a member yet? Register here!