Created
August 9, 2010 16:41
-
-
Save Ramblurr/515685 to your computer and use it in GitHub Desktop.
Proxy model for filtering only the 1st level children in a treemodel. Assumes 1 column, 2 level tree.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
Proxy model for filtering only the 1st level children in a treemodel. Assumes 1 column, 2 level tree. | |
If the source model is: | |
Parent 1 | |
- child 1 | |
- child 2 | |
Parent 2 | |
- child 4 | |
- child 5 | |
Then this proxy model will be: | |
child 1 | |
child 2 | |
child 3 | |
child 4 | |
child 5 | |
*/ | |
QModelIndex ProxyModel::index( int row, int column, const QModelIndex& parent ) const | |
{ | |
if ( !hasIndex( row, column, parent ) ) | |
return QModelIndex(); | |
return createIndex( row, 0 ); | |
} | |
int ProxyModel::rowCount( const QModelIndex& /* parent */ ) const | |
{ | |
int count = 0; | |
for ( int i = 0; i < sourceModel()->rowCount(); ++i ) { | |
QModelIndex parent = sourceModel()->index( i, 0 ); | |
count += sourceModel()->rowCount( parent ); | |
} | |
return count; | |
} | |
QModelIndex ProxyModel::mapFromSource( const QModelIndex& sourceIndex ) const | |
{ | |
if ( !sourceIndex.isValid() ) | |
return QModelIndex(); | |
if ( !sourceIndex.parent().isValid() ) | |
return QModelIndex(); | |
int count = 0; | |
for ( int i = 0; i < sourceIndex.parent().row(); ++i ) { | |
QModelIndex parent = sourceModel()->index( i, 0 ); | |
count += sourceModel()->rowCount( parent ); | |
} | |
count += sourceIndex.row(); | |
return index( count, 0 ); | |
} | |
QModelIndex ProxyModel::mapToSource( const QModelIndex& proxyIndex ) const | |
{ | |
int proxy_row = proxyIndex.row(); | |
int count = 0; | |
QModelIndex parent; | |
bool found = false; | |
//locate the parent index which contains proxy_row | |
for ( int i = 0; i < sourceModel()->rowCount(); ++i ) { | |
parent = sourceModel()->index( i, 0 ); | |
count += sourceModel()->rowCount( parent ); | |
if ( count > proxy_row ) { | |
count = sourceModel()->rowCount( parent ); | |
found = true; | |
break; | |
} | |
} | |
if ( !found ) { | |
qDebug() << "source model parent not found"; | |
return QModelIndex(); | |
} | |
// qDebug() << proxy_row <<"%" << count << "=" << proxy_row % count; | |
return sourceModel()->index( proxy_row % count, 0, parent ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment