QSqlTableModel column to QStringList

  • I have QSqlTableModel:
    How I can get QstringList from column name with result: ("name1", "name2", "name3")

  • @
    QStringList nameList;

    // make sure the complete result set is fetched
    while (myModel->canFetchMore())

    for (int r = 0; r < model->rowCount(); ++r) {
    nameList << model->data(model->index(r,1));

    [Brain to terminal, not tested]

  • Thanks. I wanted simplest, but with little function works good.
    @QStringList get_str_col(QSqlTableModel *tm, QString col_name){
    int i, rc = tm->rowCount();
    QStringList list;
    for (i = 0; i < rc; i++) list << tm->data(tm->index(i, tm->fieldIndex(col_name))).toString();
    return list;
    QSqlTableModel *myModel;
    QStringList column_list;
    column_list = get_str_col(myModel, "name");@

  • 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

  • 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++?

  • 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.

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.