def refresh_databases(self): QApplication.setOverrideCursor(Qt.WaitCursor) if self.clouddb: db_list = self.api.read_databases() if self.show_api_error(db_list): QApplication.restoreOverrideCursor() return self.db_connections = DbConnections() for db in db_list: self.db_connections.add_from_json(db) self.ui.tabDatabases.clear() self.ui.btnDbDelete.setEnabled(False) self.ui.cbUploadDatabase.clear() self.ui.cbUploadDatabase.setEditable(True) self.ui.cbUploadDatabase.lineEdit().setReadOnly(True) if self.db_connections.count() == 0: self.ui.cbUploadDatabase.setEditText(self.tr("No databases")) else: for name, db in list(self.db_connections.iteritems()): it = QListWidgetItem(name) it.setToolTip(db.description()) self.ui.tabDatabases.addItem(it) self.ui.cbUploadDatabase.addItem(name) if self.ui.cbUploadDatabase.count() > 1: # Display the "Select database" text if more than one db is available self.ui.cbUploadDatabase.setCurrentIndex(-1) self.ui.cbUploadDatabase.setEditText(self.tr("Select database")) self.db_connections.refresh(self.user) self.db_size(self.db_connections) QApplication.restoreOverrideCursor()
def _populate_list(self): self.__list.clear() for cfg in self.__config_list: if cfg["type"] in ("cumulative", "instantaneous"): # check number of features for this station if cfg.get("feature_filter_type") == "unique_data_from_values": # get unique filter values layerid = cfg["source"] data_l = QgsProject.instance().mapLayers()[layerid] values = set() for feature in self.__features: feature_id = feature[self.__config["id_column"]] req = QgsFeatureRequest() req.setFilterExpression("{}={}".format( cfg["feature_ref_column"], feature_id)) values.update([ f[cfg["feature_filter_column"]] for f in data_l.getFeatures(req) ]) cfg.set_filter_unique_values(sorted(list(values))) item = QListWidgetItem(cfg["name"]) item.setData(Qt.UserRole, cfg) self.__list.addItem(item)
def refresh_databases(self): QApplication.setOverrideCursor(Qt.WaitCursor) if self.clouddb: db_list = self.api.read_databases() if self.show_api_error(db_list): QApplication.restoreOverrideCursor() return self.db_connections = DbConnections() for db in db_list: self.db_connections.add_from_json(db) self.ui.tabDatabases.clear() self.ui.btnDbDelete.setEnabled(False) self.ui.cbUploadDatabase.clear() self.ui.cbUploadDatabase.setEditable(True) self.ui.cbUploadDatabase.lineEdit().setReadOnly(True) if self.db_connections.count() == 0: self.ui.cbUploadDatabase.setEditText(self.tr("No databases")) else: for name, db in list(self.db_connections.iteritems()): it = QListWidgetItem(name) it.setToolTip(db.description()) self.ui.tabDatabases.addItem(it) self.ui.cbUploadDatabase.addItem(name) if self.ui.cbUploadDatabase.count() > 1: # Display the "Select database" text if more than one db is available self.ui.cbUploadDatabase.setCurrentIndex(-1) self.ui.cbUploadDatabase.setEditText(self.tr("Select database")) self.db_connections.refresh(self.user) self.db_size(self.db_connections) QApplication.restoreOverrideCursor()
def set_widgets(self): """Set widgets on the Hazard Category tab.""" self.clear_further_steps() # Set widgets self.lstHazardCategories.clear() self.lblDescribeHazardCategory.setText('') self.lblSelectHazardCategory.setText(hazard_category_question) hazard_categories = self.hazard_categories_for_layer() for hazard_category in hazard_categories: if not isinstance(hazard_category, dict): # noinspection PyTypeChecker hazard_category = definition(hazard_category) # noinspection PyTypeChecker item = QListWidgetItem(hazard_category['name'], self.lstHazardCategories) # noinspection PyTypeChecker item.setData(QtCore.Qt.UserRole, hazard_category['key']) self.lstHazardCategories.addItem(item) # Set values based on existing keywords (if already assigned) category_keyword = self.parent.get_existing_keyword('hazard_category') if category_keyword: categories = [] for index in range(self.lstHazardCategories.count()): item = self.lstHazardCategories.item(index) categories.append(item.data(QtCore.Qt.UserRole)) if category_keyword in categories: self.lstHazardCategories.setCurrentRow( categories.index(category_keyword)) self.auto_select_one_item(self.lstHazardCategories)
def feel_list(self): self.lstGroups.clear() ds_groups = GroupsList(USER_GROUP_PATHS) for ds_group in ds_groups.groups.values(): item = QListWidgetItem(QIcon(ds_group.icon), self.tr(ds_group.alias)) item.setData(Qt.UserRole, ds_group) self.lstGroups.addItem(item)
def validate(self): self.layerList.setTitle('Layers') data_source = self.gmlas_datasource() if data_source is None: QMessageBox.critical( self, plugin_name(), self.tr('Failed to open file using OGR GMLAS driver')) return ogrMetadataLayerPrefix = '_ogr_' self.datasetsListWidget.clear() for i in range(0, data_source.GetLayerCount()): layer = data_source.GetLayer(i) layer_name = layer.GetName() if not layer_name.startswith(ogrMetadataLayerPrefix): feature_count = layer.GetFeatureCount() item = QListWidgetItem("{} ({})".format( layer_name, feature_count)) item.setData(Qt.UserRole, layer_name) self.datasetsListWidget.addItem(item) self.datasetsListWidget.sortItems() self.datasetsListWidget.selectAll() self.layerList.setTitle('{} layer(s) found:'.format( self.datasetsListWidget.count()))
def addServerItem(self, server): widget = ServerItemWidget(server) item = QListWidgetItem(self.listServers) item.setSizeHint(widget.sizeHint()) self.listServers.addItem(item) self.listServers.setItemWidget(item, widget) return item
def add_route_item_to_list_widget(self, route): pollutant_types = list(self.planner.pollutants.keys()) distance = route.distance / 1000 hours, minutes = divmod(route.minutes, 60) hours = int(hours) minutes = int(minutes) myQCustomQWidget = TheWidgetItem() myQCustomQWidget.set_route_name("Route{}".format(route.id + 1), self.color_list[route.id]) myQCustomQWidget.set_route_id(route.id) myQCustomQWidget.set_distance_time( "{} km".format(distance), "{} hours and {} minutes.".format(hours, minutes)) myQCustomQWidget.hide_all_lbl_pollutants() for idxPlt, pt in enumerate(pollutant_types): myQCustomQWidget.set_pollutants(idxPlt, pt, round(route.total_emission(pt), 2)) myQListWidgetItem = QListWidgetItem(self.dlg.listWidget) myQListWidgetItem.setSizeHint(myQCustomQWidget.sizeHint()) self.dlg.listWidget.addItem(myQListWidgetItem) self.dlg.listWidget.setItemWidget(myQListWidgetItem, myQCustomQWidget) self.dlg.listWidget.setStyleSheet(""" QListWidget:item:selected:active { background-color:rgb(230, 230, 230); }""")
def set_widgets(self): """Set widgets on the Hazard Category tab.""" self.clear_further_steps() # Set widgets self.lstHazardCategories.clear() self.lblDescribeHazardCategory.setText('') self.lblSelectHazardCategory.setText( hazard_category_question) hazard_categories = self.hazard_categories_for_layer() for hazard_category in hazard_categories: if not isinstance(hazard_category, dict): # noinspection PyTypeChecker hazard_category = definition(hazard_category) # noinspection PyTypeChecker item = QListWidgetItem( hazard_category['name'], self.lstHazardCategories) # noinspection PyTypeChecker item.setData(QtCore.Qt.UserRole, hazard_category['key']) self.lstHazardCategories.addItem(item) # Set values based on existing keywords (if already assigned) category_keyword = self.parent.get_existing_keyword('hazard_category') if category_keyword: categories = [] for index in range(self.lstHazardCategories.count()): item = self.lstHazardCategories.item(index) categories.append(item.data(QtCore.Qt.UserRole)) if category_keyword in categories: self.lstHazardCategories.setCurrentRow( categories.index(category_keyword)) self.auto_select_one_item(self.lstHazardCategories)
def feel_list(self): self.lstServices.clear() ds_list = DataSourcesList(USER_DS_PATHS) for ds in ds_list.data_sources.values(): item = QListWidgetItem(ds.action.icon(), ds.action.text()) item.setData(Qt.UserRole, ds) self.lstServices.addItem(item)
def __init__(self, commit, repo, path): QListWidgetItem.__init__(self) self.commit = commit self._feature = None self.repo = repo self.path = path self.setText("%s (by %s)" % (commit.message.splitlines()[0], commit.authorname))
def set_widgets(self): """Set widgets on the Classification tab.""" self.clear_further_steps() purpose = self.parent.step_kw_purpose.selected_purpose()['name'] subcategory = self.parent.step_kw_subcategory.\ selected_subcategory()['name'] self.lstClassifications.clear() self.lblDescribeClassification.setText('') self.lblSelectClassification.setText( classification_question % (subcategory, purpose)) classifications = self.classifications_for_layer() for classification in classifications: if not isinstance(classification, dict): classification = definition(classification) item = QListWidgetItem( classification['name'], self.lstClassifications) item.setData(QtCore.Qt.UserRole, classification['key']) self.lstClassifications.addItem(item) # Set values based on existing keywords (if already assigned) classification_keyword = self.parent.get_existing_keyword( 'classification') if classification_keyword: classifications = [] for index in range(self.lstClassifications.count()): item = self.lstClassifications.item(index) classifications.append(item.data(QtCore.Qt.UserRole)) if classification_keyword in classifications: self.lstClassifications.setCurrentRow( classifications.index(classification_keyword)) self.auto_select_one_item(self.lstClassifications)
def set_widgets(self): """Set widgets on the Classification tab.""" self.clear_further_steps() purpose = self.parent.step_kw_purpose.selected_purpose()['name'] subcategory = self.parent.step_kw_subcategory.\ selected_subcategory()['name'] self.lstClassifications.clear() self.lblDescribeClassification.setText('') self.lblSelectClassification.setText( classification_question % (subcategory, purpose)) classifications = self.classifications_for_layer() for classification in classifications: if not isinstance(classification, dict): classification = definition(classification) item = QListWidgetItem( classification['name'], self.lstClassifications) item.setData(QtCore.Qt.UserRole, classification['key']) self.lstClassifications.addItem(item) # Set values based on existing keywords (if already assigned) classification_keyword = self.parent.get_existing_keyword( 'classification') if classification_keyword: classifications = [] for index in range(self.lstClassifications.count()): item = self.lstClassifications.item(index) classifications.append(item.data(QtCore.Qt.UserRole)) if classification_keyword in classifications: self.lstClassifications.setCurrentRow( classifications.index(classification_keyword)) self.auto_select_one_item(self.lstClassifications)
def createCellWidget(self, qmlDict, attr, count): """ Creates specific widgets for each attribute, which can be a QCombobox, a QLineEdit or a QListWidget. """ if attr in qmlDict: enableIgnoreOption = False #case the type is dict the cell widget must be a combobox if isinstance(qmlDict[attr],dict): comboItem = DsgCustomComboBox() comboItem.addItems(sorted(qmlDict[attr].keys())) self.attributeTableWidget.setCellWidget(count, 1, comboItem) #case the type is tuple the cell widget must be a listwidget if isinstance(qmlDict[attr],tuple): (table, filterKeys) = qmlDict[attr] #getting the value relation dictionary used to make the listwidget valueRelation = self.makeValueRelationDict(table, filterKeys) list = QListWidget() for key in list(valueRelation.keys()): listItem = QListWidgetItem(key) listItem.setCheckState(Qt.Unchecked) list.addItem(listItem) self.attributeTableWidget.setCellWidget(count, 1, list) #this is the normal case, a simple lineedit else: textItem = QLineEdit() self.attributeTableWidget.setCellWidget(count, 1, textItem) enableIgnoreOption = True #insert here aditional parameters self.createAditionalParameters(count, enableIgnoreOption)
def validate(self): #self.layerList.setTitle('Layers') data_source = self.gmlas_datasource() if data_source is None: QMessageBox.critical(self, plugin_name(), self.tr('Failed to open file using OGR GMLAS driver')) return ogrMetadataLayerPrefix = '_ogr_' self.datasetsListWidget.clear() for i in range(0, data_source.GetLayerCount()): layer = data_source.GetLayer(i) layer_name = layer.GetName() if not layer_name.startswith(ogrMetadataLayerPrefix): feature_count = layer.GetFeatureCount() item = QListWidgetItem("{} ({})".format(layer_name, feature_count)) item.setData(Qt.UserRole, layer_name) self.datasetsListWidget.addItem(item) self.datasetsListWidget.sortItems() self.datasetsListWidget.selectAll()
def addLayerListItem(self, layer): widget = LayerItemWidget(layer) item = QListWidgetItem(self.listLayers) item.setSizeHint(widget.sizeHint()) self.listLayers.addItem(item) self.listLayers.setItemWidget(item, widget) return item
def feel_list(self): self.lstServices.clear() ds_list = DataSourcesList(USER_DS_PATHS) for ds in ds_list.data_sources.values(): item = QListWidgetItem(ds.action.icon(), ds.action.text()) item.setData(Qt.UserRole, ds) self.lstServices.addItem(item)
def _populate_list(self): self.__list.clear() for cfg in self.__config_list: if cfg["type"] in ("continuous", "instantaneous"): uri, provider = cfg["source"] # check number of features for this station data_l = QgsVectorLayer(uri, "data_layer", provider) req = QgsFeatureRequest() req.setFilterExpression("{}={}".format( cfg["feature_ref_column"], self.__feature_id)) if len(list(data_l.getFeatures(req))) == 0: continue if cfg.get("feature_filter_type") == "unique_data_from_values": # get unique filter values cfg["filter_unique_values"] = sorted( list( set([ f[cfg["feature_filter_column"]] for f in data_l.getFeatures(req) ]))) elif cfg["type"] == "image": if not self.__viewer.has_imagery_data(cfg, self.__feature_id): continue item = QListWidgetItem(cfg["name"]) item.setData(Qt.UserRole, cfg) self.__list.addItem(item)
def addServerItem(self, server): widget = ServerItemWidget(server) item = QListWidgetItem(self.listServers) item.setSizeHint(widget.sizeHint()) self.listServers.addItem(item) self.listServers.setItemWidget(item, widget) self.checkServersHaveBeenDefined() return item
def add_item(self, title, icon): """ Add item to the dialog's list of options """ item = QListWidgetItem(title) item.setIcon(QIcon(icon)) self.dlg.uListOptions.addItem(item)
def updateManaged(self): self.mManagedLayers.clear() for layer in managed_layers(): item = QListWidgetItem(layer.name()) item.setData(Qt.UserRole, layer.id()) self.mManagedLayers.addItem(item)
def createItems(self, widget, names): """ Create items """ for name in names: item = QListWidgetItem(widget) text = name.split(os.sep)[-1] item.setText(text)
def feel_list(self): self.lstGroups.clear() ds_groups = GroupsList(USER_GROUP_PATHS) for ds_group in ds_groups.groups.values(): item = QListWidgetItem(QIcon(ds_group.icon), self.tr(ds_group.alias)) item.setData(Qt.UserRole, ds_group) self.lstGroups.addItem(item)
def __init__(self, commit, repo, path): QListWidgetItem.__init__(self) self.commit = commit self._feature = None self.repo = repo self.path = path self.setText("%s (by %s)" % (commit.message.splitlines()[0], commit.authorname))
def add_error_to_list_widget(self, error_msg): myQCustomErrorQWidget = ErrorWidgetItem() myQCustomErrorQWidget.set_error_msg("Error: {}".format(error_msg)) myQListWidgetItem = QListWidgetItem(self.dlg.listWidget) myQListWidgetItem.setSizeHint(myQCustomErrorQWidget.sizeHint()) self.dlg.listWidget.addItem(myQListWidgetItem) self.dlg.listWidget.setItemWidget(myQListWidgetItem, myQCustomErrorQWidget) self.planner = None
def loadSourceTables(self): # Load all STDM tables self.lstSrcTab.clear() # tables = pg_tables() tables = profile_user_tables(self.curr_profile, True, True, sort=True) for t in tables.keys(): tabItem = QListWidgetItem(t, self.lstSrcTab) tabItem.setIcon(GuiUtils.get_icon("table.png")) self.lstSrcTab.addItem(tabItem)
def rename_query(self, query: QListWidgetItem): """Rename a query in the preset""" input_dialog = QInputDialog(self) new_name = input_dialog.getText( self, tr("Rename the query"), tr("New name:"), text=query.text()) if new_name[1] and new_name[0]: query.setText(new_name[0].replace(' ', '_')) self.update_qml_format()
def __init__(self, commit, geogiglayer, fid): QListWidgetItem.__init__(self) self.commit = commit self._feature = None self.geogiglayer = geogiglayer self.fid = fid self.setText( "%s (by %s)" % (commit["message"].splitlines()[0], commit["author"]["name"]))
def _add_target_table_columns(self, items, style=False): for item in items: list_item = QListWidgetItem(item) if style: color = QColor(0, 128, 255) list_item.setTextColor(color) self.lstTargetFields.addItem(list_item)
def load_sample(self, sample): self.list_attribute.clear() for element in sample: _, v = list(element.items())[0] item = QListWidgetItem() item.setText(str(v)) self.list_attribute.addItem(item)
def filterPublicLayers(self): self.publicWebMapsList.clear() filter = self.filterText.text() for idx, public_layers in enumerate(self.public_db_keys): if "layer_name" in public_layers: if len(filter) < 3 or public_layers["layer_name"].find( filter) != -1 or public_layers["id"].find( filter) != -1: listItem = QListWidgetItem(public_layers["layer_name"]) listItem.setData(Qt.UserRole, idx) self.publicWebMapsList.addItem(listItem)
def __init__(self, commit): QListWidgetItem.__init__(self) self.commit = commit epoch = time.mktime(commit.committerdate.timetuple()) offset = datetime.datetime.fromtimestamp( epoch) - datetime.datetime.utcfromtimestamp(epoch) d = commit.committerdate + offset self.setText( "%s %s" % (d.strftime("[%m/%d/%y %H:%M]"), commit.message.splitlines()[0])) self.setIcon(self.icon)
def populate_entities_widget(self): """ Add entities in the instance file into a list view widget """ self.lst_widget.clear() entities = self.instance_entities() if len(entities) > 0: for entity in entities: list_widget = QListWidgetItem( current_profile().entity_by_name(entity).short_name, self.lst_widget) list_widget.setCheckState(Qt.Checked)
def on_loadTypesPushButton_clicked(self): LOGGER.info("CLicked") self.listWidget.clear() wfs = self.wfsPathLineEdit.text() self.converter = KuntaGML2Layers(wfs, '2.1.6', '2.1.1', '1.1.0') self.converter.populate_features() for f_type in self.converter.feature_types: item = QListWidgetItem(f_type) item.setFlags(item.flags() | Qt.ItemIsUserCheckable) self.listWidget.addItem(item)
def update_history_view(self): """Update the history view.""" historic_folder = query_historic() files = os.listdir(historic_folder) self.dialog.list_historic.clear() for file in files[::-1]: file_path = join(historic_folder, file) with open(file_path, encoding='utf8') as json_file: data = json.load(json_file, object_hook=as_enum) name = data['file_name'] item = QListWidgetItem(self.dialog.list_historic) self.dialog.list_historic.addItem(item) group = QFrame() group.setFrameStyle(QFrame.StyledPanel) group.setStyleSheet('QFrame { margin: 3px; }') group.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) hbox = QHBoxLayout() vbox = QVBoxLayout() label_name = QLabel(name) label_name.setStyleSheet('font-weight: bold;') label_name.setWordWrap(True) vbox.addWidget(label_name) for label in data['description']: if not label: label = tr('No description') real_label = QLabel(label) real_label.setWordWrap(True) vbox.addWidget(real_label) hbox.addItem(vbox) button_run = QPushButton() button_save = QPushButton() button_run.setIcon(QIcon(QgsApplication.iconPath("mActionStart.svg"))) button_save.setIcon(QIcon(QgsApplication.iconPath("mActionFileSave.svg"))) button_run.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) button_save.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) button_run.setToolTip(tr('Run the query')) button_save.setToolTip(tr('Save this query in a new preset')) hbox.addWidget(button_run) hbox.addWidget(button_save) group.setLayout(hbox) # Actions on click run = partial(self.run_saved_query, data) button_run.clicked.connect(run) save = partial(self.save_history_preset, data) button_save.clicked.connect(save) item.setSizeHint(group.minimumSizeHint()) self.dialog.list_historic.setItemWidget(item, group)
def update_lists(self, only_update_all_list=False): """ Update left list widget and optionally the right one. :param only_update_all_list: Only update left list widget. :type only_update_all_list: bool """ # All parties self.lst_all_parties.clear() if self.txt_search_party.text(): tmp_parties = { i: d for i, d in self.data.items() if self.txt_search_party.text().lower() in d[0].lower() } else: tmp_parties = copy.deepcopy(self.data) # Copy all! for party_id in self.current_selected_parties: if party_id in tmp_parties: del tmp_parties[party_id] for i, d in tmp_parties.items(): item = QListWidgetItem(d[0]) item.setData(Qt.UserRole, i) self.lst_all_parties.addItem(item) if not only_update_all_list: # Selected parties self.tbl_selected_parties.clearContents() self.tbl_selected_parties.setRowCount( len(self.current_selected_parties)) self.tbl_selected_parties.setColumnCount(3) self.tbl_selected_parties.setSortingEnabled(False) for row, party_id in enumerate(self.current_selected_parties): item = QTableWidgetItem(self.data[party_id][0]) item.setFlags(item.flags() & ~Qt.ItemIsEditable) item.setData(Qt.UserRole, party_id) self.tbl_selected_parties.setItem(row, 0, item) value_denominator = self.parties_to_group[party_id][ 0] if party_id in self.parties_to_group else self.data[ party_id][1] self.tbl_selected_parties.setItem( row, 1, QTableWidgetItem(str(value_denominator))) value_numerator = self.parties_to_group[party_id][ 1] if party_id in self.parties_to_group else self.data[ party_id][2] self.tbl_selected_parties.setItem( row, 2, QTableWidgetItem(str(value_numerator))) self.tbl_selected_parties.setSortingEnabled(True)
def createEditor(self, parent, option, index): """ Creates a custom editor to edit value relation data """ # special combobox for field type if index.column() == self.column: list = QListWidget(parent) for item in self.itemsDict: listItem = QListWidgetItem(item) listItem.setCheckState(Qt.Unchecked) list.addItem(listItem) return list return QItemDelegate.createEditor(self, parent, option, index)
def set_widgets(self): """Set widgets on the LayerMode tab.""" self.clear_further_steps() # Set widgets purpose = self.parent.step_kw_purpose.selected_purpose() subcategory = self.parent.step_kw_subcategory.selected_subcategory() layer_mode_question = ( layer_mode_raster_question if is_raster_layer(self.parent.layer) else layer_mode_vector_question) self.lblDescribeLayerMode.setText('') self.lstLayerModes.clear() layer_modes = get_layer_modes(subcategory['key']) if is_raster_layer(self.parent.layer): layer_mode_question = layer_mode_raster_question else: if len(layer_modes) == 2: layer_mode_question = layer_mode_vector_question elif len(layer_modes) == 1: if layer_modes[0]['key'] == 'classified': layer_mode_question = layer_mode_vector_classified_confirm elif layer_modes[0]['key'] == 'continuous': layer_mode_question = layer_mode_vector_continuous_confirm else: layer_mode_question = layer_mode_vector_question self.lblSelectLayerMode.setText( layer_mode_question % (subcategory['name'], purpose['name'])) for layer_mode in layer_modes: item = QListWidgetItem(layer_mode['name'], self.lstLayerModes) item.setData(QtCore.Qt.UserRole, layer_mode['key']) self.lstLayerModes.addItem(item) # Set value to existing keyword or default value layer_mode_keys = [m['key'] for m in layer_modes] layer_mode_keyword = self.parent.get_existing_keyword('layer_mode') if layer_mode_keyword in layer_mode_keys: index = layer_mode_keys.index(layer_mode_keyword) elif layer_mode_continuous['key'] in layer_mode_keys: # Set default value index = layer_mode_keys.index(layer_mode_continuous['key']) else: index = -1 self.lstLayerModes.setCurrentRow(index) self.auto_select_one_item(self.lstLayerModes)
def setList(self, options): self.options = options self.listWidget.clear() entries = QgsRasterCalculatorEntry.rasterEntries() def _find_source(name): for entry in entries: if entry.ref == name: return entry.raster.source() return '' for name in options.keys(): item = QListWidgetItem(name, self.listWidget) tooltip = _find_source(name) if tooltip: item.setData(Qt.ToolTipRole, tooltip) self.listWidget.addItem(item)
def list_compatible_canvas_layers(self): """Fill the list widget with compatible layers. :returns: Metadata of found layers. :rtype: list of dicts """ italic_font = QFont() italic_font.setItalic(True) list_widget = self.lstCanvasExpLayers # Add compatible layers list_widget.clear() for layer in self.parent.get_compatible_canvas_layers('exposure'): item = QListWidgetItem(layer['name'], list_widget) item.setData(Qt.UserRole, layer['id']) if not layer['keywords']: item.setFont(italic_font) list_widget.addItem(item)
def getNewCompo(self, w, cView): """Function that finds new layout to be added to the list.""" nameCompo = cView.name() if not w.findItems(nameCompo, Qt.MatchExactly): item = QListWidgetItem() item.setFlags(item.flags() | Qt.ItemIsUserCheckable) item.setCheckState(Qt.Unchecked) item.setText(nameCompo) w.addItem(item)
def populate_field_list(self, excluded_fields=None): """Helper to add field of the layer to the list. :param excluded_fields: List of field that want to be excluded. :type excluded_fields: list """ # Populate fields list if excluded_fields is None: excluded_fields = [] self.field_list.clear() for field in self.layer.fields(): # Skip if it's excluded if field.name() in excluded_fields: continue # Skip if it's not number (float, int, etc) if field.type() not in qvariant_numbers: continue field_item = QListWidgetItem(self.field_list) field_item.setFlags( Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled) field_item.setData(Qt.UserRole, field.name()) field_item.setText(field.name()) self.field_list.addItem(field_item)
def refresh_maps(self): QApplication.setOverrideCursor(Qt.WaitCursor) if self.clouddb: map_list = self.api.read_maps() if self.show_api_error(map_list): QApplication.restoreOverrideCursor() return self.ui.tabMaps.clear() self.ui.btnMapDelete.setEnabled(False) self.ui.btnMapLoad.setEnabled(False) for map in map_list: it = QListWidgetItem(map['map']['name']) self.ui.tabMaps.addItem(it) it.setData(Qt.UserRole, map['map']['id']) QApplication.restoreOverrideCursor()
def __addPolygonsToGui(self): self.ui.IDC_listPolygons.clear() self.ui.cmbCadastreLayer.clear() check = Qt.Unchecked for poly_lyr in self.settings.mapData.polygons.polygons(): item = QListWidgetItem(poly_lyr.name) item.setData(Qt.UserRole, poly_lyr) item.setFlags(item.flags() | Qt.ItemIsUserCheckable) item.setCheckState(check) self.ui.IDC_listPolygons.addItem(item) self.ui.cmbCadastreLayer.addItem(poly_lyr.name, poly_lyr.id)
def show_error(self, error_text): self.lstSearchResult.clear() new_widget = QLabel() new_widget.setTextFormat(Qt.RichText) new_widget.setOpenExternalLinks(True) new_widget.setWordWrap(True) new_widget.setText( u"<div align='center'> <strong>{}</strong> </div><div align='center' style='margin-top: 3px'> {} </div>".format( self.tr('Error'), error_text ) ) new_item = QListWidgetItem(self.lstSearchResult) new_item.setSizeHint(new_widget.sizeHint()) self.lstSearchResult.addItem(new_item) self.lstSearchResult.setItemWidget( new_item, new_widget )
def __addRastersToGui(self): self.ui.IDC_listRasters.clear() check = Qt.Unchecked if self.settings.mapData.rasters.count() == 1: check = Qt.Checked self.settings.mapData.rasters.rasters()[0].selected = True for raster_lyr in self.settings.mapData.rasters.rasters(): item = QListWidgetItem(raster_lyr.name) item.setData(Qt.UserRole, raster_lyr) item.setFlags(item.flags() | Qt.ItemIsUserCheckable) item.setCheckState(check) self.ui.IDC_listRasters.addItem(item)
def set_widgets(self): """Set widgets on the LayerMode tab.""" self.clear_further_steps() # Set widgets self.lblBandSelector.setText(tr( 'Please select which band that contains the data that you want to ' 'use for this layer.')) self.lstBands.clear() band_num = self.parent.layer.bandCount() for i in range(band_num): item = QListWidgetItem( self.parent.layer.bandName(i + 1), self.lstBands) item.setData(QtCore.Qt.UserRole, i + 1) self.lstBands.addItem(item) existing_band = self.parent.get_existing_keyword('active_band') if existing_band: self.lstBands.setCurrentRow(existing_band - 1) else: # Set to Band 1 / index 0 self.lstBands.setCurrentRow(0)
def add_last_used_services(self): services = CachedServices().get_cached_services() if len(services) == 0: return self.lstSearchResult.insertItem(0, self.tr("Last used:")) # l = QLabel(self.tr("Last used:")) # l.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed) # self.lSearchResult.addWidget(l) for attributes, image_qByteArray in services: custom_widget = QmsSearchResultItemWidget( attributes, image_qByteArray ) new_item = QListWidgetItem(self.lstSearchResult) new_item.setSizeHint(custom_widget.sizeHint()) self.lstSearchResult.addItem(new_item) self.lstSearchResult.setItemWidget( new_item, custom_widget )
def search_finished_progress(self): self.lstSearchResult.takeItem(0) if self.lstSearchResult.count() == 0: new_widget = QLabel() new_widget.setTextFormat(Qt.RichText) new_widget.setOpenExternalLinks(True) new_widget.setWordWrap(True) new_widget.setText( u"<div align='center'> <strong>{}</strong> </div><div align='center' style='margin-top: 3px'> {} </div>".format( self.tr(u"No results."), self.tr(u"You can add a service to become searchable. Start <a href='{}'>here</a>.").format( u"https://qms.nextgis.com/create" ), ) ) new_item = QListWidgetItem(self.lstSearchResult) new_item.setSizeHint(new_widget.sizeHint()) self.lstSearchResult.addItem(new_item) self.lstSearchResult.setItemWidget( new_item, new_widget )
def set_widgets(self): """Set widgets on the Subcategory tab.""" self.clear_further_steps() # Set widgets purpose = self.parent.step_kw_purpose.selected_purpose() self.lstSubcategories.clear() self.lblDescribeSubcategory.setText('') self.lblIconSubcategory.setPixmap(QPixmap()) self.lblSelectSubcategory.setText( get_question_text('%s_question' % purpose['key'])) for i in self.subcategories_for_layer(): # noinspection PyTypeChecker item = QListWidgetItem(i['name'], self.lstSubcategories) # noinspection PyTypeChecker item.setData(QtCore.Qt.UserRole, i['key']) self.lstSubcategories.addItem(item) # Check if layer keywords are already assigned key = self.parent.step_kw_purpose.selected_purpose()['key'] keyword = self.parent.get_existing_keyword(key) # Overwrite the keyword if it's KW mode embedded in IFCW mode if self.parent.parent_step: keyword = self.parent.get_parent_mode_constraints()[1]['key'] # Set values based on existing keywords or parent mode if keyword: subcategories = [] for index in range(self.lstSubcategories.count()): item = self.lstSubcategories.item(index) subcategories.append(item.data(QtCore.Qt.UserRole)) if keyword in subcategories: self.lstSubcategories.setCurrentRow( subcategories.index(keyword)) self.auto_select_one_item(self.lstSubcategories)
def show_result(self, geoservice, image_ba): if geoservice: custom_widget = QmsSearchResultItemWidget(geoservice, image_ba, extent_renderer=self.extent_renderer) new_item = QListWidgetItem(self.lstSearchResult) new_item.setSizeHint(custom_widget.sizeHint()) self.lstSearchResult.addItem(new_item) self.lstSearchResult.setItemWidget( new_item, custom_widget ) else: new_item = QListWidgetItem() new_item.setText(self.tr('No results!')) new_item.setData(Qt.UserRole, None) self.lstSearchResult.addItem(new_item) self.lstSearchResult.update()
def set_widgets(self): """Set widgets on the layer purpose tab.""" self.clear_further_steps() # Set widgets self.lstCategories.clear() self.lblDescribeCategory.setText('') self.lblIconCategory.setPixmap(QPixmap()) self.lblSelectCategory.setText( category_question % self.parent.layer.name()) purposes = self.purposes_for_layer() for purpose in purposes: if not isinstance(purpose, dict): purpose = definition(purpose) item = QListWidgetItem(purpose['name'], self.lstCategories) item.setData(QtCore.Qt.UserRole, purpose['key']) self.lstCategories.addItem(item) # Check if layer keywords are already assigned purpose_keyword = self.parent.get_existing_keyword('layer_purpose') # Overwrite the purpose_keyword if it's KW mode embedded in IFCW mode if self.parent.parent_step: purpose_keyword = self.parent.\ get_parent_mode_constraints()[0]['key'] # Set values based on existing keywords or parent mode if purpose_keyword: purposes = [] for index in range(self.lstCategories.count()): item = self.lstCategories.item(index) purposes.append(item.data(QtCore.Qt.UserRole)) if purpose_keyword in purposes: self.lstCategories.setCurrentRow( purposes.index(purpose_keyword)) self.auto_select_one_item(self.lstCategories)
def set_widgets(self): """Set widgets on the Unit tab.""" self.clear_further_steps() # Set widgets purpose = self.parent.step_kw_purpose.selected_purpose() subcategory = self.parent.step_kw_subcategory.selected_subcategory() self.lblSelectUnit.setText( unit_question % (subcategory['name'], purpose['name'])) self.lblDescribeUnit.setText('') self.lstUnits.clear() subcat = self.parent.step_kw_subcategory.selected_subcategory()['key'] if purpose == layer_purpose_hazard: units_for_layer = hazard_units(subcat) else: units_for_layer = exposure_units(subcat) for unit_for_layer in units_for_layer: item = QListWidgetItem(unit_for_layer['name'], self.lstUnits) item.setData(QtCore.Qt.UserRole, unit_for_layer['key']) self.lstUnits.addItem(item) # Set values based on existing keywords (if already assigned) if self.parent.step_kw_purpose.\ selected_purpose() == layer_purpose_hazard: key = continuous_hazard_unit['key'] else: key = exposure_unit['key'] unit_id = self.parent.get_existing_keyword(key) if unit_id: units = [] for index in range(self.lstUnits.count()): item = self.lstUnits.item(index) units.append(item.data(QtCore.Qt.UserRole)) if unit_id in units: self.lstUnits.setCurrentRow(units.index(unit_id)) self.auto_select_one_item(self.lstUnits)
def update_list_widget(self): """Update list widget when radio button is clicked.""" # Get selected radio button radio_button_checked_id = self.input_button_group.checkedId() # No radio button checked, then default value = None if radio_button_checked_id > -1: selected_dict = list(self._parameter.options.values())[ radio_button_checked_id] if selected_dict.get('type') == MULTIPLE_DYNAMIC: for field in selected_dict.get('value'): # Update list widget field_item = QListWidgetItem(self.list_widget) field_item.setFlags( Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled) field_item.setData(Qt.UserRole, field) field_item.setText(field) self.list_widget.addItem(field_item)
def populate(self): """populate connections list from settings""" if self.mode == 0: self.settings.beginGroup('/MetaSearch/') keys = self.settings.childGroups() for key in keys: item = QListWidgetItem(self.listConnections) item.setText(key) self.settings.endGroup() else: # populate connections list from file doc = get_connections_from_file(self, self.filename) if doc is None: self.filename = None self.leFileName.clear() self.listConnections.clear() return for csw in doc.findall('csw'): item = QListWidgetItem(self.listConnections) item.setText(csw.attrib.get('name'))
def populate_classified_values( unassigned_values, assigned_values, default_classes, list_unique_values, tree_mapping_widget): """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 list_unique_values. :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 tree_mapping_widget. :type assigned_values: dict :param default_classes: Default classes from unit. :type default_classes: list :param list_unique_values: List Widget for unique values :type list_unique_values: QListWidget :param tree_mapping_widget: Tree Widget for classifying. :type tree_mapping_widget: QTreeWidget """ # Populate the unique values list list_unique_values.clear() list_unique_values.setSelectionMode( QAbstractItemView.ExtendedSelection) for value in unassigned_values: value_as_string = value is not None and str(value) or 'NULL' list_item = QListWidgetItem(list_unique_values) list_item.setFlags( Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled) list_item.setData(Qt.UserRole, value) list_item.setText(value_as_string) list_unique_values.addItem(list_item) # Populate assigned values tree tree_mapping_widget.clear() bold_font = QFont() bold_font.setItalic(True) bold_font.setBold(True) bold_font.setWeight(75) tree_mapping_widget.invisibleRootItem().setFlags( Qt.ItemIsEnabled) for default_class in default_classes: # Create branch for class tree_branch = QTreeWidgetItem(tree_mapping_widget) 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 str(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 __init__(self, commit): QListWidgetItem.__init__(self) self.commit = commit self.ref = commit.commitid