def on_ions_updated(self, new_ions): qmodel = QStandardItemModel() qmodel.setColumnCount(2) qmodel.setHorizontalHeaderItem(0, QStandardItem('Ion')) qmodel.setHorizontalHeaderItem(1, QStandardItem('Abundance (%)')) root = qmodel.invisibleRootItem() element_keyfunc = lambda x: x.isotope.element sorted_ions = sorted(new_ions, key=element_keyfunc) for element, ions in itertools.groupby(sorted_ions, key=element_keyfunc): element_item = QStandardItem(element) element_item.setCheckable(True) element_item.setCheckState(2) root.appendRow(element_item) for ion in ions: ion_name = QStandardItem(ion.name) ion_name.setData(ion,32) ion_name.emitDataChanged() ion_abundance = QStandardItem(str(ion.isotope.abundance)) element_item.appendRow([ion_name, ion_abundance]) self.ionlistTree.setModel(qmodel) self.ionlistTree.expandAll() self.addionsButton.setEnabled(True) self._qmodel=qmodel
def on_analyses_viewmodel_updated(self, view_model): qmodel = QStandardItemModel() qmodel.itemChanged.connect(self.on_qmodel_itemChanged) qmodel.setColumnCount(5) qmodel.setHorizontalHeaderItem(0, QStandardItem('Ion')) qmodel.setHorizontalHeaderItem(1, QStandardItem('Method')) qmodel.setHorizontalHeaderItem(2, QStandardItem('Start')) qmodel.setHorizontalHeaderItem(3, QStandardItem('End')) qmodel.setHorizontalHeaderItem(4, QStandardItem('Reason')) root = qmodel.invisibleRootItem() for ion, analysis in view_model.analyses.items(): ion_name = QStandardItem(ion.name) ion_name.setData(ion, Qt.UserRole) method = QStandardItem(analysis.method) start = QStandardItem(str(round(analysis.range.start,2))) end = QStandardItem(str(round(analysis.range.end,2))) reason = QStandardItem(analysis.reason) root.appendRow([ion_name, method, start, end, reason]) self.rangedTable.setModel(qmodel) self.rangedTable.setItemDelegateForColumn(1, MethodsComboDelegate(view_model.methods, self.rangedTable)) for row in range(0, qmodel.rowCount()): self.rangedTable.openPersistentEditor(qmodel.index(row, 1)) self.rangedTable.setColumnWidth(1, 95) self.rangedTable.setContextMenuPolicy(3) self.rangedTable.customContextMenuRequested.connect(self._context_menu_requested) shortcut = QShortcut(QKeySequence('Del'), self.rangedTable, self._delete_ion,self._delete_ion, context=0)
def fillOpenTraverseEndPoints(self): """ Change End Points combo with target points observed from the last point selected in Order List if open traverse is chosen. """ oldEndPoint = self.ui.EndPointComboBox.itemData( self.ui.EndPointComboBox.currentIndex()) # clear combos self.ui.EndPointComboBox.clear() self.ui.EndPointComboBox.setEnabled(True) #get last angle point from order list if self.ui.OrderList.count() == 0: return lastp = self.ui.OrderList.item(self.ui.OrderList.count() - 1).data( Qt.UserRole) targets = get_targets(lastp[0], lastp[1], lastp[2]) # fill end point combo combomodel = self.ui.EndPointComboBox.model() known_list = get_known() if targets is not None: for target in targets: item = QStandardItem(u"%s (id:%s)" % (target[0], target[2])) item.setData(target, Qt.UserRole) if known_list is not None and target[0] in known_list: itemfont = item.font() itemfont.setWeight(QFont.Bold) item.setFont(itemfont) combomodel.appendRow(item) self.ui.EndPointComboBox.setCurrentIndex( self.ui.EndPointComboBox.findData(oldEndPoint))
def _cat_desc_to_std_item(self, desc): """ Create a QStandardItem for the category description. """ item = QStandardItem() item.setText(desc.name) if desc.icon: icon = desc.icon else: icon = "icons/default-category.svg" icon = icon_loader.from_description(desc).get(icon) item.setIcon(icon) if desc.background: background = desc.background else: background = DEFAULT_COLOR background = NAMED_COLORS.get(background, background) brush = QBrush(QColor(background)) item.setData(brush, self.BACKGROUND_ROLE) tooltip = desc.description if desc.description else desc.name item.setToolTip(tooltip) item.setFlags(Qt.ItemIsEnabled) item.setData(QVariant(desc), self.CATEGORY_DESC_ROLE) return item
def listCharts(self): self.chartModel.clear() for c in self.charts: item = QStandardItem(c[0] + ' (' + c[2] + ')') item.setData(c[1]) self.chartModel.appendRow(item)
def dropMimeData(self, mimedata, action, row, column, parentIndex): """ Handles the dropping of an item onto the model. De-serializes the data and inserts it into the model. """ # decode data using qgis helpers uri_list = QgsMimeDataUtils.decodeUriList(mimedata) if not uri_list: return False # find parent item dropParent = self.itemFromIndex(parentIndex) if not dropParent: return False # each uri will become a new item for uri in uri_list: item = QStandardItem(uri.name) item.setData(uri) # avoid placing dragged layers on it item.setDropEnabled(False) if uri.providerKey in ICON_MAPPER: item.setIcon(QIcon(ICON_MAPPER[uri.providerKey])) dropParent.appendRow(item) dropParent.emitDataChanged() return True
def fillOpenTraverseEndPoints(self): """ Change End Points combo with target points observed from the last point selected in Order List if open traverse is chosen. """ oldEndPoint = self.ui.EndPointComboBox.itemData( self.ui.EndPointComboBox.currentIndex() ) # clear combos self.ui.EndPointComboBox.clear() self.ui.EndPointComboBox.setEnabled(True) #get last angle point from order list if self.ui.OrderList.count() == 0: return lastp = self.ui.OrderList.item( self.ui.OrderList.count()-1 ).data(Qt.UserRole) targets = get_targets(lastp[0], lastp[1], lastp[2]) # fill end point combo combomodel = self.ui.EndPointComboBox.model() known_list = get_known() if targets is not None: for target in targets: item = QStandardItem(u"%s (id:%s)"% (target[0],target[2])) item.setData(target,Qt.UserRole) if known_list is not None and target[0] in known_list: itemfont = item.font() itemfont.setWeight(QFont.Bold) item.setFont(itemfont) combomodel.appendRow( item ) self.ui.EndPointComboBox.setCurrentIndex( self.ui.EndPointComboBox.findData(oldEndPoint) )
def addItemToStore(self, name, category=None, icon=None): newItem = QStandardItem(name) if icon: newItem.setIcon(icon) if category: newItem.setData(category) self.__modelStore.appendRow(newItem)
def create_last_modified_item(last_modified): item = QStandardItem( QDateTime.fromTime_t(last_modified).toString( 'yyyy-MM-dd HH:mm:ss')) item.setData(last_modified, USER_ROLE_LAST_MODIFIED) return item
def __init__(self, __parent = None, event=False, fm = False): """ Model constructor. Create the default QStandardItem's for the default nodes. """ QStandardItemModel.__init__(self, __parent) EventHandler.__init__(self) self.__parent = __parent self.VFS = VFS.Get() self.ch = False # init translation self.translation() # creating qstandarditem for the default nodes (the four displayed nodes when dff is launched) self.root_item = self.invisibleRootItem() tmp = self.VFS.GetNode("/").children() item_list = [] for i in tmp: node_item = QStandardItem(i.name()) node_item.setData(QVariant(long(i.this)), Qt.UserRole + 1) node_item.setData(QVariant(False), Qt.UserRole + 2) item_list.append(node_item) if len(item_list): self.root_item.appendRows(item_list) if event: self.VFS.connection(self)
class UserItemModel(QStandardItemModel): foo, nama, userPicture, address, realname, locked = range(6) def __init__(self): QStandardItemModel.__init__(self) role_names = { self.foo: "", self.nama: "nama", self.userPicture: "userpicture", self.address: "address", self.realname: "realname", self.locked: "locked" } self.setRoleNames(role_names) def addRootElement(self): root = MyUser('root', 'root', '/root') self.addUserItem(root.getName(), root.getAvatar(), root.getHome(), root.getRealName(), root.getLock()) def addUserItem(self, username, userPicture, address, realname, locked, foo = ""): self.item = QStandardItem() self.item.setData(username, self.nama) self.item.setData(userPicture, self.userPicture) self.item.setData(address, self.address) self.item.setData(realname, self.realname) self.item.setData(locked, self.locked) self.appendRow(self.item)
def populate_neo_channel_group_list(self): """ Fill the channel group list with appropriate entries. Qt.UserRole: The :class:`neo.RecordingChannelGroup` object """ self.neoChannelGroupList.clearSelection() self.channelgroup_model.clear() self.parent.channel_group_names.clear() rcgs = [] for b in self.blocks(): rcgs.extend(b.recordingchannelgroups) filters = self.parent.get_active_filters( 'Recording Channel Group') rcgs = self.filter_ordered(rcgs, filters) for i, rcg in enumerate(rcgs): self.parent.channel_group_names[rcg] = '%s-%s' % ( self.parent.block_ids[rcg.block], self.get_letter_id(i, True)) if rcg.name: name = rcg.name + ' (%s)' % \ self.parent.channel_group_names[rcg] else: name = self.parent.channel_group_names[rcg] new_item = QStandardItem(name) new_item.setData(rcg, Qt.UserRole) self.channelgroup_model.appendRow(new_item) self.neoChannelGroupList.setCurrentIndex( self.channelgroup_model.index(0, 0)) if api.config.autoselect_channel_groups: self.neoChannelGroupList.selectAll() elif not rcgs: self.selected_channel_groups_changed()
def addItemToQTableView(self, item, selectedItems): standardItem = QStandardItem(item.name) standardItem.setData(item.data) logger.debug( "--rightArrowClicked() self._model.appendRow(standardItem) selectedItems: {0}" .format(len(selectedItems))) self._model.appendRow(standardItem)
def sum_item(value): item = QStandardItem() item.setData(value, Qt.DisplayRole) item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter) item.setFlags(Qt.ItemIsEnabled) item.setFont(bold_font) return item
def __display_table_rslt(self, table_rows): ''' controls table_comp_rslt widget fill the widget with table_rows list @param table_rows: [] ''' rows_count = len(table_rows) model = QStandardItemModel(rows_count, 3) model.setHorizontalHeaderLabels(TAB_LABELS) # fill model with data for row in range(rows_count): for col in range(3): item = QStandardItem() item.setData(str(table_rows[row][col]), Qt.DisplayRole) model.setItem(row, col, item) # self.table_comp_rslt.clearContents() if self.table_comp_rslt.isSortingEnabled(): self.table_comp_rslt.setSortingEnabled(False) proxy = numsort.NumberSortModel() proxy.setSourceModel(model) self.table_comp_rslt.setModel(proxy) self.table_comp_rslt.resizeColumnsToContents() self.table_comp_rslt.setSortingEnabled(True)
def populate_neo_unit_list(self): """ Fill the unit list with appropriate entries. Qt.UserRole: The :class:`neo.Unit` object """ self.unit_model.clear() units = [] for rcg in self.recording_channel_groups(): units.extend(rcg.units) filters = self.parent.get_active_filters('Unit') units = self.filter_ordered(units, filters) for i, u in enumerate(units): if self.parent.is_filtered(u, filters): continue if u.name: name = u.name + ' (%s-%d)' % \ (self.parent.channel_group_names[rcg], i) else: name = '%s-%d' % (self.parent.channel_group_names[rcg], i) new_item = QStandardItem(name) new_item.setData(u, Qt.UserRole) self.unit_model.appendRow(new_item) if api.config.autoselect_units: self.neoUnitList.selectAll() self.selected_units_changed()
def make_row(self, state, title): item = QStandardItem(title) if title else QStandardItem() item.setFlags( Qt.ItemIsUserCheckable | Qt.ItemIsTristate | Qt.ItemIsEnabled | Qt.ItemIsEditable) item.setData(self.state_to_check_state(state), Qt.CheckStateRole) return [item]
def _cat_desc_to_std_item(self, desc): """ Create a QStandardItem for the category description. """ item = QStandardItem() item.setText(desc.name) if desc.icon: icon = desc.icon else: icon = "icons/default-category.svg" icon = icon_loader.from_description(desc).get(icon) item.setIcon(icon) if desc.background: background = desc.background else: background = DEFAULT_COLOR background = NAMED_COLORS.get(background, background) brush = QBrush(QColor(background)) item.setData(brush, self.BACKGROUND_ROLE) tooltip = desc.description if desc.description else desc.name item.setToolTip(tooltip) item.setFlags(Qt.ItemIsEnabled) item.setData(desc, self.CATEGORY_DESC_ROLE) return item
def populate_neo_segment_list(self): """ Fill the segment list with appropriate entries. Qt.UserRole: The :class:`neo.Segment` object """ self.segment_model.clear() segments = [] for b in self.blocks(): segments.extend(b.segments) filters = self.parent.get_active_filters('Segment') segments = self.filter_ordered(segments, filters) for i, s in enumerate(segments): if s.name: name = s.name + ' (%s-%i)' % \ (self.parent.block_ids[s.block], i) else: name = '%s-%i' % (self.parent.block_ids[s.block], i) new_item = QStandardItem(name) new_item.setData(s, Qt.UserRole) self.segment_model.appendRow(new_item) self.neoSegmentList.setCurrentIndex(self.segment_model.index(0, 0)) if api.config.autoselect_segments: self.neoSegmentList.selectAll() self.selected_segments_changed()
def addNcFile(self, ncFileName): f = NetCDFFile(ncFileName) self.files[ncFileName] = f fItem = QStandardItem(ncFileName) fItem.setIcon(self.icons['file']) fItem.setData(QVariant(ncFileName)) fItem.ncItem = ('F', f) self.rootItem.appendRow(fItem) for an,av in ncFAttributes(f).items(): aItem = QStandardItem(an) aItem.setIcon(self.icons['attribute']) aItem.setData(QVariant(an)) aItem.ncItem = ('A', av) fItem.appendRow(aItem) for dn,dv in f.dimensions.items(): dItem = QStandardItem(dn) dItem.setIcon(self.icons['dimension']) dItem.setData(QVariant(dn)) dItem.ncItem = ('D', dv) fItem.appendRow(dItem) for vn, vv in f.variables.items(): vItem = QStandardItem(vn) vItem.setIcon(self.icons['variable']) vItem.setData(QVariant(vn)) vItem.ncItem = ('V', vv) fItem.appendRow(vItem) for an,av in ncVAttributes(vv).items(): aItem = QStandardItem(an) aItem.setIcon(self.icons['attribute']) aItem.setData(QVariant(an)) aItem.ncItem = ('A', av) vItem.appendRow(aItem)
def updateDir(self, path = None): """ Fonction permettant de naviguer dans la listes des répertoires """ if path : self.currentDir = path self.location.setText("<b>%s</b>" % path) self.dirModel.clear() self.tmpdir = QDir() self.tmpdir.setPath(self.currentDir) self.tmpdir.setNameFilters(QStringList(self.filter)) # Une icône pour les images, un autre icône pour les vidéos, et # une pour audio if self.mode == "image" : icone = QIcon("Icones" + os.sep + "image_image.png") elif self.mode == "video" : icone = QIcon("Icones" + os.sep + "image_video.png") elif self.mode == "audio" : icone = QIcon("Icones" + os.sep + "image_audio.png") else: icone = QIcon("Icones" + os.sep + "image_default.png") for wlfile in self.tmpdir.entryList(QDir.Files): if self.mode == "image" : icone = QIcon(EkdPreview("Icones" + os.sep + "image_default.png").get_preview()) item = QStandardItem(icone, QString(wlfile)) item.setToolTip(wlfile) item.setData(QVariant(self.tmpdir.absolutePath() + os.sep + wlfile), Qt.UserRole + 2) item.setData(QVariant(wlfile), Qt.UserRole + 3) self.dirModel.appendRow(item)
def update_tree_view(self): sis = self.tree_view.header().sortIndicatorSection() sio = self.tree_view.header().sortIndicatorOrder() self.tree_view_model.clear() for info in infos.get_brick_infos(): if info.connected_uid != '0': position_prefix = info.connected_uid else: position_prefix = info.uid position_item = QStandardItem(info.position.upper()) position_item.setData(position_prefix + ':' + info.position.upper(), USER_ROLE_POSITION) parent = [QStandardItem(info.name), QStandardItem(info.uid), position_item, QStandardItem('.'.join(map(str, info.firmware_version_installed)))] for item in parent: item.setFlags(item.flags() & ~Qt.ItemIsEditable) self.tree_view_model.appendRow(parent) for port in sorted(info.bricklets): if info.bricklets[port] and info.bricklets[port].protocol_version == 2: child = [QStandardItem(info.bricklets[port].name), QStandardItem(info.bricklets[port].uid), QStandardItem(info.bricklets[port].position.upper()), QStandardItem('.'.join(map(str, info.bricklets[port].firmware_version_installed)))] for item in child: item.setFlags(item.flags() & ~Qt.ItemIsEditable) parent[0].appendRow(child) if info.can_have_extension: extensions = [] if info.extensions['ext0'] != None: extensions.append((info.extensions['ext0'], 'Ext0')) if info.extensions['ext1'] != None: extensions.append((info.extensions['ext1'], 'Ext1')) for extension in extensions: if extension[0].firmware_version_installed != (0, 0, 0): fw_version = '.'.join(map(str, extension[0].firmware_version_installed)) else: fw_version = '' child = [QStandardItem(extension[0].name), QStandardItem(''), QStandardItem(extension[1]), QStandardItem(fw_version)] for item in child: item.setFlags(item.flags() & ~Qt.ItemIsEditable) parent[0].appendRow(child) self.set_tree_view_defaults() self.tree_view.header().setSortIndicator(sis, sio) self.update_advanced_window() self.delayed_refresh_updates_timer.start()
def _update_stats_model(self): # Update the results_model with up to date scores. # Note: The target class specific scores (if requested) are # computed as needed in this method. model = self.view.model() # clear the table model, but preserving the header labels for r in reversed(range(model.rowCount())): model.takeRow(r) target_index = None if self.data is not None: class_var = self.data.domain.class_var if self.data.domain.has_discrete_class and self.class_selection != self.TARGET_AVERAGE: target_index = class_var.values.index(self.class_selection) else: class_var = None errors = [] has_missing_scores = False for key, slot in self.learners.items(): name = learner_name(slot.learner) head = QStandardItem(name) head.setData(key, Qt.UserRole) if isinstance(slot.results, Try.Fail): head.setToolTip(str(slot.results.exception)) head.setText("{} (error)".format(name)) head.setForeground(QtGui.QBrush(Qt.red)) errors.append( "{name} failed with error:\n" "{exc.__class__.__name__}: {exc!s}".format(name=name, exc=slot.results.exception) ) row = [head] if class_var is not None and class_var.is_discrete and target_index is not None: if slot.results is not None and slot.results.success: ovr_results = results_one_vs_rest(slot.results.value, target_index) stats = [Try(lambda: score(ovr_results)) for score in classification_stats.scores] else: stats = None else: stats = slot.stats if stats is not None: for stat in stats: item = QStandardItem() if stat.success: item.setText("{:.3f}".format(stat.value[0])) else: item.setToolTip(str(stat.exception)) has_missing_scores = True row.append(item) model.appendRow(row) self.error("\n".join(errors), shown=bool(errors)) self.Warning.scores_not_computed(shown=has_missing_scores)
def populateClients(self): row = 0 for client, settings in self.config['clients'].iteritems(): name = QStandardItem(client) name.setData(settings) path = QStandardItem(settings['path']) self.model.insertRow(row, [name, path]) row += 1
def _processProject(self, pr, parent, dbf): """process the project and add its child nodes""" for k, v in pr.items(): item = QStandardItem(k) item.setIcon(self.icons['sensorgroup']) item.setData(QVariant("G|%s|%s" % (dbf, v.path))) parent.appendRow(item) self._processSensorGroup(v, item, dbf)
def createItem(self, key, data, column): item = QStandardItem() item.setEditable(False) self.callItemInitializer(column, key, data, item) if item.data(self.SORT_ROLE) == None: item.setData(item.data(Qt.DisplayRole), self.SORT_ROLE) item.setData(key, self.KEY_ROLE) return item
def mkitem(self, d): """ dict with field->value """ si = QStandardItem() for k, v in d.items(): rid = self.roleids[k] si.setData(v, rid) return si
def addSensorgroup(self, project_mi, sg): """show a newly created or updated sensorgroup""" dbf = self.dsFolder(project_mi) item = QStandardItem(sg.name) item.setIcon(self.icons["sensorgroup"]) item.setData(QVariant("G|%s|%s" % (dbf, sg.path))) self.itemFromIndex(project_mi).appendRow(item) self._processSensorGroup(sg, item, dbf)
def row_for_state(self, score, state): items = [] attrs = sorted((self.attrs[x] for x in state), key=attrgetter("name")) for attr in attrs: item = QStandardItem(attr.name) item.setData(attr, self._AttrRole) items.append(item) return items
def _processDB(self, db, parent, dbf): """process the database and add its child nodes""" for k, v in db.items(): item = QStandardItem(k) item.setIcon(self.icons["project"]) item.setData(QVariant("P|%s|%s" % (dbf, v.path))) parent.appendRow(item) self._processProject(v, item, dbf)
def addParentItem(self, category): item = QStandardItem(category) item.setFlags(item.flags() & ~(Qt.ItemIsEnabled | Qt.ItemIsSelectable)) item.setData("parent", Qt.AccessibleDescriptionRole) font = item.font() font.setBold(True) item.setFont(font) self.model().appendRow(item)
def mkitem(self, d): """ dict with field->value """ si = QStandardItem() for k,v in d.items(): rid = self.roleids[k] si.setData(v, rid) return si
def update_model(self, model, schema, profile): """ Update the model by retrieving the profile given in database """ menudict = {} with self.transaction(): cur = self.connection.cursor() select = """ select name, profile, model_index, datasource_uri from {}.{} where profile = '{}' """.format(schema, self.table, profile) cur.execute(select) rows = cur.fetchall() model.clear() for name, profile, model_index, datasource_uri in self.sortby_modelindex( rows): menu = model.invisibleRootItem() indexes = json.loads(model_index) parent = '' for idx, subname in indexes[:-1]: parent += '{}-{}/'.format(idx, subname) if parent in menudict: # already created entry menu = menudict[parent] continue # create menu item = QStandardItem(subname) uri_struct = QgsMimeDataUtils.Uri(datasource_uri) item.setData(uri_struct) item.setIcon( QIcon(':/plugins/MenuBuilder/resources/menu.svg')) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDropEnabled | Qt.ItemIsEditable) item.setWhatsThis("menu") menu.appendRow(item) menudict[parent] = item # set current menu to the new created item menu = item # add leaf (layer item) item = QStandardItem(name) uri_struct = QgsMimeDataUtils.Uri(datasource_uri) # fix layer name instead of table name # usefull when the layer has been renamed in menu uri_struct.name = name if uri_struct.providerKey in ICON_MAPPER: item.setIcon(QIcon(ICON_MAPPER[uri_struct.providerKey])) item.setData(uri_struct) # avoid placing dragged layers on it item.setDropEnabled(False) if uri_struct.providerKey == 'postgres': # set tooltip to postgres comment comment = self.get_table_comment(uri_struct.uri) item.setToolTip(comment) menudict[parent].appendRow(item)
def addDatabase(self, folder): """add the database at folder to the model""" db = DataBaseRoot(folder) self.databases[folder] = db dbItem = QStandardItem(db.name) dbItem.setData(QVariant("R|%s" % folder)) dbItem.setIcon(self.icons["database"]) self.rootItem.appendRow(dbItem) self._processDB(db, dbItem, folder)
def addRow(self, song): attribs = song.getOptionalValues('%name%|'+self.radioConfig['prefered_informations']) nodes = [QStandardItem(x) for x in attribs] map(lambda x : x.setData(song), nodes) n = QStandardItem('') n.setData(song) nodes.insert(0, n) self.model().appendRow(nodes)
def add_parent_tree(self, icon, title): roots = OrderedDict() for feature_id in self.selected_features(): root = QStandardItem(icon, title) root.setData(feature_id) self.set_bold(root) self.model.appendRow(root) roots[feature_id] = root return roots
def _createActionItem(self, action): item = QStandardItem() item.setEditable(False) item.setData(action, self.ACTION_ROLE) item.setText(action.getName()) icon = action.getIcon() if icon is not None: item.setData(QVariant(icon), Qt.DecorationRole) return item
def RecentPath_asqstandarditem(pathitem): icon_provider = QFileIconProvider() # basename of a normalized name (strip right path component separators) basename = os.path.basename(os.path.normpath(pathitem.abspath)) item = QStandardItem(icon_provider.icon(QFileInfo(pathitem.abspath)), basename) item.setToolTip(pathitem.abspath) item.setData(pathitem, Qt.UserRole) return item
def update_model(self, model, schema, profile): """ Update the model by retrieving the profile given in database """ menudict = {} with self.transaction(): cur = self.connection.cursor() select = """ select name, profile, model_index, datasource_uri from {}.{} where profile = '{}' """.format(schema, self.table, profile) cur.execute(select) rows = cur.fetchall() model.clear() for name, profile, model_index, datasource_uri in self.sortby_modelindex(rows): menu = model.invisibleRootItem() indexes = json.loads(model_index) parent = '' for idx, subname in indexes[:-1]: parent += '{}-{}/'.format(idx, subname) if parent in menudict: # already created entry menu = menudict[parent] continue # create menu item = QStandardItem(subname) uri_struct = QgsMimeDataUtils.Uri(datasource_uri) item.setData(uri_struct) item.setIcon(QIcon(':/plugins/MenuBuilder/resources/menu.svg')) item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsDropEnabled | Qt.ItemIsEditable) item.setWhatsThis("menu") menu.appendRow(item) menudict[parent] = item # set current menu to the new created item menu = item # add leaf (layer item) item = QStandardItem(name) uri_struct = QgsMimeDataUtils.Uri(datasource_uri) # fix layer name instead of table name # usefull when the layer has been renamed in menu uri_struct.name = name if uri_struct.providerKey in ICON_MAPPER: item.setIcon(QIcon(ICON_MAPPER[uri_struct.providerKey])) item.setData(uri_struct) # avoid placing dragged layers on it item.setDropEnabled(False) if uri_struct.providerKey == 'postgres': # set tooltip to postgres comment comment = self.get_table_comment(uri_struct.uri) item.setToolTip(comment) menudict[parent].appendRow(item)
def add_STR_steam(self, parent, STR_id): str_icon = QIcon( ':/plugins/stdm/images/icons/social_tenure.png' ) title = 'Social Tenure Relationship' str_root = QStandardItem(str_icon, title) str_root.setData(STR_id) self.set_bold(str_root) parent.appendRow([str_root]) return str_root
def addRow(self, song): attribs = song.getOptionalValues( '%name%|' + self.radioConfig['prefered_informations']) nodes = [QStandardItem(x) for x in attribs] map(lambda x: x.setData(song), nodes) n = QStandardItem('') n.setData(song) nodes.insert(0, n) self.model().appendRow(nodes)
def addSingleItem(self, iname, val=None): if not val: val = iname if val not in self._items: self._items.append(val) idx = len(self._items) - 1 item = QStandardItem(iname) item.setData(idx, Qt.UserRole) self.model().insertRow(0, [item]) self.setCurrentIndex(0)
def addChart(self, chart, mi): """add a new chart to sensorgroup item at mi""" t, sensorgroup = self.dsNode(mi) if not chart.name in sensorgroup.charts: sensorgroup.addChart(chart) sensorgroup.flush() chItem = QStandardItem(chart.name) chItem.setIcon(self.icons["graph"]) chItem.setData(QVariant("C|%s|%s|%s" % (self.dsFolder(mi), sensorgroup.path, chart.name))) self.itemFromIndex(mi).appendRow(chItem)
def _update(self): # Update the displayed confusion matrix if self.results is not None and self.selected_learner: index = self.selected_learner[0] cmatrix = confusion_matrix(self.results, index) colsum = cmatrix.sum(axis=0) rowsum = cmatrix.sum(axis=1) total = rowsum.sum() if self.selected_quantity == 0: value = lambda i, j: int(cmatrix[i, j]) elif self.selected_quantity == 1: priors = numpy.outer(rowsum, colsum) / total value = lambda i, j: \ "{} / {:5.3f}".format(cmatrix[i, j], priors[i, j]) elif self.selected_quantity == 2: value = lambda i, j: \ ("{:2.1f} %".format(100 * cmatrix[i, j] / colsum[i]) if colsum[i] else "N/A") elif self.selected_quantity == 3: value = lambda i, j: \ ("{:2.1f} %".format(100 * cmatrix[i, j] / rowsum[i]) if colsum[i] else "N/A") else: assert False model = self.tablemodel for i, row in enumerate(cmatrix): for j, _ in enumerate(row): item = model.item(i, j) if item is None: item = QStandardItem() item.setData(value(i, j), Qt.DisplayRole) item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter) item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable) model.setItem(i, j, item) font = model.invisibleRootItem().font() bold_font = QFont(font) bold_font.setBold(True) def sum_item(value): item = QStandardItem() item.setData(value, Qt.DisplayRole) item.setTextAlignment(Qt.AlignRight | Qt.AlignVCenter) item.setFlags(Qt.ItemIsEnabled) item.setFont(bold_font) return item N = len(colsum) for i in range(N): model.setItem(N, i, sum_item(int(colsum[i]))) model.setItem(i, N, sum_item(int(rowsum[i]))) model.setItem(N, N, sum_item(int(total)))
def addChildItem(self, iname, val=None): if val is None: val = iname if val not in self._items: self._items.append(val) idx = len(self._items) - 1 item = QStandardItem(iname) item.setData("child", Qt.AccessibleDescriptionRole) item.setData(idx, Qt.UserRole) self.model().appendRow(item) self.setCurrentItem()
def add_party_steam(self, parent, party_id): party_icon = QIcon( ':/plugins/stdm/images/icons/table.png' ) title = format_name(self.party.short_name) party_root = QStandardItem(party_icon, title) party_root.setData(party_id) self.set_bold(party_root) parent.appendRow([party_root]) party_root.setEditable(False) return party_root
def populateTreeOLD(self, disco): # Get all attributes from first song if len(disco) < 1: attribs = {} else: attribs = disco[0].getOptionalValues(self.comm) length = len(attribs) if length > 0: # Create corresponding nodes nodes = [] for i in attribs: nodes.append(QStandardItem(i)) # Add them to each other for i in range(1, length): nodes[i - 1].appendRow(nodes[i]) # Add data to the last one nodes[length - 1].setData(disco[0]) # Append to tree self.model().appendRow(nodes[0]) else: #Create corresponding nodes nodes = [QStandardItem('Nothing')] nodes[0].setData('nothing') self.model().appendRow(nodes[0]) #Pour la tail de la liste for s in disco[1:]: attr = s.getOptionalValues(self.comm) length = len(attr) #First attribut separated because attached to node if attr[0] != attribs[0]: node = QStandardItem(attr[0]) #self.model().appendRow(node) nodes[0] = node self.model().appendRow(nodes[0]) attribs[0] = attr[0] for i in range(1, length - 1): if (attr[i] != attribs[i]): # or differ: node = QStandardItem(attr[i]) nodes[i - 1].appendRow(node) if i < len(nodes): nodes[i] = node else: nodes.append(node) attribs[i] = attr[i] #Dernier attribut node = QStandardItem(attr[length - 1]) nodes[length - 2].appendRow(node) node.setData(s)
def requestUrl(self, action): url = action.data().toString() settings = self.settings settings.beginGroup(settings.keys.main) useExternal = settings.value('useSystemBrowser', False).toBool() settings.endGroup() if useExternal: QDesktopServices.openUrl(QUrl(url)) else: item = QStandardItem(url) item.setData(QVariant(url), DataRoles.url) item.setData(QVariant(action.toolTip()), DataRoles.urlTitle) item.setIcon(action.icon()) self.emit(Signals.openUrl, item)
def populate_value_list_view(self): """ Populates the lookup values and codes. """ self.value_and_code = self.lookup_entity.values for value, code in self.value_and_code.iteritems(): u_value = unicode(value) code_value = self.lookup_entity.values[u_value] value_code = QStandardItem('{} ({})'.format( code_value.value, code.code)) value_code.setData(code.code) self._view_model.appendRow(value_code)
def createRootItems(self): # Add Root children items (bookmarks, logical etc.) self.root_item = self.invisibleRootItem() self.root_node = self.VFS.GetNode("/") tmp = self.root_node.children() item_list = [] for i in tmp: node_item = QStandardItem(i.name()) node_item.setData(QVariant(long(i.this)), Qt.UserRole + 1) node_item.setData(QVariant(False), Qt.UserRole + 2) item_list.append(node_item) self.indexmap[long(i.this)] = node_item if len(item_list): self.root_item.appendRows(item_list)
def __init__(self, engine, gui_parent, parent=None): """ Constructor @param parent reference to the parent widget (QWidget) """ super().__init__(parent) self.setupUi(self) self.setWindowTitle("Enregistrement d'une formation") self.engine = engine self.dateEdit.setDate(pendulum.now('Europe/Paris')) self.cmr_bdd = Bdd_Cmr(self.engine) gen_cmr = self.cmr_bdd.recup_cmr_en_activite() self.remplir_tableau_cmr(next(gen_cmr)) # self.threadpool = QThreadPool() self.gui_parent = gui_parent ####Threads self.thread_finish = False # self.affectation_lancement_threads() init_domaine = Insertion_Domaine(self.engine) areas = init_domaine.recuperation_domaine() # print(areas) self.model = QStandardItemModel((len(areas) + 1), 1) # 5 rows, 1 col firstItem = QStandardItem("---- Select domaine(s) ----") firstItem.setBackground(QBrush(QColor(200, 200, 200))) firstItem.setSelectable(False) self.model.setItem(0, 0, firstItem) for i, area in enumerate(areas): item = QStandardItem(area) item.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled) item.setData(Qt.Unchecked, Qt.CheckStateRole) self.model.setItem(i + 1, 0, item) self.comboBox_domaine.setModel(self.model) self.gui_parent.formation_a_modifier.connect( self.reaffectation_formation)
def refreshmodel(self, data_in): "Fill the frontend with rules data" rawstr = unicode(QString.fromUtf8(data_in)) export_list = [] rules = rawstr[len('RULES_LIST'):].split('CRLF') for one_rule in rules: split_rule = one_rule.split() if len(split_rule) != 5: continue export_list.append(split_rule) export_list.append("EOF") ruleslist = export_list #empty the model, we're filling it anew, we can't use clear() cause it flushes headers too: modellock.acquire() self.sourcemodel.layoutAboutToBeChanged.emit() self.sourcemodel.removeRows(0, self.sourcemodel.rowCount()) #if there's only one element, it's EOF; dont go through iterations,just leave the model empty if (len(ruleslist) == 1): self.sourcemodel.layoutChanged.emit() modellock.release() return for item in ruleslist[0:-1]: #leave out the last EOF from iteration path_u = b64decode(item[0]).decode('utf-8') fullpath = QStandardItem(path_u) #item[4] contains nfmark fullpath.setData(item[4]) if (item[1] == "0"): pid_string = "N/A" else: pid_string = item[1] pid = QStandardItem(pid_string) perms = QStandardItem(item[2]) #only the name of the executable after the last / m_list = string.rsplit(path_u, "/", 1) m_name = m_list[1] name = QStandardItem(m_name) in_allow_traf = QStandardItem() out_allow_traf = QStandardItem() in_deny_traf = QStandardItem() out_deny_traf = QStandardItem() self.sourcemodel.appendRow( (name, pid, perms, fullpath, in_allow_traf, out_allow_traf, in_deny_traf, out_deny_traf)) #print "Received: %s" %(item[0]) self.sourcemodel.layoutChanged.emit() modellock.release() self.update_bytestats()