Ejemplo n.º 1
0
	def _proceed_dir(self, d, parentItem):
		#d = QtCore.QString(_d).toUtf8().data()
		if (not os.access(d, os.F_OK) or
			not os.access(d, os.R_OK) or
			not os.access(d, os.X_OK)):
			return

		try :
			for entry_dir in os.listdir(d):
				try:
					#print entry_dir, ':', d, QtCore.QString().fromUtf8(d), \
					#						QtCore.QString().fromUtf8(entry_dir)
					#fullpath = os.path.join(d, entry_dir)
					fullpath = QtCore.QString().fromUtf8(d) + self.SEP + \
											QtCore.QString().fromUtf8(entry_dir)
				except UnicodeEncodeError :
					#print 'UnicodeError_file'
					continue
				except UnicodeDecodeError :
					#print 'UnicodeError_file'
					continue
				if os.path.islink(unicode(fullpath)) or \
					not os.path.isdir(unicode(fullpath)): #FIXME: remove this line if you have add and files too
					continue

				entryItem = TreeItem(QtCore.QString().fromUtf8(entry_dir), self.typePath, parentItem)
				if os.path.isdir(unicode(fullpath)):
					self._proceed_dir(fullpath, entryItem)

				parentItem.appendChild(entryItem)
				entryItem.checkState = QtCore.Qt.Checked
		except OSError :
			print 'OSError'
			pass
Ejemplo n.º 2
0
 def __init__(self, parent, node):
     TreeItem.__init__(self, parent, node)
     tagDict = self.document.XMLTag2ClassDict
     self.childs = [
         tagDict[childNode.tag](self, childNode) for childNode in node
     ]
     self.isExpanded = node.attrib.get("expanded") == "True"
Ejemplo n.º 3
0
    def __init__(self, parent, node):
        TreeItem.__init__(self, parent, node)
        text = node.text
        if not text:
            # this should never happen
            return
        text = text.strip()
        objStr, remainder = text.split('(', 1)
        objStr = PATCHES.get(objStr, objStr)
        argString, _ = remainder.rsplit(')', 1)
        pluginStr, actionStr = objStr.split(".", 1)
        plugin = getattr(eg.plugins, pluginStr).plugin
        try:
            action = plugin.info.actions[actionStr]
        except KeyError:
            eg.PrintError("Can't find action: " + text)
            action = None
        if action is None or not issubclass(action, eg.ActionBase):
            action = eg.plugins.EventGhost.plugin.info.actions["PythonCommand"]
            argString = repr(text)
        try:
            self.executable = action()
        except:
            eg.PrintTraceback(msg="Error in action: " + repr(text))
            self.executable = eg.plugins.EventGhost.PythonCommand
            argString = repr(text)

        self.icon = action.info.icon
        self.SetArgumentString(argString)
Ejemplo n.º 4
0
	def parseFile_(self, listNodes, parent_obj, tab = '	'):
		i = 0; count = 0; downLoads = 0
		while i < listNodes.length :
			node = listNodes.item(i)
			if node is not None :
				name_ = node.localName

				if node.attributes.length >= 2 :
					#print tab, 'name :', name_, \
					#		'attr :', node.attributes.item(0).value, node.attributes.item(1).value
					#_ddata = [node.attributes.item(0).value, node.attributes.item(1).value]  ##name_ + ' , ' +
					fileName = node.attributes['name'].value
					fileSize = node.attributes['size'].value
					if name_ == 'file' :
						count += 1
						_str = string.split(fileSize, ' ')
						if len(_str) > 1 : downLoads += int(_str[0])
				else :
					#_ddata = [node.attributes.item(0).value, name_] ## временно для заполнения дерева в клиенте
					fileName = node.attributes['name'].value
					fileSize = name_
				_newobj = TreeItem(fileName, fileSize, parent_obj)
				if node.attributes.length == 3 : _newobj.Root = node.attributes['xRoot'].value
				parent_obj.appendChild(_newobj)
				if name_ == 'dir':
					_count, _downLoads = self.parseFile_(node.childNodes, _newobj, tab + '\t')
					count += _count
					downLoads += _downLoads
			i += 1
		return count, downLoads
Ejemplo n.º 5
0
 def _Delete(self):
     TreeItem._Delete(self)
     for arg in self.GetArgs():
         if isinstance(arg, TreeLink):
             if arg.target:
                 arg.target.dependants.remove(arg)
             arg.owner = None
             arg.target = None
             del arg
Ejemplo n.º 6
0
    def get_type(json_document, root_item):

        if isinstance(json_document, QJsonValue):
            if json_document.isBool():
                name = 'True' if json_document.isBool() else 'False'
                root_item.setValue(name)
                return

            if json_document.isDouble():
                name = str(json_document.toDouble())
                root_item.setValue(name)
                return

            if json_document.isNull():
                name = 'None'
                root_item.setValue(name)
                return

            if json_document.isString():
                name = json_document.toString()
                root_item.setValue(name)
                return

        if json_document.isArray():
            array_item = TreeItem('array', root_item)
            array = None
            if isinstance(json_document, QJsonDocument):
                array = json_document.array()
            elif isinstance(json_document, QJsonValue):
                array = json_document.toArray()

            for el in array:
                TreeModel.get_type(el, array_item)

            root_item.appendChild(array_item)
            return

        if json_document.isNull():
            name = 'None'
            root_item.appendChild(TreeItem(name, root_item))
            return

        if json_document.isObject():
            json_document_object = None
            if isinstance(json_document, QJsonDocument):
                json_document_object = json_document.object()
            elif isinstance(json_document, QJsonValue):
                json_document_object = json_document.toObject()

            for obj in json_document_object:
                obj_item = TreeItem(obj, root_item)
                TreeModel.get_type(json_document_object[obj], obj_item)
                root_item.appendChild(obj_item)

            return

        return
Ejemplo n.º 7
0
 def __init__(self, parent, node):
     TreeItem.__init__(self, parent, node)
     tagDict = self.document.XMLTag2ClassDict
     self.childs = [
         tagDict[childNode.tag.lower()](self, childNode)
         for childNode in node
     ]
     if node.attrib.get("expanded", "").lower() == "true":
         self.document.expandedNodes.add(self)
Ejemplo n.º 8
0
 def __init__(self, parent, node):
     TreeItem.__init__(self, parent, node)
     tagDict = self.document.XMLTag2ClassDict
     self.childs = [
         tagDict[childNode.tag.lower()](self, childNode)
         for childNode in node
     ]
     if node.attrib.get("expanded", "").lower() == "true":
         self.document.expandedNodes.add(self)
Ejemplo n.º 9
0
    def insertItem(self, item, index=None):
        if isinstance(item, str):
            item = TreeItem(item)

        ret = self.root.addItem(item)
        if index is None:
            DOM.appendChild(self.getElement(), item.getElement())
        else:
            DOM.insertChild(self.getElement(), item.getElement(), index)

        return ret
Ejemplo n.º 10
0
 def setupModelData(self, lines, parent):
     parents = [parent]
     indentations = [0]
     
     number = 0
     
     while number < len(lines):
         position = 0
         while position < len(lines[number]):
             if lines[number][position] != ' ':
                 break
             position += 1
         lineData = lines[number][position:].trimmed()
         if lineData:
             # Read the column data from the rest of the line.
             columnData = [s for s in lineData.split('\t') if s]
             if position > indentations[-1]:
                 # The last child of the current parent is now the new
                 # parent unless the current parent has no children.
                 if parents[-1].childCoun() > 0:
                     parents.append(parents[-1].child(parents[-1].childCount() - 1))
                     indentations.append(position)
         else:
             while position < indentations[-1] and len(parents) > 0:
                 parents.pop()
                 indentations.pop()
         parents[-1].appendChild(TreeItem(columnData, parents[-1]))
     number += 1
Ejemplo n.º 11
0
 def GetData(self):
     attr, text = TreeItem.GetData(self)
     action = self.executable
     text = "%s.%s(%s)" % (action.plugin.info.evalName,
                           action.__class__.__name__, ", ".join(
                               [repr(arg) for arg in self.args]))
     return attr, text
Ejemplo n.º 12
0
 def __nodeInsert(self, TreeItem):
     for i in range(self.root.getLength()):  # Insert at right place in Node
         if self.root.retrieve(i)[0] is not None:
             if self.root.retrieve(i)[0].getKey() > TreeItem.getKey():
                 self.root.insert(i, TreeItem)
                 return True
     self.root.insert(self.root.getLength(), TreeItem)
     return True
Ejemplo n.º 13
0
 def __init__(self, parent, node):
     TreeItem.__init__(self, parent, node)
     if node.text:
         try:
             args = pickle.loads(base64.b64decode(node.text))
         except:
             args = ()
     else:
         args = ()
     ident = node.attrib.get('identifier', None)
     pluginStr = node.attrib['file']
     self.pluginFile = pluginStr
     self.info = info = eg.PluginInfo.Open(pluginStr, ident, args, self)
     self.name = eg.text.General.pluginLabel % info.label
     if info.icon != self.icon:
         self.icon = eg.Icons.PluginSubIcon(info.icon)
     #self.icon = info.icon
     self.executable = info.instance
Ejemplo n.º 14
0
 def searchTreeInsert(self, TreeItem):
     """
     Inserts TreeItem in BinarySearchTree
     :param TreeItem: TreeItem to be inserted
     :return: False if key is already present
     """
     if self.isEmpty():
         self.root = TreeItem
     elif TreeItem.getKey() < self.root.getKey():
         if self.left is None:
             self.left = BinarySearchTree()
         self.left.searchTreeInsert(TreeItem)
     elif TreeItem.getKey() > self.root.getKey():
         if self.right is None:
             self.right = BinarySearchTree()
         self.right.searchTreeInsert(TreeItem)
     else:
         return False
Ejemplo n.º 15
0
 def Delete(self):
     TreeItem.Delete(self)
     for arg in self.GetArguments():
         if isinstance(arg, TreeLink):
             if arg.target:
                 arg.target.dependants.remove(arg)
             arg.owner = None
             arg.target = None
             del arg
Ejemplo n.º 16
0
 def searchTreeInsert(self, TreeItem):
     """
     Inserts tree item in binary search tree.
     :param TreeItem: tree item to be inserted
     :return: bool indicating if insert was successful
     """
     if self.isEmpty():
         return self.root.append(TreeItem)
     elif TreeItem.getKey() < self.root.first().getKey():
         if self.left is None:
             self.left = BinarySearchTree()
         return self.left.searchTreeInsert(TreeItem)
     elif TreeItem.getKey() > self.root.first().getKey():
         if self.right is None:
             self.right = BinarySearchTree()
         return self.right.searchTreeInsert(TreeItem)
     else:
         return self.root.append(TreeItem)
Ejemplo n.º 17
0
 def GetData(self):
     attr, text = TreeItem.GetData(self)
     del attr[0]
     attr.append(('Identifier', self.executable.info.evalName))
     guid = self.executable.info.guid
     if guid:
         attr.append(('Guid', guid))
     attr.append(('File', self.pluginName))
     text = base64.b64encode(pickle.dumps(self.info.args, 2))
     return attr, text
Ejemplo n.º 18
0
def readFile():
    file = open("input.txt", "r")       # opens file
    command = file.readline()
    if "type" in command:
        if "bst" in command:        # creates BSTree
            b = BinarySearchTree()
            command = file.readline()
            while command is not None:
                if len(command.strip()) == 0:
                    break
                elif "insert" in command:       # inserts in BSTree
                    number = int(command.split()[1])
                    b.searchTreeInsert(TreeItem(str(number), number))
                    command = file.readline()
                elif "delete" in command:       # deletes in BSTree
                    number = int(command.split()[1])
                    b.searchTreeDelete(number)
                    command = file.readline()
                elif "print" in command:        # gives DOT-language of BSTree
                    createDotFileBST(b)
                    command = file.readline()
                    readFile()
        elif "234" in command:      # creates 234-Tree
            t = TwoThreeFourTree()
            command = file.readline()
            while command is not None:
                if len(command.strip()) == 0:
                    break
                elif "insert" in command:       # inserts in 234-Tree
                    number = int(command.split()[1])
                    t.twoThreeFourTreeInsert(TreeItem(str(number), number))
                    command = file.readline()
                elif "delete" in command:       # deletes in 234-Tree
                    number = int(command.split()[1])
                    t.twoThreeFourTreeDelete(number)
                    command = file.readline()
                elif "print" in command:        # gives DOT-language of 234-Tree
                    createDotFileTTFT(t)
                    command = file.readline()
Ejemplo n.º 19
0
 def __init__(self, parent, node):
     TreeItem.__init__(self, parent, node)
     if node.text:
         try:
             args = pickle.loads(base64.b64decode(node.text))
         except:
             args = ()
     else:
         args = ()
     evalName = node.attrib.get('identifier', None)
     self.pluginName = node.attrib.get('file', None)
     guid = node.attrib.get('guid', self.pluginName)
     self.info = info = eg.pluginManager.OpenPlugin(
         guid,
         evalName,
         args,
         self,
     )
     self.name = eg.text.General.pluginLabel % info.label
     if info.icon != self.icon:
         self.icon = eg.Icons.PluginSubIcon(info.icon)
     #self.icon = info.icon
     self.executable = info.instance
Ejemplo n.º 20
0
 def __init__(self, parent, node):
     TreeItem.__init__(self, parent, node)
     if node.text:
         try:
             args = pickle.loads(base64.b64decode(node.text))
         except:
             args = ()
     else:
         args = ()
     evalName = node.attrib.get('identifier', None)
     self.pluginName = node.attrib.get('file', None)
     guid = node.attrib.get('guid', self.pluginName)
     self.info = info = eg.pluginManager.OpenPlugin(
         guid,
         evalName,
         args,
         self,
     )
     self.name = eg.text.General.pluginLabel % info.label
     if info.icon != self.icon:
         self.icon = eg.Icons.PluginSubIcon(info.icon)
     #self.icon = info.icon
     self.executable = info.instance
Ejemplo n.º 21
0
    def AskDelete(self):
        actionItemCls = self.document.ActionItem

        def SearchFunc(obj):
            if obj.__class__ == actionItemCls:
                if obj.executable and obj.executable.plugin == self.executable:
                    return True
            return None

        if self.root.Traverse(SearchFunc) is not None:
            eg.MessageBox(eg.text.General.deletePlugin, eg.APP_NAME,
                          wx.NO_DEFAULT | wx.OK | wx.ICON_EXCLAMATION)
            return False
        if not TreeItem.AskDelete(self):
            return False
        return True
Ejemplo n.º 22
0
 def _Delete(self):
     self.UnRegisterEvent(self.name)
     TreeItem._Delete(self)
Ejemplo n.º 23
0
 def GetData(self):
     attr, text = TreeItem.GetData(self)
     if self in self.document.expandedNodes:
         attr.append(("Expanded", "True"))
     return attr, text
Ejemplo n.º 24
0
	def __init__(self, section1Name, section2Name, parent = None):
		QtCore.QAbstractItemModel.__init__(self, parent)

		self.rootItem = TreeItem(section1Name, section2Name, None, self)
		self.changeMe = True
Ejemplo n.º 25
0
 def tableInsert(self, order):
     return self.bst.searchTreeInsert(TreeItem(order, order.getTimestamp()))
Ejemplo n.º 26
0
 def twoThreeFourTreeInsert(self, TreeItem):
     """
     Inserts given TreeItem at right place in TwoThreeFourTree
     :param TreeItem: TreeItem to be inserted
     :return: True if succeeded, False if not succeeded
     >>> t = TwoThreeFourTree()
     >>> t.twoThreeFourTreeInsert(TreeItem("Test", 5))
     True
     >>> t.twoThreeFourTreeInsert(TreeItem("Test 2", 7))
     True
     >>> t.twoThreeFourTreeInsert(TreeItem("Test 2", 9))
     True
     >>> t.twoThreeFourTreeInsert(TreeItem("Test 2", 11))
     True
     >>> t.right.root.retrieve(1)[0].getKey()
     11
     """
     isLeaf = self.left is None and self.leftmid is None and self.rightmid is None and self.right is None
     if self.root.getLength() < 3:  # Node is 2-node or 3-node
         if isLeaf:  #Node is a leaf
             return self.__nodeInsert(TreeItem)
         else:  #Node is not a leaf
             if self.root.getLength(
             ) == 1:  #Node is 2-node, find child Tree to insert TreeItem
                 if self.root.retrieve(0)[0].getKey() < TreeItem.getKey():
                     return self.right.twoThreeFourTreeInsert(TreeItem)
                 elif self.root.retrieve(0)[0].getKey() > TreeItem.getKey():
                     return self.left.twoThreeFourTreeInsert(TreeItem)
                 else:
                     return False
             elif self.root.getLength(
             ) == 2:  #Node is 3-node, find child Tree to insert TreeItem
                 if self.root.retrieve(0)[0].getKey() < TreeItem.getKey():
                     if self.root.retrieve(
                             1)[0].getKey() < TreeItem.getKey():
                         return self.right.twoThreeFourTreeInsert(TreeItem)
                     else:
                         return self.leftmid.twoThreeFourTreeInsert(
                             TreeItem)
                 else:
                     return self.left.twoThreeFourTreeInsert(TreeItem)
     else:  # Node is 4-node
         self.__split()
         if self.parent is None:  #Insert for root
             return self.twoThreeFourTreeInsert(TreeItem)
         else:  #Insert for internal node, insert in parent (if parent is a 4-node use custom algorithm because parent does not have to be split)
             if self.parent.root.getLength() < 3:
                 return self.parent.twoThreeFourTreeInsert(TreeItem)
             else:
                 if self.parent.root.retrieve(
                         0)[0].getKey() < TreeItem.getKey():
                     if self.parent.root.retrieve(
                             1)[0].getKey() < TreeItem.getKey():
                         return self.parent.right.twoThreeFourTreeInsert(
                             TreeItem)
                     else:
                         return self.parent.leftmid.twoThreeFourTreeInsert(
                             TreeItem)
                 else:
                     return self.parent.left.twoThreeFourTreeInsert(
                         TreeItem)
Ejemplo n.º 27
0
	def listPrepare(self):
		str_path = self.path
		entryItem = TreeItem(str_path, self.typePath, self.rootItem, first = True)
		entryItem.checkState = QtCore.Qt.Checked
		self.rootItem.appendChild(entryItem)
		self._proceed_dir(str_path, entryItem)
Ejemplo n.º 28
0
	def treeSharedDataToXML(self, obj, prefix = '', tab = '\t'):
		_str = obj.data(1)
		_name = obj.data(0)
		node = self.doc.createElement(_str)
		node.setAttribute('name', QtCore.QString(_name).toUtf8().data())
		node.setAttribute('size', ' dir')
		#print tab, prefix, unicode(_name), 'parent'
		i = 0
		while i < obj.childCount() :
			item = obj.child(i)
			str_ = item.data(1)
			name_ = item.data(0)
			if hasattr(item, 'Root') : name_ = os.path.join(item.Root, name_)
			if item.checkState == QtCore.Qt.Checked :
				#print tab, str_, prefix + unicode(_name), unicode(name_), 'check'
				path_ = os.path.join(unicode(prefix) + unicode(_name), unicode(name_))
				#print QtCore.QString(path_).toUtf8().data(), ' path_'
				if os.path.isfile(path_) :
					#print 'path exist & file'
					elem = self.doc.createElement(str_)
					if hasattr(item, 'Root') : name_ = name_.split(os.path.join(item.Root, ''))[1]
					elem.setAttribute('name', QtCore.QString(name_).toUtf8().data())
					elem.setAttribute('size', str(os.path.getsize(path_)) + ' Byte(s)' + ' file')
				elif os.path.isdir(path_) :
					#print 'path exist & dir'
					if _name == 'Name' :
						prefix_ = ''
					else :
						prefix_ = prefix + _name + self.SEP
					listChild = []
					try:
						listChild = os.listdir(path_)
					except OSError :
						print 'OSerror_1'
						pass
					#print listChild, 'listChild'
					for _path in listChild :
						if not os.path.isdir(os.path.join(path_,_path)) :
							""" во избежание дублирования только для не_каталогов,
								потому что каталоги все и так представлены в дереве
							"""
							str__ = 'file'
							new_item = TreeItem(_path, str__, item)
							new_item.checkState = QtCore.Qt.Checked
							item.appendChild(new_item)
					if hasattr(item, 'Root') : prefix_ = os.path.join(item.Root, '')
					if len(listChild) > 0 :
						elem = self.treeSharedDataToXML(item, prefix_, tab = tab + '\t')
					else :
						""" not create the node for empty directory """
						i += 1
						continue
				else :
					#print 'path exist & no regular'
					elem = self.doc.createElement(str_)
					elem.setAttribute('name', QtCore.QString(name_).toUtf8().data())
					elem.setAttribute('size', 'no_regular_file')
			elif item.checkState == QtCore.Qt.PartiallyChecked and item.childCount() > 0 :
				""" for parsing PartiallyChecked directory, not for all """
				if _name == 'Name' :
					prefix_ = ''
				else :
					prefix_ = prefix + _name + self.SEP
				#print tab, str_, prefix, name_, 'pref'
				elem = self.treeSharedDataToXML(item, prefix_, tab = tab + '\t')
			else :
				i += 1
				continue
			if hasattr(item, 'Root') : elem.setAttribute('xRoot', item.Root)
			node.appendChild(elem)
			i += 1

		return node
Ejemplo n.º 29
0
def readFile():
    file = open("input.txt", "r")       # opens file
    command = file.readline()
    if "type" in command:
        if "bst" in command:        # creates BSTree
            b = BinarySearchTree()
            command = file.readline()
            while command is not None:
                if len(command.strip()) == 0:
                    break
                elif "insert" in command:       # inserts in BSTree
                    number = int(command.split()[1])
                    b.searchTreeInsert(TreeItem(str(number), number))
                    command = file.readline()
                elif "delete" in command:       # deletes in BSTree
                    number = int(command.split()[1])
                    b.searchTreeDelete(number)
                    command = file.readline()
                elif "print" in command:        # gives DOT-language of BSTree
                    createDotFileBST(b)
                    command = file.readline()
        elif "234" in command:      # creates 234-Tree
            t = TwoThreeFourTree()
            command = file.readline()
            while command is not None:
                if len(command.strip()) == 0:
                    break
                elif "insert" in command:       # inserts in 234-Tree
                    number = int(command.split()[1])
                    t.twoThreeFourTreeInsert(TreeItem(str(number), number))
                    command = file.readline()
                elif "delete" in command:       # deletes in 234-Tree
                    number = int(command.split()[1])
                    t.twoThreeFourTreeDelete(number)
                    command = file.readline()
                elif "print" in command:        # gives DOT-language of 234-Tree
                    createDotFileTTFT(t)
                    command = file.readline()
        elif "ll" in command:       # creates circular linked list
            l = CircularLinkedList()
            command = file.readline()
            while command is not None:
                if len(command.strip()) == 0:
                    break
                elif "insert" in command:       # inserts in circular linked list
                    index = int(command.split()[1])
                    number = int(command.split()[2])
                    l.insert(index, number)
                    command = file.readline()
                elif "delete" in command:       # deletes in circular linked list
                    index = int(command.split()[1])
                    l.delete(index)
                    command = file.readline()
                elif "print" in command:        # gives DOT-language of circular linked list
                    createDotFileLL(l)
                    command = file.readline()
        elif "stack" in command:    # creates stack
            s = Stack()
            command = file.readline()
            while command is not None:
                if len(command.strip()) == 0:
                    break
                elif "push" in command:         # pushes on stack
                    number = int(command.split()[1])
                    s.push(number)
                    command = file.readline()
                elif "pop" in command:          # pops from stack
                    s.pop()
                    command = file.readline()
                elif "print" in command:        # gives DOT-language of stack
                    createDotFileS(s)
                    command = file.readline()
Ejemplo n.º 30
0
 def Delete(self):
     self.UnRegisterEvent(self.name)
     TreeItem.Delete(self)
Ejemplo n.º 31
0
class TreeModel(QtCore.QAbstractItemModel):
	checkStateChanged = QtCore.pyqtSignal()
	def __init__(self, section1Name, section2Name, parent = None):
		QtCore.QAbstractItemModel.__init__(self, parent)

		self.rootItem = TreeItem(section1Name, section2Name, None, self)
		self.changeMe = True

	def index(self, row, column, prnt = QtCore.QModelIndex()):
		if (not self.hasIndex(row, column, prnt)) :
			return QtCore.QModelIndex()

		parentItem = self.rootItem;
		if prnt.isValid():
			parentItem = prnt.internalPointer()
			#print "=====> %s\t-\t%s" % (parentItem, parentItem.data(0))

		childItem = parentItem.child(row)
		if ( childItem is not None) :
			return self.createIndex(row, column, childItem)

		return QtCore.QModelIndex()

	def parent(self, child = QtCore.QModelIndex()):
		if ( not child.isValid() ) :
			return QtCore.QModelIndex()

		childItem = child.internalPointer()
		#print "--> %s" % type(childItem)
		if childItem is None:
			return QtCore.QModelIndex()

		parentItem = childItem.getParentItem()
		if ( parentItem is None or parentItem == self.rootItem ) :
			return QtCore.QModelIndex()

		return self.createIndex(parentItem.row(), 0, parentItem)

	def rowCount(self, parent = QtCore.QModelIndex()):
		if ( parent.column() > 0 ):
			return 0

		if ( not parent.isValid() ) :
			item = self.rootItem
		else :
			item = parent.internalPointer()

		return item.childCount()

	def columnCount(self, parent = QtCore.QModelIndex()):
		#if parent.isValid() :
		#	return parent.internalPointer().columnCount()
		#else :
		#	return self.rootItem.columnCount()
		return 2

	def data(self, index_, role):
		if (not index_.isValid()) :
			return QtCore.QVariant()

		item = index_.internalPointer()
		if role == QtCore.Qt.CheckStateRole :
				return item.data(index_.column(), role)
		elif (role != QtCore.Qt.DisplayRole and role != QtCore.Qt.DecorationRole) :
			return QtCore.QVariant()
		return item.data(index_.column(), role)

	def headerData(self, section, orientation = QtCore.Qt.Horizontal, role = QtCore.Qt.DisplayRole):
		if (orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole) :
			return self.rootItem.data(section)
		return QtCore.QVariant()

	def processCheckStateOfChildren(self, b):
		qua = b.childCount()
		checkState = b.checkState
		for i in range(0, qua):
			childItem = b.child(i)
			childItem.checkState = checkState
			self.processCheckStateOfChildren(childItem)

	def processCheckStateOfParents(self, b):
		parentItem = b.getParentItem()
		if parentItem is not None :
			qua = parentItem.childCount()
		else :
			return

		quaOfChecked = 0
		quaOfPartChecked = 0
		for i in range(0, qua) :
			if parentItem.child(i).checkState == QtCore.Qt.Checked :
				quaOfChecked += 1
			elif parentItem.child(i).checkState == QtCore.Qt.PartiallyChecked :
				quaOfPartChecked += 1

			if quaOfChecked == qua :
				checkState = QtCore.Qt.Checked
			elif quaOfChecked == 0 and quaOfPartChecked == 0 :
				checkState = QtCore.Qt.Unchecked
			else :
				checkState = QtCore.Qt.PartiallyChecked

			parentItem.checkState = checkState
			self.processCheckStateOfParents(parentItem)

	def setData(self, index_, value, role = QtCore.Qt.DisplayRole):
		if not index_.isValid() :
			return False

		if role == QtCore.Qt.CheckStateRole :
			item = index_.internalPointer()

			if item.checkState == QtCore.Qt.Unchecked :
				item.checkState = QtCore.Qt.Checked
			else :
				item.checkState = QtCore.Qt.Unchecked

			if self.changeMe and item is not None:
				self.changeMe = False
				self.processCheckStateOfChildren(item)
				self.processCheckStateOfParents(item)
				self.changeMe = True

			self.emit(QtCore.SIGNAL("checkStateChanged()"))
			self.emit(QtCore.SIGNAL("dataChanged(const QModelIndex&, const QModelIndex&)"), \
													index_.parent().parent(), index_.parent())
			return True

		return False

	def flags(self, index_):
		if not index_.isValid() :
			return QtCore.Qt.ItemIsEnabled

		return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | QtCore.Qt.ItemIsUserCheckable
Ejemplo n.º 32
0
 def __init__(self, parent, node):
     TreeItem.__init__(self, parent, node)
     self.RegisterEvent(self.name)
Ejemplo n.º 33
0
 def __init__(self, parent, node):
     TreeItem.__init__(self, parent, node)
     self.RegisterEvent(self.name)
Ejemplo n.º 34
0
 def _Delete(self):
     for child in self.childs[:]:
         child._Delete()
     TreeItem._Delete(self)
Ejemplo n.º 35
0
 def RenameTo(self, newName):
     self.UnRegisterEvent(self.name)
     TreeItem.RenameTo(self, newName)
     self.RegisterEvent(newName)
Ejemplo n.º 36
0
 def tableInsert(self, order):
     return self.ttft.twoThreeFourTreeInsert(
         TreeItem(order, order.getTimestamp()))
Ejemplo n.º 37
0
 def __init__(self, data, parent=None):
     super().__init__(parent)
     
     self.rootItem = TreeItem(("Title", "Summary"))
     self.setupModelData(data.split('\n'), self.rootItem)
Ejemplo n.º 38
0
 def Delete(self):
     for child in self.childs[:]:
         child.Delete()
     TreeItem.Delete(self)