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

Jaco Naude naude.jaco at gmail.com
Thu Mar 12 08:02:36 CET 2009


I've been in the same situation quite a few times where I needed a
QModelIndex. There is probably a good reason for it though.
Cheers

On Thu, Mar 12, 2009 at 12:11 AM, Dario Ahdoot <
dario.ahdoot at image-metrics.com> wrote:

> 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
>
> _______________________________________________
> Qt-interest mailing list
> Qt-interest at trolltech.com
> http://lists.trolltech.com/mailman/listinfo/qt-interest
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.qt-project.org/pipermail/qt-interest-old/attachments/20090312/deb788ba/attachment.html 


More information about the Qt-interest-old mailing list