PDA

View Full Version : Select specific item in QListView



Cerberus
15th October 2015, 16:47
I have a QListView which contents I said with a Model. When resetting the model I need to reselect the previous item but I'm not sure how to search for it and than select it.
This is how I set the model:



void IMClientGui::setActiveUsers(QSqlQueryModel *sqm) {
QString currentUser = this->getSelectedHost();
ui->clientsOnline->setModel(sqm);
//here the old selection should be reset if this entry is still in the list
}

QString IMClientGui::getSelectedHost() {
auto itemselectmodel = ui->clientsOnline->selectionModel();

if (itemselectmodel->selectedIndexes().size() > 0) {
QModelIndex index = itemselectmodel->selectedIndexes().at(0);
return index.data().toString();
} else
return "";
}



I cannot work with the indexes here (e.g. if item with index 3 was selected reset to index 3) since a previous item might have been removed and therefore the index could be less or more if an item was added

anda_skoa
15th October 2015, 18:58
See QAbstractItemModel::match() for finding a model index with certain data.

Cheers,
_

Cerberus
15th October 2015, 21:54
I'm not sure how to use this method, what exactly am i supposed to put as QModelIndex and role? And how do I define the QVariant, in my case the displayed values are all QStrings?

ChrisW67
15th October 2015, 22:22
QModelIndexList indexes = model->match(
model->index(0,0), // first row, first column
Qt::DisplayRole, // search the text as displayed
stringValue, // there is a QVariant(QString) conversion constructor
1, // first hit only
Qt::MatchExactly // or Qt::MatchFixedString
);

Cerberus
15th October 2015, 22:33
When executing this



auto model = ui->clientsOnline->selectionModel()->model();

QModelIndexList indexes = model->match(
model->index(0,0), // first row, first column
Qt::DisplayRole, // search the text as displayed
currentUser, // there is a QVariant(QString) conversion constructor
1, // first hit only
Qt::MatchExactly // or Qt::MatchFixedString
);



I get a Segmentation fault!?

ChrisW67
17th October 2015, 00:33
So model is 0 or invalid. Why are you going via the selection model anyway?

Something like this:
When the data model emits modelAboutToBeReset() you want to store the current value selected in the list view.


const QModelIndex currentIndex = ui->clientsOnline->currentIndex(); // may be an invalid index
m_previouslySelected = (currentIndex.isValid())? currentIndex->data(Qt::DisplayRole): QVariant();

When the data model later emits modelReset() find and restore the list view's current item if possible:


if (!m_previouslySelected.isNull()) {
const QAbstractItemModel *model = ui->clientsOnline->model();
const QModelIndexList indexes = model->match(
model->index(0,0),
Qt::DisplayRole,
m_previouslySelected,
1, // first hit only
Qt::MatchExactly
);
if (index.size() > 0) { // found a match
ui->clientsOnline->setCurrentIndex(indexes.at(0));
}
}

Cerberus
17th October 2015, 14:55
Worked thanks