Guest User

maya_nodes_tree_view

a guest
Sep 14th, 2018
236
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.10 KB | None | 0 0
  1. """
  2. https://groups.google.com/d/topic/python_inside_maya/DdTn2qiW2vc/discussion
  3.  
  4. Creating a tree view out of a list of Maya node paths
  5. """
  6. from PyQt4 import QtCore, QtGui
  7.  
  8.  
  9. class Window(QtGui.QMainWindow):
  10.  
  11.     PATH_ROLE = QtCore.Qt.UserRole+1
  12.  
  13.     def __init__(self, parent=None):
  14.         super(Window, self).__init__(parent)
  15.         self.tree = QtGui.QTreeWidget()
  16.         self.setCentralWidget(self.tree)
  17.  
  18.     def populate(self, paths):
  19.         view = self.tree
  20.         view.clear()
  21.  
  22.         for path in sorted(paths):
  23.             parts = [path.rsplit('|', i)[0] for i in xrange(path.count('|'))]
  24.             parts.reverse()
  25.  
  26.             parent = view.invisibleRootItem()
  27.  
  28.             for i, part in enumerate(parts):
  29.                 # We don't want to create duplicate branches
  30.                 # so we can check if the path already exists
  31.                 found = self.itemFromPath(part)
  32.                 if found:
  33.                     parent = found
  34.                     continue
  35.                
  36.                 # Create a new node under the current parent
  37.                 name = part.rsplit('|', 1)[-1]
  38.                 item = QtGui.QTreeWidgetItem([name])
  39.                 item.setData(0, self.PATH_ROLE, part)
  40.                 parent.addChild(item)
  41.                 parent = item
  42.  
  43.     def itemFromPath(self, path, parent=None):
  44.         """Find item by maya path"""
  45.         model = self.tree.model()
  46.         if parent is None:
  47.             parent = model.index(0, 0)
  48.         else:
  49.             parent = self.tree.indexFromItem(parent)
  50.  
  51.         found = model.match(parent, self.PATH_ROLE, path, flags=QtCore.Qt.MatchRecursive)
  52.         if not found:
  53.             return None
  54.  
  55.         return self.tree.itemFromIndex(found[0])
  56.  
  57.  
  58. if __name__ == "__main__":
  59.     app = QtGui.QApplication([])
  60.     win = Window()
  61.  
  62.     paths = [
  63.         "|root|one|two|three",
  64.         "|root|one",
  65.         "|root2|one|two2|three",
  66.         "|root|one|two2|three",
  67.         "|root2|one|two2|three3",
  68.     ]
  69.  
  70.     win.populate(paths)
  71.  
  72.     win.resize(800, 600)
  73.     win.show()
  74.     win.raise_()
  75.     app.exec_()
Advertisement
Add Comment
Please, Sign In to add comment