Search code examples
c++qtqtableviewqlistwidgetqmodelindex

set current index of qtableview base on some string


I have a QTableView whith a QSqlqueryModel

QSqlQueryModel db_model_.setQuery("SELECT * FROM Main WHERE Type='1' ORDER BY Count DESC");
tableView.setModel(&db_model_);

Main defined as :

Word(TEXT) | Count(INTEGER) | Type(INTEGER

I want to select a row of this table base on the text of item that user selects from another QListWidget .

I tried setCurrentIndex but it accept a QModelIndex . I can't figure out how to search through whole Word column of my tableView and find the string of that listWidget and feed it to QModelIndex

void (QListWidget::*itemClicked)(QListWidgetItem*) = &QListWidget::itemClicked;

connect(&listWidget, itemClicked, [&](QListWidgetItem * item){
    const QString& text= item->text();
    //How to search thorough the Word column and find text and select it?!
});

Note that I can't use same model for these two widget because the way they fill is completely different .

enter image description here


Solution

  • I used QAbstractItemModel::index for iterating through the first column and using setCurrentIndex for changing the current selected item.

    It works fine now.

    connect(&listWidget, itemClicked, [&](QListWidgetItem * item){
        const QString& text= item->text();
        int size = tableView.model()->rowCount();
        for (int i = 0; i < size; i++){
            QModelIndex& cur=tableView.model()->index(i, 0);
            if (cur.data() == text){
                tableView.setCurrentIndex(cur);
                tableView.scrollTo(cur);
                break;
            }
        }
    });