[Qt-interest] Creating a QModelIndex outside of a QAbstractItemModel subclass

Dario Ahdoot dario.ahdoot at image-metrics.com
Wed Mar 11 23:11:06 CET 2009


Is it really not possible to create a QModelIndex outside of a QAbstractItemModel subclass?

* The QModelIndex c'tor which takes any args is private
* There are no setRow/setColumn methods
* To create a QModelIndex, you must call QAbstractItemModel::createIndex( row, column )
* However, createIndex is protected, so it is only callable from a subclass of QAbstractItemModel

This is rather inconvenient since it means that any time you have any piece of code that needs to create a QModelIndex you must either be in some subclass of QAbstractItemModel, or you must in your sub-class of QAbstractItemModel write a createIndex wrapper. Take for instance the following piece of code:

// In some QTreeView derived class:
void SomeView::SelectItemByName( const std::string & name )
{
	// Need to select using item selection instead of just a simple model index so it will select
	// the whole row (even though this is a select whole row table... grrrrr)
	QAbstractItemModel * itemModel = model();
	QItemSelectionModel * selModel = selectionModel();
	QModelIndexList matches = itemModel->match( itemModel->createIndex( 0, 0 ), Qt::DisplayRole, name, 1, Qt::MatchExactly );

	if( !matches.empty() )
	{
		QItemSelection selection;
 
 		selection.select( matches.at( 0 ), itemModel->createIndex( matches.at( 0 ).row(), EColumnCount - 1 ) );
 		selectionModel->select( selection, QItemSelectionModel::ClearAndSelect );
	}
}

This means that I will need to move this method into the QAbstractItemModel derived class just so I can call createIndex. I tried just passing a default constructed QModelIndex to the match method, however the match method always returns an empty list with a default constructed index.

I hope this makes sense. This is just one trivial example, but I have run into this a number of times.

Thanks,
Dario




More information about the Qt-interest-old mailing list