QTableview scrollTo most accurate value.
-
Hello, i have a QTableview, and also i have a button to search for an specific row and then select it, it works fine using this code:
int size = ui->tableView->model()->rowCount(); for (int i = 0; i < size; i++){ QModelIndex cur = ui->tableView->model()->index(i, 0); if (cur.data() == ui->lineEdit->text()){ ui->tableView->setCurrentIndex(cur); ui->tableView->scrollTo(cur); } }
I have been looking for a way to do exactly the same thing, but searching also for the most accurate value according to my line edit text, because this code only works for the exact match, is there a way to do it?
Thanks!
-
QAbstractItemModel *model = ui->tableView->model(); QModelIndexList matchList = model->match(model->index(0, 0), Qt::EditRole, "Lami", -1, Qt::MatchFlags(Qt::MatchContains|Qt::MatchWrap));
-
Hi,
What do you mean by "most accurate" ?
Are you looking for the QAbstractItemModel::match method ?
-
@SGaist As an example, i have 3 items on my QTableview, Laminate, Lamborghini and Lotus, so if i dont put the exact name on the QLineedit it wont find anything, but i want something that if i put "Lami" on the QLineedit, it will find Laminate, and then i can scroll and select it.
-
Then match is what you are looking for. Using
Qt::MatchContains
at lease for the search flags. -
QAbstractItemModel *model = ui->tableView->model(); QModelIndexList matchList = model->match(model->index(0, 0), Qt::EditRole, "Lami", -1, Qt::MatchFlags(Qt::MatchContains|Qt::MatchWrap));
-
@SGaist Hi, thanks its working like a charm, but... if by any reason i add text pluz numbers to the search like "Lamin34" the program closes unexpectedly, this is my code:
void Inventory::on_Search_clicked(){ QModelIndexList matchList; matchList = ui->tableView->model()->match(ui->tableView->model()->index(0, 0), Qt::EditRole, ui->lineEdit->text(), -1, Qt::MatchFlags(Qt::MatchContains|Qt::MatchWrap)); ui->tableView->setCurrentIndex(matchList.first()); ui->tableView->scrollTo(matchList.first()); QSound::play("/home/adan/Groostore/Resources/Sounds/Update.wav"); }
Any clue on why is happening? :C
Update:
Fixed, the issue was that if i added text that did not match with any index, it wont be able to select anythig:
void Inventory::on_Search_clicked(){ QModelIndexList matchList = ui->tableView->model()->match(ui->tableView->model()->index(0, 0), Qt::EditRole, ui->lineEdit->text(), -1, Qt::MatchFlags(Qt::MatchContains|Qt::MatchWrap)); if(matchList.count()>=1){ ui->tableView->setCurrentIndex(matchList.first()); ui->tableView->scrollTo(matchList.first()); } QSound::play("/home/adan/Groostore/Resources/Sounds/Update.wav"); }
Thanks!!!