def add(self, index, accepted): """ Add the specified index to the cache together with it's accepted state :param index: The QModelIndex to be added :param accepted: True if the model index is accepted by the filtering, False if not. """ if not self.enabled: return cache_key = self._gen_cache_key(index) p_index = (cache_key if self._use_persistent_index_keys else QtCore.QPersistentModelIndex(index)) self._cache[cache_key] = (p_index, accepted)
def __init__(self): """ Construction """ self._cache = {} self.enabled = True self._cache_hits = 0 self._cache_misses = 0 # ideally we'd use QPersistentModelIndexes to key into the cache but these # aren't hashable in earlier versions of PySide! self._use_persistent_index_keys = True try: # wouldn't it be nice if there were an in-built mechanism to test if a type was # hashable! hash(QtCore.QPersistentModelIndex()) except: self._use_persistent_index_keys = False
def _gen_cache_key(self, index): """ Generate the key for the specified index in the cache. :param index: The QModelIndex to generate a cache key for :returns: The key of the index in the cache """ # ideally we would just use persistent model indexes but these aren't hashable # in early versions of PySide :( if self._use_persistent_index_keys: return QtCore.QPersistentModelIndex(index) # the cache key is a tuple of all the row indexes of the parent # hierarchy for the index. First, find the row indexes: rows = [] parent_idx = index while parent_idx.isValid(): rows.append(parent_idx.row()) parent_idx = parent_idx.parent() # return a tuple of the reversed indexes: return tuple(reversed(rows))