/ Qt

QModelIndex lookup

The MVC architecture of Qt *View classes is brilliant except one little thing that is not pretty obvious from the beginning: how to find the QModelIndex instance corresponding to specific internal pointer. I wonder why, but I’ve searched the Internet pretty much until I’ve found the possible solutions on Qt developer FAQ page: “How can a QModelIndex be retrived from the model for an internal data item?”. There are three possible solutions. I’ve chosen the first and the simplest one: “Use unique identifiers” as far as it matched our requirements. The main idea of this option is that when you create the instance of a QModelIndex you pass the pointer to some internal data, but you should be sure that there will be no QModelIndex‘es pointing to the same data. So how to implement this approach?

There are only two simple steps to implement this approach. First of all you need to modify the data() overload of your QAbstractItemModel derived model class to return the pointer to the internal data on request for Qt::UserRole role.

// ... skipped
else if (role == Qt::UserRole)
return QVariant::fromValue(parent(index).internalPointer());
// ... skipped

The second part is performing match() over your model:

QModelIndexList list = yourModel.match(
	yourModel.index(0,0),    // starting index for traverse
    Qt::UserRole,            // data source for comparison
    QVariant::fromValue((void*) yourInternalDataClass),    // searched value
    1,                       // maximum number of matched items, use -1 to
    						 // return all
	Qt::MatchFlags(Qt::MatchRecursive)    // match flags

Works like a charm…

Sergii Gulenok

Sergii Gulenok

Geek, project manager, software developer (web and application), backpacking tourist, amateur photographer, kendo swordsman, cyclist and (almost) biker.

Read More