def fill_item(self, item, value): item.setExpanded(True) if type(value) is OrderedDict: for key, val in sorted(value.items()): if type(val) is unicode: if '@xmlns' not in key: # hack child = QTreeWidgetItem() text = unicode(key + " '" + val + "'") child.setTextColor(0, self.getQColor(text)) child.setText(0, text) item.addChild(child) else: child = QTreeWidgetItem() text = unicode(key) #child.setTextColor(0, self.getQColor(text)) child.setText(0, text) item.addChild(child) self.fill_item(child, val) elif type(value) is list: for val in value: child = QTreeWidgetItem() item.addChild(child) if type(val) is OrderedDict: child.setText(0, '[' + str(value.index(val)) +']') self.fill_item(child, val) elif type(val) is list: child.setText(0, '[' + str(value.index(val)) +']') self.fill_item(child, val) else: child.setText(0, unicode(val)) child.setExpanded(True) else: child = QTreeWidgetItem() child.setText(0, str(value)) item.addChild(child)
def fill_item(self, item, value): item.setExpanded(True) if type(value) is OrderedDict: for key, val in sorted(value.items()): if type(val) is unicode: if '@xmlns' not in key: # hack child = QTreeWidgetItem() text = unicode(key + " '" + val + "'") child.setTextColor(0, self.getQColor(text)) child.setText(0, text) item.addChild(child) else: child = QTreeWidgetItem() text = unicode(key) #child.setTextColor(0, self.getQColor(text)) child.setText(0, text) item.addChild(child) self.fill_item(child, val) elif type(value) is list: for val in value: child = QTreeWidgetItem() item.addChild(child) if type(val) is OrderedDict: child.setText(0, '[' + str(value.index(val)) + ']') self.fill_item(child, val) elif type(val) is list: child.setText(0, '[' + str(value.index(val)) + ']') self.fill_item(child, val) else: child.setText(0, unicode(val)) child.setExpanded(True) else: child = QTreeWidgetItem() child.setText(0, str(value)) item.addChild(child)
def set_root_folder(self, root_folder): self.tree.clear() self.clear_all_load_animations() if self.root_folder != None: del self.root_folder self.root_folder = root_folder # Add root columns = QStringList() columns.append(root_folder.get_name()) columns.append(root_folder.get_size()) root_item = QTreeWidgetItem(columns) self.set_icon(root_folder.mime_type, root_item) self.tree.addTopLevelItem(root_item) root_item.setExpanded(True) root_folder.tree_item = root_item self.generate_children(root_folder) self.add_loading_widgets(root_folder) self.tree.setCurrentItem(root_item) self.start_load_anim(root_folder) self.tree.header().resizeSections(QHeaderView.ResizeToContents)
def __init__(self, featureDict, selectedFeatures=None, parent=None): QDialog.__init__(self, parent) self.featureDict = featureDict if selectedFeatures is None or len(selectedFeatures) == 0: selectedFeatures = defaultdict(list) self.selectedFeatures = selectedFeatures self.setWindowTitle("Object Features") ui_class, widget_class = uic.loadUiType(os.path.split(__file__)[0] + "/featureSelection.ui") self.ui = ui_class() self.ui.setupUi(self) self.ui.buttonBox.accepted.connect(self.accept) self.ui.buttonBox.rejected.connect(self.reject) self.ui.allButton.pressed.connect(self.handleAll) self.ui.noneButton.pressed.connect(self.handleNone) self.ui.treeWidget.setColumnCount(1) for pluginName, features in featureDict.iteritems(): parent = QTreeWidgetItem(self.ui.treeWidget) parent.setText(0, pluginName) parent.setExpanded(True) for name in sorted(features): item = QTreeWidgetItem(parent) item.setText(0, name) item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) if pluginName in self.selectedFeatures: if name in self.selectedFeatures[pluginName]: item.setCheckState(0, Qt.Checked) else: item.setCheckState(0, Qt.Unchecked)
def _loadCardGroup(self, groupName, records, parent=None): if (not groupName): groupName = 'None' cards = self.cardWidget() factory = self.factory() # create the group item group_item = QTreeWidgetItem(parent, [groupName]) font = group_item.font(0) font.setBold(True) font.setPointSize(font.pointSize() + 2) group_item.setFont(0, font) group_item.setFlags(Qt.ItemIsEnabled) # load sub-groups if (type(records) == dict): for subgroup, records in sorted(records.items()): self._loadCardGroup(subgroup, records, group_item) else: for record in records: widget = factory.createCard(cards, record) if (not widget): continue widget.adjustSize() # create the card item item = QTreeWidgetItem(group_item) item.setSizeHint(0, QSize(0, widget.height())) cards.setItemWidget(item, 0, widget) group_item.setExpanded(True)
def buildParentItem(self, dcollection, title, rootresource): ''' Builds tree widget items from a dictionary. ''' rtItem = QTreeWidgetItem() rtItem.setText(0, title) rtItem.setIcon(0, QIcon(rootresource)) topLevelItems = [] for k, v in dcollection.iteritems(): parentItem = QTreeWidgetItem() if isinstance(v, dict): parentItem.setText(0, k) for kc, vc in v.iteritems(): child = QTreeWidgetItem() child.setText(0, self._combine(kc, vc)) parentItem.addChild(child) else: parentItem.setText(0, self._combine(k, v)) topLevelItems.append(parentItem) rtItem.addChildren(topLevelItems) rtItem.setExpanded(True) return rtItem
def addRecentAlgorithms(self, updating): showRecent = ProcessingConfig.getSetting( ProcessingConfig.SHOW_RECENT_ALGORITHMS) if showRecent: recent = ProcessingLog.getRecentAlgorithms() if len(recent) != 0: found = False if updating: recentItem = self.algorithmTree.topLevelItem(0) treeWidget = recentItem.treeWidget() treeWidget.takeTopLevelItem( treeWidget.indexOfTopLevelItem(recentItem)) recentItem = QTreeWidgetItem() recentItem.setText(0, self.tr('Recently used algorithms')) for algname in recent: alg = Processing.getAlgorithm(algname) if alg is not None: algItem = TreeAlgorithmItem(alg) recentItem.addChild(algItem) found = True if found: self.algorithmTree.insertTopLevelItem(0, recentItem) recentItem.setExpanded(True) self.algorithmTree.setWordWrap(True)
def addParent(self, parent, column, title, data, status): item = QTreeWidgetItem(parent, [title]) item.setData(column, Qt.UserRole, data) item.setChildIndicatorPolicy(QTreeWidgetItem.ShowIndicator) item.setCheckState (column, self.getCheckStatus(status)) item.setExpanded (False) return item
def createTreeItem(self, parent, text, uuid=""): """ Creates tree items parent: parent item text: item text uuid: complex uuid """ count = parent.childCount() children = [] #making a list of item names for i in range(count): child = parent.child(i) children.append(child.text(0)) #checking if the text is already in the tree widget if text not in children: #case not it should be created item = QTreeWidgetItem(parent) item.setExpanded(True) item.setText(0, text) #adding the complex uuid to the tree widget if uuid != "": item.setText(1, str(uuid)) else: #case already exists the correspondind item should be returned for i in range(count): child = parent.child(i) if child.text(0) == text: item = child return item
def createTreeItem(self, parent, text, uuid = ""): """ Creates tree items parent: parent item text: item text uuid: complex uuid """ count = parent.childCount() children = [] #making a list of item names for i in range(count): child = parent.child(i) children.append(child.text(0)) #checking if the text is already in the tree widget if text not in children: #case not it should be created item = QTreeWidgetItem(parent) item.setExpanded(True) item.setText(0,text) #adding the complex uuid to the tree widget if uuid != "": item.setText(1, str(uuid)) else: #case already exists the correspondind item should be returned for i in range(count): child = parent.child(i) if child.text(0) == text: item = child return item
def __init__(self, parent=None): """ Constructor """ QDialog.__init__(self, parent) self.setupUi(self) self.parent = parent self.pxSchedTbl = parent.pxCurSelGaInOsObj self.setWindowTitle("Configure Schedule Table <%s>" % (self.pxSchedTbl.xScheduleTableName)) self.vDisableAllTab() self.pxCurSelEp = None self.pxCurSelEpSubIndex = -1 self.pxCurSelTreeItem = None #根据table 刷新界面树,初始化 index = 0 for ep in self.pxSchedTbl.xSchedTblEpList: defaultName = QString('Expiry Point %s(%s)' % (index, ep[0])) pxTreeIlem = QTreeWidgetItem(self.trSchedTable, QStringList(defaultName)) self.trSchedTable.addTopLevelItem(pxTreeIlem) index += 1 for epsub in ep[1]: defaultName = QString(epsub) pxTreeIlem2 = QTreeWidgetItem(None, QStringList(defaultName)) pxTreeIlem.addChild(pxTreeIlem2) pxTreeIlem.setExpanded(True) #刷新基本控件 self.cbxSchedTblRepeatable.setChecked( self.pxSchedTbl.xSchedTblRepeatable) self.cbxSchedTblAutostartable.setChecked( self.pxSchedTbl.xSchedTblAutostartable) self.cmbxSchedTblAutoStartType.setCurrentIndex( self.vDoGetAutostartType()) self.cmbxSchedTblSyncStrategy.setCurrentIndex( self.vDoGetSyncStrategy()) self.spbxSchedTblAbsRel.setValue(self.pxSchedTbl.xSchedTblAbsRelValue) self.spbxSchedTblFinalDelay.setValue( self.pxSchedTbl.xSchedTblFinalDelay) self.spbxSchedTblMaxAdvance.setValue( self.pxSchedTbl.xSchedTblMaxAdvance) self.spbxSchedTblMaxRetard.setValue(self.pxSchedTbl.xSchedTblMaxRetard) self.spbxSchedTblPrecision.setValue( self.pxSchedTbl.xSchedTblExplicitPrecision) index = -1 i = 0 for cnt in self.parent.pxGaInOSCounterCfgList: name = cnt.xCounterName self.cmbxSchedTblDrivingCounter.addItem(name) if (self.pxSchedTbl.xSchedTblDrivingCounter == name): index = i i += 1 #模拟一次点击刷新控件 self.on_cbxSchedTblAutostartable_clicked( self.pxSchedTbl.xSchedTblAutostartable) #初始化控件 self.btnAdd.setText("Add Expiry Point") self.btnAdd.setDisabled(False) self.btnInsert.setDisabled(True) self.btnDelete.setDisabled(True)
def fill_item(item, value): item.setExpanded(True) if type(value) is dict: for key, val in sorted(value.iteritems()): child = QTreeWidgetItem() child.setText(0, unicode(key)) item.addChild(child) fill_item(child, val) elif type(value) is list: for val in value: child = QTreeWidgetItem() item.addChild(child) if type(val) is dict: child.setText(0, '[dict]') fill_item(child, val) elif type(val) is list: child.setText(0, '[list]') fill_item(child, val) else: child.setText(0, unicode(val)) child.setExpanded(True) else: child = QTreeWidgetItem() child.setText(0, unicode(value)) item.addChild(child)
class LoadThings(QUndoCommand): def __init__(self, widget, thing): super(LoadThings, self).__init__() self.widget = widget self.createdThing = thing self.item = QTreeWidgetItem() self.item.setText(0, thing.name) typeName = type(thing).__name__ for i in range(self.widget.ui.treeWidget.topLevelItemCount()): group = self.widget.ui.treeWidget.topLevelItem(i) if group.text(0) == typeName: self.group = group break else: # group not found self.group = QTreeWidgetItem() self.group.setText(0, typeName) def redo(self): if self.widget.ui.treeWidget.indexOfTopLevelItem(self.group) == -1: self.widget.ui.treeWidget.addTopLevelItem(self.group) self.group.addChild(self.item) self.group.setExpanded(True) self.widget.ui.treeWidget.setCurrentItem(self.item) def undo(self): self.group.takeChild(self.group.childCount()-1) if self.group.childCount() == 0: parentIndex = self.widget.ui.treeWidget.indexOfTopLevelItem(self.group) self.widget.ui.treeWidget.takeTopLevelItem(parentIndex)
def _loadCardGroup( self, groupName, records, parent = None ): if ( not groupName ): groupName = 'None' cards = self.cardWidget() factory = self.factory() # create the group item group_item = QTreeWidgetItem(parent, [groupName]) font = group_item.font(0) font.setBold(True) font.setPointSize(font.pointSize() + 2) group_item.setFont(0, font) group_item.setFlags(Qt.ItemIsEnabled) # load sub-groups if ( type(records) == dict ): for subgroup, records in sorted(records.items()): self._loadCardGroup(subgroup, records, group_item) else: for record in records: widget = factory.createCard(cards, record) if ( not widget ): continue widget.adjustSize() # create the card item item = QTreeWidgetItem(group_item) item.setSizeHint(0, QSize(0, widget.height())) cards.setItemWidget(item, 0, widget) group_item.setExpanded(True)
def insertClusterItem(self, tree, text): """ Creates an item for the tree widget for a specific parent item and a specific text (cluster name) """ parent = tree.invisibleRootItem() item = QTreeWidgetItem(parent) item.setExpanded(True) item.setText(0,text)
def __init__(self, parent=None): QTreeWidget.__init__(self, parent) self.setWindowTitle('TreeWidget Context Menu') self.header().setHidden(True) self.setGeometry(320, 320, 320, 320) for index in '12345': parent = QTreeWidgetItem(self, ['Parent %s' % index]) for item in 'ABCDE': QTreeWidgetItem(parent, ['Child %s%s' % (index, item)]) parent.setExpanded(True)
def reloadGui(self): tree=self.trSchedTable.topLevelItem(0); for tbl in self.cfg.table: item=QTreeWidgetItem(tree,QStringList('Expiry Point(offset = %s)'%(tbl.offset))); tree.addChild(item); for action in tbl.actionList: item2=QTreeWidgetItem(item,QStringList(action)); item.addChild(item2); item.setExpanded(True) tree.setExpanded(True)
def recusive_add_group(self, parentTreeWidgetItem, pwGroup): treeWidgetItem = QTreeWidgetItem(parentTreeWidgetItem) treeWidgetItem.setText(0, pwGroup.Name) treeWidgetItem.setData(1, Qt.UserRole, pwGroup) for childGroup in pwGroup.Groups: self.recusive_add_group(treeWidgetItem, childGroup) treeWidgetItem.setExpanded(True) return treeWidgetItem
def reloadGui(self): tree = self.trSchedTable.topLevelItem(0) for tbl in self.cfg.table: item = QTreeWidgetItem( tree, QStringList('Expiry Point(offset = %s)' % (tbl.offset))) tree.addChild(item) for action in tbl.actionList: item2 = QTreeWidgetItem(item, QStringList(action)) item.addChild(item2) item.setExpanded(True) tree.setExpanded(True)
def fillInputsTree(self): icon = QIcon(os.path.join(pluginPath, 'images', 'input.png')) parametersItem = QTreeWidgetItem() parametersItem.setText(0, self.tr('Parameters')) for paramType in ModelerParameterDefinitionDialog.paramTypes: paramItem = QTreeWidgetItem() paramItem.setText(0, paramType) paramItem.setIcon(0, icon) paramItem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled) parametersItem.addChild(paramItem) self.inputsTree.addTopLevelItem(parametersItem) parametersItem.setExpanded(True)
def populate_classified_values(self, unassigned_values, assigned_values, default_classes): """Populate lstUniqueValues and treeClasses.from the parameters. :param unassigned_values: List of values that haven't been assigned to a class. It will be put in self.lstUniqueValues. :type unassigned_values: list :param assigned_values: Dictionary with class as the key and list of value as the value of the dictionary. It will be put in self.treeClasses. :type assigned_values: dict :param default_classes: Default classes from unit. :type default_classes: list """ # Populate the unique values list self.lstUniqueValues.clear() self.lstUniqueValues.setSelectionMode( QAbstractItemView.ExtendedSelection) for value in unassigned_values: value_as_string = value is not None and unicode(value) or 'NULL' list_item = QListWidgetItem(self.lstUniqueValues) list_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled) list_item.setData(Qt.UserRole, value) list_item.setText(value_as_string) self.lstUniqueValues.addItem(list_item) # Populate assigned values tree self.treeClasses.clear() self.treeClasses.invisibleRootItem().setFlags(Qt.ItemIsEnabled) for default_class in default_classes: # Create branch for class tree_branch = QTreeWidgetItem(self.treeClasses) tree_branch.setFlags(Qt.ItemIsDropEnabled | Qt.ItemIsEnabled) tree_branch.setExpanded(True) tree_branch.setFont(0, bold_font) if 'name' in default_class: default_class_name = default_class['name'] else: default_class_name = default_class['key'] tree_branch.setText(0, default_class_name) tree_branch.setData(0, Qt.UserRole, default_class['key']) if 'description' in default_class: tree_branch.setToolTip(0, default_class['description']) # Assign known values for value in assigned_values[default_class['key']]: string_value = value is not None and unicode(value) or 'NULL' tree_leaf = QTreeWidgetItem(tree_branch) tree_leaf.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled) tree_leaf.setData(0, Qt.UserRole, value) tree_leaf.setText(0, string_value)
def _load_project(self, folderStructure, folder): if not folder: return name = file_manager.get_basename(folder) item = QTreeWidgetItem(self._tree) item.setText(0, name) item.setToolTip(0, folder) item.setIcon(0, QIcon(resources.IMAGES['tree-folder'])) if folderStructure[folder][1] is not None: folderStructure[folder][1].sort() self._load_folder(folderStructure, folder, item) item.setExpanded(True) self._root = item
def __init__(self, parent = None): """ Constructor """ QDialog.__init__(self, parent) self.setupUi(self); self.parent=parent; self.pxSchedTbl=parent.pxCurSelGaInOsObj; self.setWindowTitle("Configure Schedule Table <%s>"%(self.pxSchedTbl.xScheduleTableName)); self.vDisableAllTab(); self.pxCurSelEp=None; self.pxCurSelEpSubIndex=-1; self.pxCurSelTreeItem=None; #根据table 刷新界面树,初始化 index=0; for ep in self.pxSchedTbl.xSchedTblEpList: defaultName=QString('Expiry Point %s(%s)'%(index, ep[0])); pxTreeIlem=QTreeWidgetItem(self.trSchedTable,QStringList(defaultName)); self.trSchedTable.addTopLevelItem(pxTreeIlem); index+=1; for epsub in ep[1]: defaultName=QString(epsub); pxTreeIlem2=QTreeWidgetItem(None,QStringList(defaultName)); pxTreeIlem.addChild(pxTreeIlem2); pxTreeIlem.setExpanded(True); #刷新基本控件 self.cbxSchedTblRepeatable.setChecked(self.pxSchedTbl.xSchedTblRepeatable); self.cbxSchedTblAutostartable.setChecked(self.pxSchedTbl.xSchedTblAutostartable); self.cmbxSchedTblAutoStartType.setCurrentIndex(self.vDoGetAutostartType()); self.cmbxSchedTblSyncStrategy.setCurrentIndex(self.vDoGetSyncStrategy()); self.spbxSchedTblAbsRel.setValue(self.pxSchedTbl.xSchedTblAbsRelValue); self.spbxSchedTblFinalDelay.setValue(self.pxSchedTbl.xSchedTblFinalDelay); self.spbxSchedTblMaxAdvance.setValue(self.pxSchedTbl.xSchedTblMaxAdvance); self.spbxSchedTblMaxRetard.setValue(self.pxSchedTbl.xSchedTblMaxRetard); self.spbxSchedTblPrecision.setValue(self.pxSchedTbl.xSchedTblExplicitPrecision); index=-1; i=0; for cnt in self.parent.pxGaInOSCounterCfgList: name=cnt.xCounterName; self.cmbxSchedTblDrivingCounter.addItem(name); if(self.pxSchedTbl.xSchedTblDrivingCounter==name): index=i; i+=1; #模拟一次点击刷新控件 self.on_cbxSchedTblAutostartable_clicked(self.pxSchedTbl.xSchedTblAutostartable); #初始化控件 self.btnAdd.setText("Add Expiry Point"); self.btnAdd.setDisabled(False); self.btnInsert.setDisabled(True); self.btnDelete.setDisabled(True);
def treeMenuSetupRecur(self, curStruct, parent=None): item = QTreeWidgetItem(parent) item.setText(0, curStruct["text"]) if "flags" in curStruct: item.setFlags(curStruct["flags"]) if "children" in curStruct: children = [] for child in curStruct["children"]: children.append(self.treeMenuSetupRecur(child, item)) item.addChildren(children) if "expanded" in curStruct: print(curStruct["expanded"]) item.setExpanded(curStruct["expanded"]) print(item.isExpanded()) return item
def populate(self): self.ui.treeWidget.setColumnCount(1) for pluginName, features in self.featureDict.iteritems(): if pluginName == "TestFeatures" and not ilastik_config.getboolean( "ilastik", "debug"): continue parent = QTreeWidgetItem(self.ui.treeWidget) parent.setText(0, pluginName) parent.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) # hack to ensure checkboxes visible parent.setCheckState(0, Qt.Checked) parent.setCheckState(0, Qt.Unchecked) parent.setExpanded(False) self.countChecked[pluginName] = 0 self.countAll[pluginName] = len(self.featureDict[pluginName]) advanced_names = [] simple_names = [] for name in sorted(features.keys()): parameters = features[name] if 'advanced' in parameters: advanced_names.append(name) else: simple_names.append(name) for name in simple_names + advanced_names: parameters = features[name] item = QTreeWidgetItem(parent) item.setText(0, name) item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) if 'tooltip' in parameters: item.setToolTip(0, parameters['tooltip']) # hack to ensure checkboxes visible item.setCheckState(0, Qt.Checked) item.setCheckState(0, Qt.Unchecked) if pluginName in self.selectedFeatures: if name in self.selectedFeatures[pluginName]: item.setCheckState(0, Qt.Checked) self.countChecked[pluginName] += 1 if self.countChecked[pluginName] == 0: parent.setCheckState(0, Qt.Unchecked) elif self.countChecked[pluginName] == self.countAll[pluginName]: parent.setCheckState(0, Qt.Checked) else: parent.setCheckState(0, Qt.PartiallyChecked) self.updateToolTip(parent) # facilitates switching of the CheckBox when clicking on the Text of a QTreeWidgetItem self.ui.treeWidget.setCurrentItem(None)
def populate(self): self.ui.treeWidget.setColumnCount(1) for pluginName, features in self.featureDict.iteritems(): if pluginName=="TestFeatures" and not ilastik_config.getboolean("ilastik", "debug"): continue parent = QTreeWidgetItem(self.ui.treeWidget) parent.setText(0, pluginName) parent.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) # hack to ensure checkboxes visible parent.setCheckState(0, Qt.Checked) parent.setCheckState(0, Qt.Unchecked) parent.setExpanded(False) self.countChecked[pluginName]=0 self.countAll[pluginName]=len(self.featureDict[pluginName]) advanced_names = [] simple_names = [] for name in sorted(features.keys()): parameters = features[name] if 'advanced' in parameters: advanced_names.append(name) else: simple_names.append(name) for name in simple_names+advanced_names: parameters = features[name] item = QTreeWidgetItem(parent) item.setText(0, name) item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) if 'tooltip' in parameters: item.setToolTip(0, parameters['tooltip']) # hack to ensure checkboxes visible item.setCheckState(0, Qt.Checked) item.setCheckState(0, Qt.Unchecked) if pluginName in self.selectedFeatures: if name in self.selectedFeatures[pluginName]: item.setCheckState(0, Qt.Checked) self.countChecked[pluginName]+=1 if self.countChecked[pluginName] == 0: parent.setCheckState(0, Qt.Unchecked) elif self.countChecked[pluginName] == self.countAll[pluginName]: parent.setCheckState(0, Qt.Checked) else: parent.setCheckState(0, Qt.PartiallyChecked) self.updateToolTip(parent) # facilitates switching of the CheckBox when clicking on the Text of a QTreeWidgetItem self.ui.treeWidget.setCurrentItem(None)
def loaddata(self, data): ''' load data for index tree. data is list of TableEntry(define in pychmfile.py ''' if self.dataloaded: return if data == None: return self.dataloaded = True self.tree.clear() lastchild = [] rootentry = [] for i in xrange(len(data)): indent = data[i].indent if indent >= len(rootentry): maxindent = len(rootentry) - 1 lastchild.append(None) rootentry.append(None) if indent > 0 and maxindent < 0: print 'error, first entry isn\'t the root entry' if (indent - maxindent) > 1: j = maxindent while j < indent: if len(lastchild) <= j + 1: lastchild.append(None) rootentry.append(None) lastchild[j + 1] = lastchild[j] rootentry[j + 1] = rootentry[j] j += 1 lastchild[indent] = None rootentry[indent] = None if indent == 0: item = QTreeWidgetItem(self.tree, lastchild[indent]) item.entry = data[i] item.setText(0, data[i].key) else: if rootentry[indent - 1] == None: print 'error no root entry' item = QTreeWidgetItem(rootentry[indent - 1], lastchild[indent]) item.entry = data[i] item.setText(0, data[i].key) item.setExpanded(True) lastchild[indent] = item rootentry[indent] = item self.tree.update()
def fillAlgorithmTreeUsingProviders(self): self.algorithmTree.clear() text = unicode(self.searchBox.text()) allAlgs = ModelerUtils.allAlgs for providerName in allAlgs.keys(): name = 'ACTIVATE_' + providerName.upper().replace(' ', '_') if not ProcessingConfig.getSetting(name): continue groups = {} provider = allAlgs[providerName] algs = provider.values() # Add algorithms for alg in algs: if not alg.showInModeler or alg.allowOnlyOpenedLayers: continue if alg.commandLineName() == self.alg.commandLineName(): continue if text == '' or text.lower() in alg.name.lower(): if alg.group in groups: groupItem = groups[alg.group] else: groupItem = QTreeWidgetItem() name = alg.i18n_group or alg.group groupItem.setText(0, name) groupItem.setToolTip(0, name) groups[alg.group] = groupItem algItem = TreeAlgorithmItem(alg) groupItem.addChild(algItem) if len(groups) > 0: providerItem = QTreeWidgetItem() providerItem.setText(0, ModelerUtils.providers[providerName].getDescription()) providerItem.setToolTip(0, ModelerUtils.providers[providerName].getDescription()) providerItem.setIcon(0, ModelerUtils.providers[providerName].getIcon()) for groupItem in groups.values(): providerItem.addChild(groupItem) self.algorithmTree.addTopLevelItem(providerItem) providerItem.setExpanded(text != '') for groupItem in groups.values(): if text != '': groupItem.setExpanded(True) self.algorithmTree.sortItems(0, Qt.AscendingOrder)
def loaddata(self,data): ''' load data for index tree. data is list of TableEntry(define in pychmfile.py ''' if self.dataloaded: return if data==None: return self.dataloaded=True self.tree.clear() lastchild=[] rootentry=[] for i in xrange(len(data)): indent=data[i].indent if indent >=len(rootentry): maxindent=len(rootentry)-1 lastchild.append(None) rootentry.append(None) if indent>0 and maxindent <0: print 'error, first entry isn\'t the root entry' if (indent-maxindent)>1: j=maxindent while j<indent: if len(lastchild)<=j+1: lastchild.append(None) rootentry.append(None) lastchild[j+1]=lastchild[j] rootentry[j+1]=rootentry[j] j+=1 lastchild[indent]=None rootentry[indent]=None if indent==0: item=QTreeWidgetItem(self.tree,lastchild[indent]) item.entry=data[i] item.setText(0,data[i].key) else: if rootentry[indent-1]==None: print 'error no root entry' item=QTreeWidgetItem(rootentry[indent-1],lastchild[indent]) item.entry=data[i] item.setText(0,data[i].key) item.setExpanded(True) lastchild[indent]=item rootentry[indent]=item self.tree.update()
def addTangoHost(self, host): host, port = parseTangoHost(host).split(':') db = PyTango.Database(host, port) hostitem = QTreeWidgetItem() hostitem.setIcon(0, QIcon(':/server.png')) hostitem.setText(0, host) hostinfo = {} devices = {} # get a list of all devices for server in db.get_server_list(): hostinfo[server] = {} devclslist = db.get_device_class_list(server) for i in xrange(0, len(devclslist), 2): devname, devcls = devclslist[i:i + 2] devinfo = db.get_device_info(devname) hostinfo[devname] = [server, devcls, devinfo] domain, family, member = devname.split('/') devices.setdefault(domain, {}).setdefault(family, set()).add(member) # create tree widget items for the devices for domain in sorted(devices): domainitem = QTreeWidgetItem([domain, '']) domainitem.setIcon(0, QIcon(':/folder.png')) for family in sorted(devices[domain]): familyitem = QTreeWidgetItem([family, '']) familyitem.setIcon(0, QIcon(':/folder.png')) for member in sorted(devices[domain][family]): devname = domain + '/' + family + '/' + member devitem = QTreeWidgetItem([member, hostinfo[devname][0]]) devitem.setIcon(0, QIcon(':/plug.png')) if not hostinfo[devname][2].exported: devitem.setForeground(0, QBrush(QColor('#666666'))) familyitem.addChild(devitem) domainitem.addChild(familyitem) hostitem.addChild(domainitem) self.tree.addTopLevelItem(hostitem) hostitem.setExpanded(True) self._tangoHosts[host] = hostinfo
def _create_item_from_node(self, node, parent): if "Type" in node: type = node["Type"].get() else: type = "" if "Description" in node: desc = node["Description"].get() else: desc = "" item = QTreeWidgetItem(parent, [node.name, type, desc]) item.node = node item.setExpanded(self.expanded_at_start) if type not in self.__icons_cache: self.__icons_cache[type] = QIcon(":/icons/small/datatypes/{}.png".format(type)) item.setIcon(0, self.__icons_cache[type]) return item
def buildParentItem(self,dcollection,title,rootresource): ''' Builds tree widget items from a dictionary. ''' rtItem = QTreeWidgetItem() rtItem.setText(0,title) rtItem.setIcon(0,QIcon(rootresource)) topLevelItems = [] for k,v in dcollection.iteritems(): parentItem = QTreeWidgetItem() if isinstance(v,dict): parentItem.setText(0,k) for kc,vc in v.iteritems(): child = QTreeWidgetItem() child.setText(0,self._combine(kc, vc)) parentItem.addChild(child) else: parentItem.setText(0,self._combine(k, v)) topLevelItems.append(parentItem) rtItem.addChildren(topLevelItems) rtItem.setExpanded(True) return rtItem
def populate(self): self.ui.treeWidget.setColumnCount(1) for pluginName, features in self.featureDict.iteritems(): parent = QTreeWidgetItem(self.ui.treeWidget) parent.setText(0, pluginName) parent.setExpanded(True) for name in sorted(features.keys()): parameters = features[name] item = QTreeWidgetItem(parent) item.setText(0, name) item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) # hack to ensure checkboxes visible item.setCheckState(0, Qt.Checked) item.setCheckState(0, Qt.Unchecked) if pluginName in self.selectedFeatures: if name in self.selectedFeatures[pluginName]: item.setCheckState(0, Qt.Checked)
def __init__(self, unmerged_files, parent=None): QDialog.__init__(self, parent=parent) self._ui = Ui_Dialog() self._ui.setupUi(self) self._parent = parent self.tree_items = {} self._status_items = [] self._solutions = {} self._current_path = "" self._radio_choices = {self._ui.deleteRadioButton: "delete", self._ui.addRadioButton: "add", self._ui.addCustomRadioButton: "add_custom"} self._u_files = unmerged_files u_files = self._u_files statuses = set([u_info["git_status"] for u_info in u_files.values()]) for status in statuses: status_item = QTreeWidgetItem(self._ui.treeWidget) status_item.setText(0, QString(GIT_STATUSES[status])) status_item.setExpanded(True) self._status_items.append(status_item) for u_path in [u_path for u_path in u_files if u_files[u_path]["git_status"] == status]: file_item = QTreeWidgetItem(status_item) file_item.setText(0, QString(u_path)) self.tree_items[file_item] = u_path self.connect_signals() # Hide every widget of the conflict details layout. self.show_all_details(False) document = self._ui.conflictTextEdit.document() syntax_highlight = SimpleGitMessagesHighlighter(document)
def loadEarthCoverage(self): """ Loads a previously saved earth coverage configuration """ try: self.clearTree() if self.earthCoverageDict == dict(): self.getEarthCoverageDict() rootItem = self.earthCoverageTreeWidget.invisibleRootItem() #database item for key in self.earthCoverageDict.keys(): item = QTreeWidgetItem(rootItem) item.setText(0,key) item.setExpanded(True) for cl in self.earthCoverageDict[key]: covItem = QTreeWidgetItem(item) covItem.setText(1,cl) covItem.setExpanded(True) except Exception as e: QgsMessageLog.logMessage(self.tr('Earth Coverage not loaded! Check log for details.')+':'.join(e.args), "DSG Tools Plugin", QgsMessageLog.CRITICAL)
def setDocuments(self, documents): """Display the specified documents in the list.""" # clear the treewidget for d in self.tree.invisibleRootItem().takeChildren(): for i in d.takeChildren(): i.doc = None # group the documents by directory dirs = {} for d in documents: path = d.url().toLocalFile() if path: dirname, filename = os.path.split(path) dirs.setdefault(dirname, []).append((filename, d)) for dirname in sorted(dirs, key=util.naturalsort): diritem = QTreeWidgetItem() diritem.setText(0, util.homify(dirname)) self.tree.addTopLevelItem(diritem) diritem.setExpanded(True) diritem.setFlags(Qt.ItemIsEnabled) diritem.setIcon(0, icons.get('folder-open')) for filename, document in sorted( dirs[dirname], key=lambda item: util.naturalsort(item[0])): fileitem = QTreeWidgetItem() diritem.addChild(fileitem) if documentwatcher.DocumentWatcher.instance( document).isdeleted(): itemtext = _("[deleted]") icon = "dialog-error" else: itemtext = _("[modified]") icon = "document-edit" fileitem.setIcon(0, icons.get(icon)) fileitem.setText(0, filename) fileitem.setText(1, itemtext) fileitem.doc = document # select the item if there is only one if len(dirs) == 1 and len(list(dirs.values())[0]) == 1: fileitem.setSelected(True) self.tree.resizeColumnToContents(0) self.tree.resizeColumnToContents(1) self.updateButtons()
def _refresh(self): self._handleChanges = False self._tree.clear() for dir in self._dirs: name = os.path.basename(os.path.normpath(dir)) top_level_item = QTreeWidgetItem(self._tree, [name]) top_level_item.setExpanded(True) self._loadDir(dir, top_level_item) dead_graphs = [] for graph in self._graphs.values(): tree_item = self._findItem(graph) if tree_item is None: dead_graphs.append(graph) else: if graph.isVisible(): tree_item.setBackground(0, QBrush(QColor(graph.color()))) tree_item.setCheckState(0, Qt.Checked) while tree_item is not None: tree_item.setExpanded(True) tree_item = tree_item.parent() ###################### # Close dead graphs: # ###################### for graph in dead_graphs: csv_path = graph.csvPath() print "Warning: Graph %s no longer exists." % csv_path if graph.isVisible(): graph.clear() del self._graphs[csv_path] ################### # Refresh graphs: # ################### for graph in self._graphs.values(): if graph.isVisible(): graph.refresh(self.fig, self.host) self._repaintCanvas() self._handleChanges = True
def populate(self): self.ui.treeWidget.setColumnCount(1) for pluginName, features in self.featureDict.iteritems(): if pluginName == "TestFeatures" and not ilastik_config.getboolean( "ilastik", "debug"): continue parent = QTreeWidgetItem(self.ui.treeWidget) if pluginName == "Standard Object Features": parent.setText(0, pluginName) parent.setToolTip( 0, 'http://hci.iwr.uni-heidelberg.de/vigra/doc/vigra/group__FeatureAccumulators.html' ) else: parent.setText(0, pluginName) parent.setExpanded(True) advanced_names = [] simple_names = [] for name in sorted(features.keys()): parameters = features[name] if 'advanced' in parameters: advanced_names.append(name) else: simple_names.append(name) for name in simple_names + advanced_names: parameters = features[name] item = QTreeWidgetItem(parent) item.setText(0, name) item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) if 'tooltip' in parameters: item.setToolTip(0, parameters['tooltip']) # hack to ensure checkboxes visible item.setCheckState(0, Qt.Checked) item.setCheckState(0, Qt.Unchecked) if pluginName in self.selectedFeatures: if name in self.selectedFeatures[pluginName]: item.setCheckState(0, Qt.Checked)
def __createEntry(self, description, entryText, entryVersion): """ Private method to generate a program entry. @param description descriptive text (string or QString) @param entryText text to show (string or QString) @param entryVersion version string to show (string or QString). """ itm = QTreeWidgetItem(self.programsList, QStringList(description)) font = itm.font(0) font.setBold(True) itm.setFont(0, font) if len(entryVersion): itm2 = QTreeWidgetItem(itm, QStringList() << entryText << entryVersion) itm.setExpanded(True) else: itm.setText(1, self.trUtf8("(not found)")) QApplication.processEvents() self.programsList.header().resizeSections(QHeaderView.ResizeToContents) self.programsList.header().setStretchLastSection(True)
def setDocuments(self, documents): """Display the specified documents in the list.""" # clear the treewidget for d in self.tree.invisibleRootItem().takeChildren(): for i in d.takeChildren(): i.doc = None # group the documents by directory dirs = {} for d in documents: path = d.url().toLocalFile() if path: dirname, filename = os.path.split(path) dirs.setdefault(dirname, []).append((filename, d)) for dirname in sorted(dirs, key=util.naturalsort): diritem = QTreeWidgetItem() diritem.setText(0, util.homify(dirname)) self.tree.addTopLevelItem(diritem) diritem.setExpanded(True) diritem.setFlags(Qt.ItemIsEnabled) diritem.setIcon(0, icons.get('folder-open')) for filename, document in sorted(dirs[dirname], key=lambda item: util.naturalsort(item[0])): fileitem = QTreeWidgetItem() diritem.addChild(fileitem) if documentwatcher.DocumentWatcher.instance(document).isdeleted(): itemtext = _("[deleted]") icon = "dialog-error" else: itemtext = _("[modified]") icon = "document-edit" fileitem.setIcon(0, icons.get(icon)) fileitem.setText(0, filename) fileitem.setText(1, itemtext) fileitem.doc = document # select the item if there is only one if len(dirs) == 1 and len(list(dirs.values())[0]) == 1: fileitem.setSelected(True) self.tree.resizeColumnToContents(0) self.tree.resizeColumnToContents(1) self.updateButtons()
def _populate_reporting_tab(self): """Populate trees about layers.""" self.tree.clear() self.add_layer.setEnabled(False) self.remove_layer.setEnabled(False) self.move_up.setEnabled(False) self.move_down.setEnabled(False) self.tree.setColumnCount(1) self.tree.setRootIsDecorated(False) self.tree.setHeaderHidden(True) analysis_branch = QTreeWidgetItem(self.tree.invisibleRootItem(), [FROM_ANALYSIS['name']]) analysis_branch.setFont(0, bold_font) analysis_branch.setExpanded(True) analysis_branch.setFlags(Qt.ItemIsEnabled) if self._multi_exposure_if: expected = self._multi_exposure_if.output_layers_expected() for group, layers in expected.iteritems(): group_branch = QTreeWidgetItem(analysis_branch, [group]) group_branch.setFont(0, bold_font) group_branch.setExpanded(True) group_branch.setFlags(Qt.ItemIsEnabled) for layer in layers: layer = definition(layer) if layer.get('allowed_geometries', None): item = QTreeWidgetItem(group_branch, [layer.get('name')]) item.setData(0, LAYER_ORIGIN_ROLE, FROM_ANALYSIS['key']) item.setData(0, LAYER_PARENT_ANALYSIS_ROLE, group) item.setData(0, LAYER_PURPOSE_KEY_OR_ID_ROLE, layer['key']) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) canvas_branch = QTreeWidgetItem(self.tree.invisibleRootItem(), [FROM_CANVAS['name']]) canvas_branch.setFont(0, bold_font) canvas_branch.setExpanded(True) canvas_branch.setFlags(Qt.ItemIsEnabled) # List layers from the canvas loaded_layers = QgsMapLayerRegistry.instance().mapLayers().values() canvas_layers = self.iface.mapCanvas().layers() flag = setting('visibleLayersOnlyFlag', expected_type=bool) for loaded_layer in loaded_layers: if flag and loaded_layer not in canvas_layers: continue title = loaded_layer.name() item = QTreeWidgetItem(canvas_branch, [title]) item.setData(0, LAYER_ORIGIN_ROLE, FROM_CANVAS['key']) item.setData(0, LAYER_PURPOSE_KEY_OR_ID_ROLE, loaded_layer.id()) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) self.tree.resizeColumnToContents(0)
def setPlugins( self, plugins ): """ Loads the plugins for the inputed dialog. :param plugins | [<XWizardPlugin>, ..] """ langs = {} icons = {} for plugin in plugins: wlang = plugin.wizardType() wgrp = plugin.wizardGroup() langs.setdefault(wlang, {}) langs[wlang].setdefault(wgrp, []) langs[wlang][wgrp].append( plugin ) icons.setdefault(wgrp, plugin.groupIcon(wgrp)) self._plugins = langs self.uiPluginTREE.clear() for wlang in sorted(langs.keys()): langitem = QTreeWidgetItem([wlang]) langitem.setSizeHint(0, QSize(0, 26)) for wgrp in sorted(langs[wlang].keys()): grpitem = QTreeWidgetItem([wgrp]) grpitem.setIcon(0, QIcon(icons[wgrp])) grpitem.setSizeHint(0, QSize(0, 26)) langitem.addChild(grpitem) folder = QIcon(projexui.resources.find('img/folder_32.png')) langitem.setIcon(0, folder) self.uiPluginTREE.addTopLevelItem(langitem) langitem.setExpanded(True)
def populate(self): self.ui.treeWidget.setColumnCount(1) for pluginName, features in self.featureDict.iteritems(): if pluginName=="TestFeatures" and not ilastik_config.getboolean("ilastik", "debug"): continue parent = QTreeWidgetItem(self.ui.treeWidget) if pluginName == "Standard Object Features": parent.setText(0, pluginName) parent.setToolTip(0, 'http://hci.iwr.uni-heidelberg.de/vigra/doc/vigra/group__FeatureAccumulators.html') else: parent.setText(0, pluginName) parent.setExpanded(True) advanced_names = [] simple_names = [] for name in sorted(features.keys()): parameters = features[name] if 'advanced' in parameters: advanced_names.append(name) else: simple_names.append(name) for name in simple_names+advanced_names: parameters = features[name] item = QTreeWidgetItem(parent) item.setText(0, name) item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) if 'tooltip' in parameters: item.setToolTip(0, parameters['tooltip']) # hack to ensure checkboxes visible item.setCheckState(0, Qt.Checked) item.setCheckState(0, Qt.Unchecked) if pluginName in self.selectedFeatures: if name in self.selectedFeatures[pluginName]: item.setCheckState(0, Qt.Checked)
def display(self): ''' Initialize top-level items ''' if len(self.items) == 0: return self.tree.clear() #If there is only one item then set it as the root item if len(self.items) == 1: rootItem = self.items[0] #Set root font rtFont = rootItem.font(0) rtFont.setBold(True) rootItem.setFont(0, rtFont) #Add the tree item to the tree widget self.tree.addTopLevelItem(rootItem) rootItem.setExpanded(True) else: rootItem = QTreeWidgetItem(self.tree) rootItem.setText(0, self.title) rootItem.setIcon(0, QIcon(self.rootResource)) #Set root font rtFont = rootItem.font(0) rtFont.setBold(True) rootItem.setFont(0, rtFont) rootItem.addChildren(self.items) rootItem.setExpanded(True) #Force the horizontal scrollbar to show self.tree.header().setResizeMode(QHeaderView.ResizeToContents)
def fill(self, registryQueries): for query in registryQueries: queryItem = QTreeWidgetItem(self) queryItem.setExpanded(True) queryItem.setText(0, QString.fromUtf8(query.path())) queryItem.setText(1, QString.fromUtf8(query.description())) for key in query: keyItem = QTreeWidgetItem(queryItem) keyItem.setExpanded(True) keyItem.setText(0, QString.fromUtf8(key.name())) for node, time in key.times().iteritems(): keyItem.setText(self.columnNode(node), QString.fromUtf8(str(time))) for value in key: valueItem = QTreeWidgetItem(keyItem) valueItem.setExpanded(True) valueItem.setText(0, QString.fromUtf8(value.name())) for data in value: valueItem.setText(self.columnNode(data.node()), QString.fromUtf8(self.dataToQString(data.datas())))
def fillAlgorithmTreeUsingCategories(self): providersToExclude = ['model', 'script'] self.algorithmTree.clear() text = unicode(self.searchBox.text()) groups = {} allAlgs = ModelerUtils.allAlgs for providerName in allAlgs.keys(): provider = allAlgs[providerName] name = 'ACTIVATE_' + providerName.upper().replace(' ', '_') if not ProcessingConfig.getSetting(name): continue if providerName in providersToExclude \ or len(ModelerUtils.providers[providerName].actions) != 0: continue algs = provider.values() # Add algorithms for alg in algs: if not alg.showInModeler or alg.allowOnlyOpenedLayers: continue altgroup, altsubgroup = AlgorithmClassification.getClassification( alg) if altgroup is None: continue algName = AlgorithmClassification.getDisplayName(alg) if text == '' or text.lower() in algName.lower(): if altgroup not in groups: groups[altgroup] = {} group = groups[altgroup] if altsubgroup not in group: groups[altgroup][altsubgroup] = [] subgroup = groups[altgroup][altsubgroup] subgroup.append(alg) if len(groups) > 0: mainItem = QTreeWidgetItem() mainItem.setText(0, self.tr('Geoalgorithms')) mainItem.setIcon(0, GeoAlgorithm.getDefaultIcon()) mainItem.setToolTip(0, mainItem.text(0)) for (groupname, group) in groups.items(): groupItem = QTreeWidgetItem() groupItem.setText(0, groupname) groupItem.setIcon(0, GeoAlgorithm.getDefaultIcon()) groupItem.setToolTip(0, groupItem.text(0)) mainItem.addChild(groupItem) for (subgroupname, subgroup) in group.items(): subgroupItem = QTreeWidgetItem() subgroupItem.setText(0, subgroupname) subgroupItem.setIcon(0, GeoAlgorithm.getDefaultIcon()) subgroupItem.setToolTip(0, subgroupItem.text(0)) groupItem.addChild(subgroupItem) for alg in subgroup: algItem = TreeAlgorithmItem(alg) subgroupItem.addChild(algItem) self.algorithmTree.addTopLevelItem(mainItem) for providerName in allAlgs.keys(): groups = {} provider = allAlgs[providerName] name = 'ACTIVATE_' + providerName.upper().replace(' ', '_') if not ProcessingConfig.getSetting(name): continue if providerName not in providersToExclude: continue algs = provider.values() # Add algorithms for alg in algs: if not alg.showInModeler or alg.allowOnlyOpenedLayers: continue if text == '' or text.lower() in alg.name.lower(): if alg.group in groups: groupItem = groups[alg.group] else: groupItem = QTreeWidgetItem() name = alg.i18n_group groupItem.setText(0, name) groupItem.setToolTip(0, name) groups[alg.group] = groupItem algItem = TreeAlgorithmItem(alg) groupItem.addChild(algItem) if len(groups) > 0: providerItem = QTreeWidgetItem() providerItem.setText( 0, ModelerUtils.providers[providerName].getDescription()) providerItem.setIcon( 0, ModelerUtils.providers[providerName].getIcon()) providerItem.setToolTip(0, providerItem.text(0)) for groupItem in groups.values(): providerItem.addChild(groupItem) self.algorithmTree.addTopLevelItem(providerItem) providerItem.setExpanded(text != '') for groupItem in groups.values(): if text != '': groupItem.setExpanded(True)
def populate_filter_tree(self): """ Populates the filter tree widget from the filter data. Called automatically from other methods when necessary. """ self.filterTreeWidget.clear() for name, manager in sorted(self.filter_managers.items()): top = QTreeWidgetItem(self.filterTreeWidget) top.setText(0, name) top.setFlags(Qt.ItemIsEnabled | Qt.ItemIsDropEnabled) top.setData(1, Qt.UserRole, self.FilterTreeRoleTop) top.setTextColor(0, Qt.gray) top.setChildIndicatorPolicy(QTreeWidgetItem.ShowIndicator) self.filterTreeWidget.addTopLevelItem(top) if manager.list_items(): top.setExpanded(True) for i in manager.list_items(): if isinstance(i[1], manager.FilterGroup): group = QTreeWidgetItem(top) group.setText(0, i[0]) group.setData(1, Qt.UserRole, self.FilterTreeRoleGroup) group.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDropEnabled | Qt.ItemIsDragEnabled) group.setChildIndicatorPolicy( QTreeWidgetItem.ShowIndicator) if i[1].list_items(): group.setExpanded(True) top.addChild(group) for f in i[1].list_items(): item = QTreeWidgetItem(group) item.setText(0, f[0]) if f[1].active: item.setData(0, CheckableItemDelegate.CheckedRole, True) else: item.setData(0, CheckableItemDelegate.CheckedRole, False) if i[1].exclusive: item.setData(0, CheckableItemDelegate.CheckTypeRole, CheckableItemDelegate.RadioCheckType) else: item.setData( 0, CheckableItemDelegate.CheckTypeRole, CheckableItemDelegate.CheckBoxCheckType) item.setData(1, Qt.UserRole, self.FilterTreeRoleFilter) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled) group.addChild(item) else: item = QTreeWidgetItem(top) item.setText(0, i[0]) if i[1].active: item.setData(0, CheckableItemDelegate.CheckedRole, True) else: item.setData(0, CheckableItemDelegate.CheckedRole, False) item.setData(0, CheckableItemDelegate.CheckTypeRole, CheckableItemDelegate.CheckBoxCheckType) item.setData(1, Qt.UserRole, self.FilterTreeRoleFilter) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled) top.addChild(item)
class DeviceDialog(QDialog, Ui_DeviceDialog): """ Function and Event handling class for the Ui_DeviceDialog. """ qtcb_enumerate = pyqtSignal(str, str, 'char', type((0, )), type((0, )), int, int) qtcb_connected = pyqtSignal(int) def __init__(self, parent): QDialog.__init__(self, parent, get_modeless_dialog_flags()) self._logger_window = parent self.qtcb_enumerate.connect(self.cb_enumerate) self.qtcb_connected.connect(self.cb_connected) self.host = None self.port = None self.secret = None self.ipcon = IPConnection() self.ipcon.register_callback(IPConnection.CALLBACK_CONNECTED, self.qtcb_connected.emit) self.ipcon.register_callback(IPConnection.CALLBACK_ENUMERATE, self.qtcb_enumerate.emit) self.setupUi(self) self.btn_add_device.clicked.connect(self.btn_add_device_clicked) self.btn_refresh.clicked.connect(self.btn_refresh_clicked) self.btn_close.clicked.connect(self.btn_close_clicked) self.tree_widget.itemActivated.connect(self.add_item) self.connected_uids = [] self.available_item = QTreeWidgetItem(['No devices available']) self.supported_item = QTreeWidgetItem(['Supported devices']) self.tree_widget.addTopLevelItem(self.available_item) self.tree_widget.addTopLevelItem(self.supported_item) for device_name in device_specs: self.supported_item.addChild(QTreeWidgetItem([device_name])) self.supported_item.sortChildren(0, Qt.AscendingOrder) self.supported_item.setExpanded(True) def cb_connected(self, connect_reason): self.tree_widget.clearSelection() self.available_item.takeChildren() self.available_item.setExpanded(True) self.available_item.setText( 0, 'No devices available at {0}:{1}'.format(self.host, self.port)) self.connected_uids = [] if self.secret != None: self.ipcon.set_auto_reconnect( False) # don't auto-reconnect on authentication error try: self.ipcon.authenticate(self.secret) except: try: self.ipcon.disconnect() except: pass if connect_reason == IPConnection.CONNECT_REASON_AUTO_RECONNECT: extra = ' after auto-reconnect' else: extra = '' self.available_item.setText(0, 'Could not authenticate' + extra) return self.ipcon.set_auto_reconnect(True) try: self.ipcon.enumerate() except: pass def cb_enumerate(self, uid, connected_uid, position, hardware_version, firmware_version, device_identifier, enumeration_type): if enumeration_type in [IPConnection.ENUMERATION_TYPE_AVAILABLE, IPConnection.ENUMERATION_TYPE_CONNECTED] and \ uid not in self.connected_uids: try: display_name = device_factory.get_device_display_name( device_identifier) except KeyError: return # unknown device identifier if display_name in device_specs: self.connected_uids.append(uid) self.available_item.addChild( QTreeWidgetItem(['{0} [{1}]'.format(display_name, uid)])) self.available_item.setText( 0, 'Devices available at {0}:{1}'.format( self.host, self.port)) self.available_item.sortChildren(0, Qt.AscendingOrder) else: if uid in self.connected_uids: self.connected_uids.remove(uid) for i in range(self.available_item.childCount()): child = self.available_item.child(i) if '[{0}]'.format(uid) in child.text(0): self.available_item.takeChild(i) break if self.available_item.childCount() == 0: self.available_item.setText( 0, 'No devices available at {0}:{1}'.format( self.host, self.port)) def btn_add_device_clicked(self): for item in self.tree_widget.selectedItems(): if item == self.available_item or item == self.supported_item: continue self._logger_window.add_device_to_tree( self.create_device_config(item.text(0))) def btn_refresh_clicked(self): try: self.ipcon.disconnect() except: pass self.tree_widget.clearSelection() self.available_item.takeChildren() self.available_item.setExpanded(True) self.connected_uids = [] self.host = self._logger_window.combo_host.currentText() self.port = self._logger_window.spin_port.value() if self._logger_window.check_authentication.isChecked(): try: self.secret = self._logger_window.edit_secret.text().encode( 'ascii') except: self.secret = None else: self.secret = None try: self.ipcon.connect(self.host, self.port) self.available_item.setText( 0, 'No devices available at {0}:{1}'.format(self.host, self.port)) except: self.available_item.setText( 0, 'Could not connect to {0}:{1}'.format(self.host, self.port)) def btn_close_clicked(self): self.close() def add_item(self, item): if item == self.available_item or item == self.supported_item: return self._logger_window.add_device_to_tree( self.create_device_config(item.text(0))) def create_device_config(self, item_text): name, uid = Utilities.parse_device_name(item_text) # FIXME device_spec = device_specs[name] if uid == None: # FIXME uid = '' device = { 'host': 'default', 'name': name, 'uid': uid, 'values': {}, 'options': {} } for value_spec in device_spec['values']: device['values'][value_spec['name']] = {'interval': 0} if value_spec['subvalues'] != None: device['values'][value_spec['name']]['subvalues'] = {} for subvalue_name in value_spec['subvalues']: device['values'][ value_spec['name']]['subvalues'][subvalue_name] = True if device_spec['options'] != None: for option_spec in device_spec['options']: device['options'][option_spec['name']] = { 'value': option_spec['default'] } return device
def addParent(self, parent, column, title, data): item = QTreeWidgetItem(parent, [title]) item.setData(column, Qt.UserRole, data) item.setChildIndicatorPolicy(QTreeWidgetItem.ShowIndicator) item.setExpanded(True) return item
def _reloadBodyTree(self): self.bodyTreeWidget.clear() self._bodyTreeParentItems = {} currentEditingRavelerLabel = self.opSplitBodyCarving.CurrentRavelerLabel.value currentEditingFragmentName = self.opSplitBodyCarving.CurrentEditingFragment.value for ravelerLabel in sorted(self._ravelerLabels): fragmentNames = self.opSplitBodyCarving.getFragmentNames( ravelerLabel) # For this raveler label, how many fragments do we have and how many do we expect? # Count the number of annotations with this label. num_splits = reduce( lambda count, ann: count + (ann.ravelerLabel == ravelerLabel), self._annotations.values(), 0) num_expected = num_splits + 1 num_fragments = len(fragmentNames) # Parent row for the raveler body progressText = "({}/{})".format(num_fragments, num_expected) bodyItem = QTreeWidgetItem( ["{}".format(ravelerLabel), progressText, ""]) bodyItem.setData(0, Qt.UserRole, ravelerLabel) self._bodyTreeParentItems[ravelerLabel] = bodyItem self.bodyTreeWidget.invisibleRootItem().addChild(bodyItem) progressBar = BodyProgressBar(self) progressBar.setMaximum(num_expected) progressBar.setValue(min(num_fragments, num_expected)) progressBar.setText(progressText) self.bodyTreeWidget.setItemWidget(bodyItem, BodyTreeColumns.Button1, progressBar) if currentEditingFragmentName == "" and currentEditingRavelerLabel == ravelerLabel: selectButton = QPushButton("New Fragment") selectButton.pressed.connect( partial(self._startNewFragment, ravelerLabel)) selectButton.setIcon(QIcon(ilastikIcons.AddSel)) self.bodyTreeWidget.setItemWidget(bodyItem, BodyTreeColumns.Button2, selectButton) bodyItem.setExpanded(True) # Child rows for each fragment fragmentItem = None for fragmentName in fragmentNames: fragmentItem = QTreeWidgetItem([fragmentName, "", ""]) bodyItem.addChild(fragmentItem) # Add 'edit' and 'delete' buttons to the LAST fragment item if fragmentItem is not None and ravelerLabel == currentEditingRavelerLabel: assert fragmentName is not None if currentEditingFragmentName == fragmentName: saveButton = QPushButton("Save") saveButton.pressed.connect( partial(self._saveFragment, fragmentName)) saveButton.setIcon(QIcon(ilastikIcons.Save)) self.bodyTreeWidget.setItemWidget(fragmentItem, BodyTreeColumns.Button1, saveButton) elif currentEditingFragmentName == "": editButton = QPushButton("Edit") editButton.pressed.connect( partial(self._editFragment, fragmentName)) editButton.setIcon(QIcon(ilastikIcons.Edit)) self.bodyTreeWidget.setItemWidget(fragmentItem, BodyTreeColumns.Button1, editButton) if currentEditingFragmentName == "" or currentEditingFragmentName == fragmentName: deleteButton = QPushButton("Delete") deleteButton.pressed.connect( partial(self._deleteFragment, fragmentName)) deleteButton.setIcon(QIcon(ilastikIcons.RemSel)) self.bodyTreeWidget.setItemWidget(fragmentItem, BodyTreeColumns.Button2, deleteButton)
def fillListBox(self, f25, f50, f100, f250): self.cartasList.clear() item25 = QTreeWidgetItem(['1:25.000 (' + str(len(f25)) + ')', '']) item50 = QTreeWidgetItem(['1:50.000 (' + str(len(f50)) + ')', '']) item100 = QTreeWidgetItem(['1:100.000 (' + str(len(f100)) + ')', '']) item250 = QTreeWidgetItem(['1:250.000 (' + str(len(f250)) + ')', '']) itemNotFound = QTreeWidgetItem([u'Não existentes', '']) self.cartasList.addTopLevelItems( [item25, item50, item100, item250, itemNotFound]) for c in f25.keys(): if f25[c] != '': if f25[c][0] != '-': item = QTreeWidgetItem([c, f25[c]]) item25.addChild(item) else: item = QTreeWidgetItem([c, '']) itemNotFound.addChild(item) else: item = QTreeWidgetItem([c, '']) itemNotFound.addChild(item) item25.setExpanded(True) for c in f50.keys(): if f50[c] != '': if f50[c][0] != '-': item = QTreeWidgetItem([c, f50[c]]) item50.addChild(item) else: item = QTreeWidgetItem([c, '']) itemNotFound.addChild(item) else: item = QTreeWidgetItem([c, '']) itemNotFound.addChild(item) item50.setExpanded(True) for c in f100.keys(): if f100[c] != '': if f100[c][0] != '-': item = QTreeWidgetItem([c, f100[c]]) item100.addChild(item) else: item = QTreeWidgetItem([c, '']) itemNotFound.addChild(item) else: item = QTreeWidgetItem([c, '']) itemNotFound.addChild(item) item100.setExpanded(True) for c in f250.keys(): if f250[c] != '': if f250[c][0] != '-': item = QTreeWidgetItem([c, f250[c]]) item250.addChild(item) else: item = QTreeWidgetItem([c, '']) itemNotFound.addChild(item) else: item = QTreeWidgetItem([c, '']) itemNotFound.addChild(item) item250.setExpanded(True) itemNotFound.setExpanded(True) if itemNotFound.childCount() == 0: self.cartasList.invisibleRootItem().removeChild(itemNotFound) else: itemNotFound.setText( 0, itemNotFound.text(0) + ' (' + str(itemNotFound.childCount()) + ')') self.cartasList.header().setResizeMode( QtGui.QHeaderView.ResizeToContents)
class RestoreDialog(widgets.dialog.Dialog): def __init__(self, parent=None): super(RestoreDialog, self).__init__(parent) self.messageLabel().setWordWrap(True) userguide.addButton(self.buttonBox(), "snippets") self.tree = QTreeWidget(headerHidden=True, rootIsDecorated=False) self.setMainWidget(self.tree) self.deletedItem = QTreeWidgetItem(self.tree) self.deletedItem.setFlags(Qt.ItemIsUserCheckable) self.changedItem = QTreeWidgetItem(self.tree) self.changedItem.setFlags(Qt.ItemIsUserCheckable) self.tree.itemChanged.connect(self.slotItemChanged) app.translateUI(self) app.languageChanged.connect(self.populate) self.accepted.connect(self.updateSnippets) qutil.saveDialogSize(self, "snippettool/restoredialog/size") def translateUI(self): self.setWindowTitle( app.caption(_("dialog title", "Restore Built-in Snippets"))) self.setMessage( _("This dialog allows you to recover built-in snippets that have " "been changed or deleted. Check the snippets you want to recover " "and click the button \"Restore Checked Snippets.\"")) self.button("ok").setText(_("Restore Checked Snippets")) self.deletedItem.setText(0, _("Deleted Snippets")) self.changedItem.setText(0, _("Changed Snippets")) def populate(self): """Puts the deleted/changed snippets in the tree.""" self.deletedItem.takeChildren() self.deletedItem.setExpanded(True) self.deletedItem.setCheckState(0, Qt.Unchecked) self.changedItem.takeChildren() self.changedItem.setExpanded(True) self.changedItem.setCheckState(0, Qt.Unchecked) builtins = list(builtin.builtin_snippets) builtins.sort(key=snippets.title) names = frozenset(snippets.names()) for name in builtins: if name in names: if snippets.isoriginal(name): continue parent = self.changedItem else: parent = self.deletedItem item = QTreeWidgetItem(parent) item.name = name item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) item.setCheckState(0, Qt.Unchecked) item.setText(0, snippets.title(name)) self.deletedItem.setDisabled(self.deletedItem.childCount() == 0) self.changedItem.setDisabled(self.changedItem.childCount() == 0) self.checkOkButton() def slotItemChanged(self, item): if item in (self.deletedItem, self.changedItem): for i in range(item.childCount()): item.child(i).setCheckState(0, item.checkState(0)) self.checkOkButton() def checkedSnippets(self): """Yields the names of the checked snippets.""" for parent in (self.deletedItem, self.changedItem): for i in range(parent.childCount()): child = parent.child(i) if child.checkState(0) == Qt.Checked: yield child.name def updateSnippets(self): """Restores the checked snippets.""" collection = self.parent().parent().snippetActions for name in self.checkedSnippets(): collection.restoreDefaultShortcuts(name) model.model().saveSnippet(name, None, None) def checkOkButton(self): """Enables the OK button if there are selected snippets.""" self.button("ok").setEnabled(any(self.checkedSnippets()))