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 on_load_base_layer(self): # look for base layers in the config layer_config = get_layer_config() dlg = QDialog() vbox = QVBoxLayout() list_widget = QListWidget() button_box = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) vbox.addWidget(list_widget) vbox.addWidget(button_box) dlg.setWindowTitle("Select a base layer to load") dlg.setLayout(vbox) # populate the list widget for (uri, provider), cfg in layer_config.items(): layer_name = cfg.get( "layer_name", "Unnamed layer ({}, {})".format(uri, provider)) list_item = QListWidgetItem() list_item.setText(layer_name) list_item.setData(Qt.UserRole, (uri, provider)) list_widget.addItem(list_item) button_box.rejected.connect(dlg.reject) button_box.accepted.connect(dlg.accept) if dlg.exec_(): item = list_widget.currentItem() if item: uri, provider = item.data(Qt.UserRole) self.iface.addVectorLayer(uri, item.text(), provider)
def search(self, text): db = self.db c = db.cursor() self.resultsView.clear() self.resultsView.setEnabled(False) if not text: return if self.fuzzyCheck.isChecked(): search = "* ".join(text.split()) + "*" else: search = text query = c.execute( """SELECT layer, featureid, snippet(search, '[',']') as snippet FROM search JOIN featureinfo on search.docid = featureinfo.id WHERE search match '{}' LIMIT 100""".format( search)).fetchall() for layer, featureid, snippet in query: item = QListWidgetItem() text = "{}\n {}".format(layer, snippet.replace('\n', ' ')) item.setText(text) item.setData(Qt.UserRole + 1, (layer, featureid, snippet)) self.resultsView.addItem(item) self.resultsView.setEnabled(True) if self.resultsView.count() == 0: self.resultsView.addItem("No Results") self.resultsView.setEnabled(False) db.close()
def _populateTerrainLayers(self): """Populates the layers list""" listLayers = self.listLayers listLayers.clear() for layerView in QgsProject.instance().layerTreeRoot().findLayers(): layer = layerView.layer() # Must be vectory if layer.type() != QgsMapLayer.VectorLayer: continue # Must be polygon if layer.geometryType() != QgsWkbTypes.PolygonGeometry: continue fields = layer.fields() elevationIndex = fields.indexOf('elevation') if elevationIndex == -1: continue listItem = QListWidgetItem(listLayers) listItem.setText(layer.name()) listItem.setData(QtCore.Qt.UserRole, layer)
def addPrefixToList(self): item = QListWidgetItem() item.setData( 0, "PREFIX " + self.tripleStorePrefixNameEdit.text() + ":<" + self.tripleStorePrefixEdit.text() + ">") item.setText("PREFIX " + self.tripleStorePrefixNameEdit.text() + ":<" + self.tripleStorePrefixEdit.text() + ">") self.prefixList.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 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 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 str(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 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 getClassesFromLabel(self, comboBox): viewlist = [] resultlist = [] label = self.conceptSearchEdit.text() if label == "": return language = "en" results = {} self.searchResult.clear() query = "" position = self.tripleStoreEdit.currentIndex() if self.tripleStoreEdit.currentIndex() > len(self.triplestoreconf): if self.findProperty.isChecked(): self.addVocab[self.addVocab.keys()[ position - len(self.triplestoreconf)]]["source"]["properties"] viewlist = {k: v for k, v in d.iteritems() if label in k} else: self.addVocab[self.addVocab.keys()[ position - len(self.triplestoreconf)]]["source"]["classes"] viewlist = {k: v for k, v in d.iteritems() if label in k} for res in viewlist: item = QListWidgetItem() item.setData(1, val) item.setText(key) self.searchResult.addItem(item) else: if self.findProperty.isChecked(): if "propertyfromlabelquery" in self.triplestoreconf[ self.tripleStoreEdit.currentIndex() + 1]: query = self.triplestoreconf[ self.tripleStoreEdit.currentIndex() + 1]["propertyfromlabelquery"].replace( "%%label%%", label) else: if "classfromlabelquery" in self.triplestoreconf[ self.tripleStoreEdit.currentIndex() + 1]: query = self.triplestoreconf[ self.tripleStoreEdit.currentIndex() + 1]["classfromlabelquery"].replace("%%label%%", label) if query == "": msgBox = QMessageBox() msgBox.setText( "No search query specified for this triplestore") msgBox.exec() return self.qtask = SearchTask( "Searching classes/properties for " + label + " in " + self.triplestoreconf[self.tripleStoreEdit.currentIndex() + 1]["endpoint"], self.triplestoreconf[self.tripleStoreEdit.currentIndex() + 1]["endpoint"], query, self.triplestoreconf, self.findProperty, self.tripleStoreEdit, self.searchResult, self.prefixes, label, language, None) QgsApplication.taskManager().addTask(self.qtask) return viewlist
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 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 addResults(self, hits): #REFACTOR to add if link is missing for hit in hits: for link in hit.get("downloadLinks"): title = self.getTitleFromHit(hit) if title: item = QListWidgetItem() item.setText(title) item.setData(1, hit) self.dlg.searchResult.addItem(item)
def __init__(self, names, parent=None): QDialog.__init__(self, parent) self.setupUi(self) self.names = names self.selected_layers_info = dict() self.lst_plots.clear() self.lst_buildings.clear() self.plots = { self.names.LC_BOUNDARY_POINT_T: None, self.names.LC_BOUNDARY_T: None, self.names.LC_PLOT_T: None } self.buildings = { self.names.LC_SURVEY_POINT_T: None, self.names.LC_BUILDING_T: None, self.names.LC_BUILDING_UNIT_T: None } icons = { self.names.LC_BOUNDARY_POINT_T: QIcon(":/Asistente-LADM-COL/resources/images/points.png"), self.names.LC_BOUNDARY_T: QIcon(":/Asistente-LADM-COL/resources/images/lines.png"), self.names.LC_PLOT_T: QIcon(":/Asistente-LADM-COL/resources/images/polygons.png"), self.names.LC_SURVEY_POINT_T: QIcon(":/Asistente-LADM-COL/resources/images/points.png"), self.names.LC_BUILDING_T: QIcon(":/Asistente-LADM-COL/resources/images/polygons.png"), self.names.LC_BUILDING_UNIT_T: QIcon(":/Asistente-LADM-COL/resources/images/polygons.png") } for k, v in self.plots.items(): item = QListWidgetItem() item.setData(Qt.DecorationRole, icons[k]) item.setText(k) self.lst_plots.addItem(item) for k, v in self.buildings.items(): item = QListWidgetItem() item.setData(Qt.DecorationRole, icons[k]) item.setText(k) self.lst_buildings.addItem(item) # Set connections self.buttonBox.accepted.connect(self.accepted) self.rad_plots.toggled.connect(self.update_controls) self.lst_plots.itemSelectionChanged.connect(self.update_controls) self.lst_buildings.itemSelectionChanged.connect(self.update_controls) self.update_controls() # Initialize GUI state
def getClassesFromLabel(self, comboBox): viewlist = [] resultlist = [] label = self.conceptSearchEdit.text() language = "en" results = {} self.searchResult.clear() query = "" if self.currentcol == 4: if "propertyfromlabelquery" in self.triplestoreconf[ self.tripleStoreEdit.currentIndex() + 1]: query = self.triplestoreconf[ self.tripleStoreEdit.currentIndex() + 1]["propertyfromlabelquery"].replace("%%label%%", label) else: if "classfromlabelquery" in self.triplestoreconf[ self.tripleStoreEdit.currentIndex() + 1]: query = self.triplestoreconf[ self.tripleStoreEdit.currentIndex() + 1]["classfromlabelquery"].replace("%%label%%", label) if "SELECT" in query: query = query.replace("%%label%%", label).replace("%%language%%", language) sparql = SPARQLWrapper( self.triplestoreconf[ self.tripleStoreEdit.currentIndex()]["endpoint"], agent= "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11" ) sparql.setQuery(query) sparql.setReturnFormat(JSON) results = sparql.query().convert() self.searchResultMap = {} for res in results["results"]["bindings"]: item = QListWidgetItem() item.setData(0, str(res["class"]["value"])) item.setText(str(res["label"]["value"])) self.searchResultMap[res["label"] ["value"]] = res["class"]["value"] self.searchResult.addItem(item) else: myResponse = json.loads(requests.get(query).text) for ent in myResponse["search"]: qid = ent["url"] label = ent["label"] + " (" + ent["id"] + ") " if "description" in ent: label += "[" + ent["description"] + "]" results[qid] = label self.searchResultMap[label] = ent["url"] for result in results: item = QListWidgetItem() item.setData(0, result) item.setText(str(results[result])) self.searchResult.addItem(item) return viewlist
def __init__(self, layers): """Constructor for the dialog.""" QDialog.__init__(self, None, Qt.WindowStaysOnTopHint) self.ui = Ui_SelectLayer_dialog_base() self.ui.setupUi(self) self.ui.LayerList.clear() for layer in layers: item = QListWidgetItem() item.setText(layer.name()) self.ui.LayerList.addItem(item) self.ui.buttonBox.accepted.connect(self.accept) self.ui.buttonBox.rejected.connect(self.reject)
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 populateListWithDatabasesFromServer(self): ''' Populates databases list from server ''' dbList = [] try: dbList = self.serverWidget.abstractDb.getEDGVDbsFromServer() except Exception as e: QMessageBox.critical(self, self.tr('Critical!'), ':'.join(e.args)) dbList.sort() for (dbname, dbversion) in dbList: item = QListWidgetItem(self.dbListWidget) item.setText(dbname + ' (EDGV v. ' + dbversion + ')') item.setData(Qt.UserRole, dbname)
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_project(self, project: QgsProject) -> None: self.project = project self.clear() for layer in self.project.mapLayers().values(): if layer.type() != QgsMapLayer.VectorLayer: continue if not layer.isSpatial(): continue cell = QListWidgetItem() cell.setText(layer.name()) cell.setData(Qt.UserRole, layer.id()) cell.setIcon(QgsMapLayerModel.iconForLayer(layer)) self.addItem(cell)
def set_layer(self, layer: QgsVectorLayer): self.layer = layer self.clear() for field in self.layer.fields(): cell = QListWidgetItem() alias = field.alias() if not alias: cell.setText(field.name()) else: cell.setText("{} ({})".format(field.name(), alias)) cell.setData(Qt.UserRole, field.name()) index = layer.fields().indexFromName(field.name()) if index >= 0: cell.setIcon(self.layer.fields().iconForField(index)) self.addItem(cell)
def _tabListValue_setup(self): self.tabListValue_list_values.clear() self.tabListValue_tx_value.clear() prop = self.property_selected if prop == 'geom': return property_list = self._get_property(self.resource, prop) for elem in property_list: k, v = list(elem.items())[0] item = QListWidgetItem() item.setText(str(v)) self.tabListValue_list_values.addItem(item)
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 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 _current_tab_property_changed(self, index): prop = self.property_selected property_list = self._get_property(self.resource, prop) current_tab = self.tab_values.currentIndex() # tab Valor if current_tab == 0: self.tabValue_list_values.clear() self.tabValue_tx_insert_value.clear() if prop == 'geom': return for elem in property_list: k, v = list(elem.items())[0] item = QListWidgetItem() item.setText(str(v)) self.tabValue_list_values.addItem(item) # tab Lista de Valores elif current_tab == 2: self.tabListValue_list_values.clear() self.tabListValue_tx_value.clear() if prop == 'geom': return for elem in property_list: k, v = list(elem.items())[0] item = QListWidgetItem() item.setText(str(v)) self.tabListValue_list_values.addItem(item) # tab URL elif current_tab == 3: self._tabUrl_setup()
def update_widget(self): # 1. Populate suggested structures self.widget.suggestedListWidget.clear() for structure in self._get_suggested_structures(): widget_item = QListWidgetItem(f"Structure {structure.obj_id}/{structure.identifier}") widget_item.setData(Qt.UserRole, structure.obj_id) self.widget.suggestedListWidget.addItem(widget_item) # 2. Populated assigned structures self.widget.assignedWidget.clear() for structure in self._get_assigned_structures(): widget_item = QListWidgetItem(f"Structure {structure.obj_id}/{structure.identifier}") widget_item.setData(Qt.UserRole, structure.obj_id) self.widget.assignedWidget.addItem(widget_item) # 3. Populate child damages self.widget.damagesTreeWidget.clear() for damage in self._get_child_damages(): editor = self.main_dialog.editors.get(damage, None) widget_item = QTreeWidgetItem() widget_item.setData(0, Qt.UserRole, damage.obj_id) if editor: # there may be items that are already in the DB widget_item.setCheckState(0, editor.listitem.checkState(0)) widget_item.setText(1, str(damage.distance)) widget_item.setText( 2, damage.channel_damage_code__REL.value_de if damage.channel_damage_code__REL else "" ) widget_item.setText(3, damage.comments) self.widget.damagesTreeWidget.addTopLevelItem(widget_item) self.widget.damagesTreeWidget.header().setSectionResizeMode(QHeaderView.ResizeToContents)
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(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 finished(self, result): counter = 0 if self.sortedatt != None: for att in self.sortedatt: if att[1] < 1: continue if att[0] in self.labels: item = QListWidgetItem() item.setText(self.labels[att[0]] + " (" + str(att[1]) + "%)") item.setData(1, self.urilist[att[0]]) self.searchResult.addItem(item) counter += 1 else: item = QListWidgetItem() item.setText(att[0] + " (" + str(att[1]) + "%)") item.setData(1, self.urilist[att[0]]) self.searchResult.addItem(item) else: msgBox = QMessageBox() msgBox.setText( "The enrichment search query did not yield any results!") msgBox.exec() self.progress.close()
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 finished(self, result): if self.query == "": msgBox = QMessageBox() msgBox.setWindowTitle("No search query specified") msgBox.setText("No search query specified for this triplestore") msgBox.exec() return if "SELECT" in self.query: if len(self.results["results"]) == 0 or len( self.results["results"]["bindings"]) == 0: msgBox = QMessageBox() msgBox.setWindowTitle("Empty search result") msgBox.setText("The search yielded no results") msgBox.exec() return for res in self.results["results"]["bindings"]: item = QListWidgetItem() item.setData(1, str(res["class"]["value"])) if "label" in res: item.setText( str(res["label"]["value"] + " (" + res["class"]["value"] + ")")) else: item.setText(str(res["class"]["value"])) self.searchResult.addItem(item) else: i = 0 for result in self.results: item = QListWidgetItem() item.setData(1, self.qids[i]) item.setText(str(self.results[result])) self.searchResult.addItem(item) i += 1 iface.messageBar().pushMessage("Searched for concepts in", "OK", level=Qgis.Success)
def noResults(self): item = QListWidgetItem() item.setText("Hakutuloksia ei löytynyt!") self.dlg.searchResult.addItem(item)
def getClassesFromLabel(self, comboBox): viewlist = [] resultlist = [] label = self.conceptSearchEdit.text() if label == "": return language = "en" results = {} self.searchResult.clear() query = "" position = self.tripleStoreEdit.currentIndex() if self.tripleStoreEdit.currentIndex() > len(self.triplestoreconf): if self.findProperty.isChecked(): self.addVocab[self.addVocab.keys()[ position - len(self.triplestoreconf)]]["source"]["properties"] viewlist = {k: v for k, v in d.iteritems() if label in k} else: self.addVocab[self.addVocab.keys()[ position - len(self.triplestoreconf)]]["source"]["classes"] viewlist = {k: v for k, v in d.iteritems() if label in k} for res in viewlist: item = QListWidgetItem() item.setData(1, val) item.setText(key) self.searchResult.addItem(item) else: if self.findProperty.isChecked(): if "propertyfromlabelquery" in self.triplestoreconf[ self.tripleStoreEdit.currentIndex() + 1]: query = self.triplestoreconf[ self.tripleStoreEdit.currentIndex() + 1]["propertyfromlabelquery"].replace( "%%label%%", label) else: if "classfromlabelquery" in self.triplestoreconf[ self.tripleStoreEdit.currentIndex() + 1]: query = self.triplestoreconf[ self.tripleStoreEdit.currentIndex() + 1]["classfromlabelquery"].replace("%%label%%", label) if query == "": msgBox = QMessageBox() msgBox.setText( "No search query specified for this triplestore") msgBox.exec() return if "SELECT" in query: query = query.replace("%%label%%", label).replace("%%language%%", language) sparql = SPARQLWrapper( self.triplestoreconf[self.tripleStoreEdit.currentIndex() + 1]["endpoint"], agent= "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11" ) #msgBox=QMessageBox() #msgBox.setText(query+" - "+self.triplestoreconf[self.tripleStoreEdit.currentIndex()+1]["endpoint"]) #msgBox.exec() sparql.setQuery( self.prefixes[self.tripleStoreEdit.currentIndex() + 1] + query) sparql.setReturnFormat(JSON) results = sparql.query().convert() #msgBox=QMessageBox() #msgBox.setText(str(results)) #msgBox.exec() if len(results["results"]) == 0: msgBox = QMessageBox() msgBox.setText("The search yielded no results") msgBox.exec() return for res in results["results"]["bindings"]: item = QListWidgetItem() item.setData(1, str(res["class"]["value"])) if "label" in res: item.setText( str(res["label"]["value"] + " (" + res["class"]["value"] + ")")) else: item.setText(str(res["class"]["value"])) self.searchResult.addItem(item) else: myResponse = json.loads(requests.get(query).text) qids = [] for ent in myResponse["search"]: qid = ent["concepturi"] if "http://www.wikidata.org/entity/" in qid and self.findProperty.isChecked( ): qid = "http://www.wikidata.org/prop/direct/" + ent["id"] elif "http://www.wikidata.org/wiki/" in qid and self.findConcept.isChecked( ): qid = "http://www.wikidata.org/entity/" + ent["id"] qids.append(qid) label = ent["label"] + " (" + ent["id"] + ") " if "description" in ent: label += "[" + ent["description"] + "]" results[qid] = label i = 0 for result in results: item = QListWidgetItem() item.setData(1, qids[i]) item.setText(str(results[result])) self.searchResult.addItem(item) i += 1 return viewlist
def __init__(self, parent=None): """Constructor. :param parent: Optional widget to use as parent :type parent: QWidget :param iface: An instance of QGisInterface :type iface: QGisInterface """ super(ResourceSharingDialog, self).__init__(parent) self.setupUi(self) # Reconfigure UI self.setWindowTitle(f"{__title__} - {__version__}") self.setModal(True) self.button_edit.setEnabled(False) self.button_delete.setEnabled(False) self.button_install.setEnabled(False) self.button_open.setEnabled(False) self.button_uninstall.setEnabled(False) # Set up the "main menu" - QListWidgetItem # All collections icon_all = QIcon() icon_all.addFile(str(resources_path("img", "plugin.svg")), QSize(), QIcon.Normal, QIcon.Off) item_all = QListWidgetItem() item_all.setIcon(icon_all) item_all.setText(self.tr("All collections")) # Installed collections icon_installed = QIcon() icon_installed.addFile( str(resources_path("img", "plugin-installed.svg")), QSize(), QIcon.Normal, QIcon.Off, ) item_installed = QListWidgetItem() item_installed.setIcon(icon_installed) item_installed.setText(self.tr("Installed collections")) item_all.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) # Settings / repositories icon_settings = QIcon() icon_settings.addFile(str(resources_path("img", "settings.svg")), QSize(), QIcon.Normal, QIcon.Off) item_settings = QListWidgetItem() item_settings.setIcon(icon_settings) item_settings.setText(self.tr("Settings")) item_all.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled) # Add the items to the list widget self.menu_list_widget.addItem(item_all) self.menu_list_widget.addItem(item_installed) self.menu_list_widget.addItem(item_settings) # Init the message bar self.message_bar = QgsMessageBar(self) self.message_bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.vlayoutRightColumn.insertWidget(0, self.message_bar) # Progress dialog for long running processes self.progress_dialog = None # Init the repository manager dialog self.repository_manager = RepositoryManager() self.collection_manager = CollectionManager() # Collections list view self.collections_model = QStandardItemModel(0, 1) self.collections_model.sort(0, Qt.AscendingOrder) self.collection_proxy = CustomSortFilterProxyModel(self) self.collection_proxy.setSourceModel(self.collections_model) self.list_view_collections.setModel(self.collection_proxy) # Active selected collection self._sel_coll_id = None # Slots self.button_add.clicked.connect(self.add_repository) self.button_edit.clicked.connect(self.edit_repository) self.button_delete.clicked.connect(self.delete_repository) self.button_reload.clicked.connect(self.reload_repositories) self.button_reload_dir.clicked.connect(self.reload_off_res_directory) self.menu_list_widget.currentRowChanged.connect(self.set_current_tab) self.list_view_collections.selectionModel().currentChanged.connect( self.on_list_view_collections_clicked) self.line_edit_filter.textChanged.connect(self.filter_collections) self.button_install.clicked.connect(self.install_collection) self.button_open.clicked.connect(self.open_collection) self.button_uninstall.clicked.connect(self.uninstall_collection) self.button_box.button(QDialogButtonBox.Help).clicked.connect( self.open_help) # Populate the repositories widget and collections list view self.populate_repositories_widget() self.reload_collections_model()
def run(self): QgsMessageLog.logMessage( 'Started task "{}"'.format(self.description()), MESSAGE_CATEGORY, Qgis.Info) if self.proxyHost != None and self.proxyHost != "" and self.proxyPort != None and self.proxyPort != "": QgsMessageLog.logMessage('Proxy? ' + str(self.proxyHost), MESSAGE_CATEGORY, Qgis.Info) proxy = urllib.ProxyHandler({'http': proxyHost}) opener = urllib.build_opener(proxy) urllib.install_opener(opener) #msgBox=QMessageBox() #msgBox.setText(self.query+" - "+self.triplestoreconf[self.tripleStoreEdit.currentIndex()+1]["endpoint"]) #msgBox.exec() if self.findProperty.isChecked(): if "propertyfromlabelquery" in self.triplestoreconf[ self.tripleStoreEdit.currentIndex() + 1]: self.query = self.triplestoreconf[ self.tripleStoreEdit.currentIndex() + 1]["propertyfromlabelquery"].replace( "%%label%%", self.label) else: if "classfromlabelquery" in self.triplestoreconf[ self.tripleStoreEdit.currentIndex() + 1]: self.query = self.triplestoreconf[ self.tripleStoreEdit.currentIndex() + 1]["classfromlabelquery"].replace("%%label%%", self.label) if self.query == "": return if "SELECT" in self.query: self.query = self.query.replace("%%label%%", self.label).replace( "%%language%%", self.language) sparql = SPARQLWrapper( self.triplestoreconf[self.tripleStoreEdit.currentIndex() + 1]["endpoint"], agent= "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11" ) sparql.setQuery(self.prefixes[self.tripleStoreEdit.currentIndex() + 1] + self.query) sparql.setReturnFormat(JSON) self.results = sparql.query().convert() # msgBox=QMessageBox() # msgBox.setText(str(results)) # msgBox.exec() for res in self.results["results"]["bindings"]: item = QListWidgetItem() item.setData(1, str(res["class"]["value"])) if "label" in res: item.setText( str(res["label"]["value"] + " (" + res["class"]["value"] + ")")) else: item.setText(str(res["class"]["value"])) self.searchResult.addItem(item) else: myResponse = json.loads(requests.get(self.query).text) self.qids = [] for ent in myResponse["search"]: qid = ent["concepturi"] if "http://www.wikidata.org/entity/" in qid and self.findProperty.isChecked( ): qid = "http://www.wikidata.org/prop/direct/" + ent["id"] elif "http://www.wikidata.org/wiki/" in qid and self.findConcept.isChecked( ): qid = "http://www.wikidata.org/entity/" + ent["id"] self.qids.append(qid) label = ent["label"] + " (" + ent["id"] + ") " if "description" in ent: label += "[" + ent["description"] + "]" self.results[qid] = label
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 _load_properties(self, resource): for prop in resource.properties(): item = QListWidgetItem() item.setText(prop.name) self.list_properties.addItem(item)