Robust selection of items in a tree or list view with variable text

This article is similiar to to Finding list items that ends in a given string however goes into a bit more detail and is also functional for treeviews as well as listviews. Dealing with a treeview requires careful handling of “.”-separated paths.

Imagine you need to select some item in a treeview, but you don’t know the exact string of the item as it may have changed. Alternatively maybe the parent item of the item you wish to select has changed, but the item is still the same. You need to find the item you want in the tree, and extract the correct Squish item identifier to interact with it later on.

For example, assume you need to find a certain file in treeview, but the treeview has items with absolute paths that might be different on various machines. All you know is that the filename you are looking for will be the same, if it exists. You wish to iterate through the treeview, checking each level against some known valid path that you have. For this example, we will assume you have paths such as

  1. \\server1\serverpath\some\path\test_data\test_project\filetest.db
  2. \\server32\serverpath\some\path\test_data\test_project\filetest.db
  3. C:\local_mirror\some\path\test_data\test_project\filetest.db

and you can’t be sure which path is in the treeview (potentially as a parent or child item). This means you might need to convert

  1. \\\\server1\\serverpath\\some\\path\\test\_data\\test\_project\\filetest\.db.sub\.Item.subSubItem

to

  1. C:\\local\_mirror\\some\\path\\test\_data\\test\_project\\filetest\.db.sub\.Item.subSubItem

(Note that these paths are escaped so that Squish’s itemview functions properly find the paths). As you can see, all three of the paths are the same from the “test_data” folder onwards, so we will use that to split between the “known good” parts of the path we wish to match, and the variable part we wish to replace.

  1. def findRealPath( treeviewname, origpath ):
  2.     import re
  3.    
  4.     print "Original path: ", origpath
  5.     treeView = waitForObject( treeviewname )
  6.     model = treeView.model()
  7.    
  8.     # we are looking for this
  9.     originalParts = origpath.split( "test\_data\\" )
  10.     pathOnly = originalParts[1]
  11.     # Remove the items separated by "." (but not \\. which is an escaped dot in the folder path)
  12.     print "Now splitting items: %s" % re.split( "[^\\\\]\\.", pathOnly, 1 )
  13.     pieces = re.split( "[^\\\\]\\.", pathOnly, 1 ) # only split once
  14.     pathOnly = pieces[ 0 ]
  15.     childrenItems = ""
  16.     if len( pieces ) > 1: # If this has children
  17.         childrenItems = pieces[ 1 ]
  18.     toplevel = model.rowCount( QModelIndex() )
  19.     for row in range( toplevel ): # iterate through tree, looking for matching file
  20.  # shortcut solution: check all top-level items in their first three columns. much more efficient if result is top-level
  21.         for col in range( 3 ): # check first few columns
  22.             idx = model.index( row, col, QModelIndex() )
  23.             if checkModelItemReplacement(idx, pathOnly):
  24.                 return replaceModelIndex(utils.escape(str( idx.data( Qt.DisplayRole ).toString() )), childrenItems)
  25.  
  26.  # didn't find what we were looking for in the top level, do a search two more levels down
  27.         # check all our children as well        
  28.         for col in range(20):
  29.             idx = model.index( row, col, QModelIndex() )
  30.             childCount = model.rowCount(idx)    
  31.             print "Checking children of item %s, found %s" % (idx.data(Qt.DisplayRole).toString(), childCount)
  32.             for childRow in range(childCount):
  33.                 child = model.index( 0, 0, idx )
  34.                 print "checking child %s: %s" % (childRow, child.data(Qt.DisplayRole).toString())
  35.                 if checkModelItemReplacement(child, pathOnly):
  36.                     # we need to do the replacement differently, because we need to keep the parent in the path
  37.                     partpieces = re.split( "([^\\\\])\\.", origpath )
  38.                     # find the index that has the test_data/ path. all indexes before that are parents
  39.                     for i in range(len(partpieces)):
  40.                         if "test\_data" in partpieces[i]: # stop here
  41.                             # since we split on [^\\\\]. and captured the split text, we need to condense each pair of items
  42.                             num = i/2
  43.                             parentItems = []
  44.                             for k in range(num):
  45.                                 parentItems.append( partpieces[k] + partpieces[k+1] ) # rescue the char lost when splitting
  46.                             parentstr = ".".join(parentItems)
  47.                             return replaceModelIndex(utils.escape(str( child.data( Qt.DisplayRole ).toString() )), childrenItems, parentstr)
  48.                            
  49.     # we failed
  50.     print "Failed to replace: %s" % origpath
  51.     return origpath
  52.  
  53. # used internally by above
  54. def checkModelItemReplacement( idx, pathOnly ):
  55.     contents = utils.escape(str( idx.data( Qt.DisplayRole ).toString() ))
  56.     print "Checking for %s in %s" % (pathOnly, contents)
  57.     if pathOnly in contents: # this is the entry we are looking for
  58.         return True
  59.     else:
  60.         return False
  61.  
  62. # used internally by above
  63. def replaceModelIndex( contents, children, parents = "" ):
  64.     print "Replacing with %s and %s with parent? %s" % (contents, children, parents)
  65.     replaced = contents
  66.    
  67.     if children != "":
  68.         replaced += "." + children
  69.         print "added children to replaced: %s" % replaced
  70.     if parents != "":
  71.         replaced = parents + "." + replaced
  72.         print "added parents to replaced: %s" % replaced
  73.     return replaced

As is visible in the above code sample, this code only searches three-levels-deep for a match. If your tree is deeper than 3 levels, you’ll need to either add another level of drilling down, or convert it into recursive function that works on any arbitrary level. The above code can be used like so:

  1. treeViewName = ":Your_treeview_here"
  2. itemPath = "\\\\server1\\serverpath\\some\\path\\test\_data\\test\_project\\filetest\.db.sub\.Item.subSubItem"
  3. realItemPath = findRealPath( treeViewName, itemPath )
  4. # realItemPath will be "C:\\local\_mirror\\some\\path\\test\_data\\test\_project\\filetest\.db.sub\.Item.subSubItem" if it exists, else the original path

Categories: