You've just copied and pasted the example from the documentation. If your columns don't contain the same information, or if you only want to look at column 0, then of course it won't work. It also doesn't implement recursive filtering, so it certainly won't do what the Qt5 version does.

In your initial post, you don't set any regular expression, so what exactly are you filtering based on? The default behavior of the proxy when there is no regexp is to accept everything.

Remember that the default behavior of QSortFilterProxyModel is to stop recursing as soon as filterAcceptsRow() returns false for any row. So even if a child row matches, if the parent doesn't the child row will never be examined and the parent row will not be displayed.

This is the opposite behavior that occurs when setRecursiveFilteringEnabled() is set to true. In that case, if any child row passes the test, then you want the parent to be displayed.

So if you want to implement recursive filtering the way it works in Qt5, you have to do the recursion yourself.

If you are using a QRegExp to hold the filter string, then your version of filterAcceptsRow() should look like this:

*** WARNING: Untested code. Might be buggy. ***
Qt Code:
  1. /*
  2.  * Implementation of manual recursive filtering for Qt < 5
  3.  *
  4. */
  5.  
  6. bool MySortFilterProxyModel::filterAcceptsRow( int sourceRow, const QModelIndex & sourceParent ) const
  7. {
  8. #if QT_VERSION < 0x050000
  9.  
  10. // Qt is less than 5, so manually perform recursion
  11.  
  12. // Default QSortFilterProxyModel behavior for an empty regexp
  13. if ( filterRegExp().isEmpty() )
  14. return true;
  15.  
  16. QModelIndex index0 = sourceModel()->index( sourceRow, 0, sourceParent );
  17.  
  18. // If column0 at the current level matches, return true
  19. if ( sourceModel()->data( index0, Qt::DisplayRole ).toString().contains( filterRegExp() ) )
  20. return true;
  21.  
  22. // The current level doesn't match but if it has children, recurse to look at them
  23. else if ( sourceModel()->hasChildren( index0 ) )
  24. {
  25. bool bResult = false;
  26. int nRows = sourceModel()->rowCount( index0 );
  27.  
  28. // Look at each child row. If any one of them matches (bResult == true) then the loop will exit
  29. for ( int nRow = 0; nRow < nRows && !bResult; ++nRow )
  30. {
  31. bResult = filterAcceptsRow( nRow, index0 );
  32. }
  33.  
  34. // Return whatever the loop result was. If any child matches, this is true, otherwise it is false.
  35. return bResult;
  36. }
  37.  
  38. // Otherwise, nothing at this level or below it matches, so the whole subtree is ignored.
  39. return false;
  40.  
  41. #else
  42. // Qt version is > 4, so use default implementation
  43. return QSortFilterProxyModel::filterAcceptsRow( sourceRow, sourceParent );
  44.  
  45. #endif
  46. }
To copy to clipboard, switch view to plain text mode