Esempio n. 1
0
    def fetchResults(self, string, context, feedback):
        # collect results in main thread, since this method is inexpensive and
        # accessing the processing registry/current layer is not thread safe

        if iface.activeLayer() is None or iface.activeLayer().type() != QgsMapLayer.VectorLayer or not iface.activeLayer().selectedFeatureCount():
            return

        for a in QgsApplication.processingRegistry().algorithms():
            if not a.flags() & QgsProcessingAlgorithm.FlagSupportsInPlaceEdits:
                continue

            if not a.supportInPlaceEdit(iface.activeLayer()):
                continue

            if QgsLocatorFilter.stringMatches(a.displayName(), string) or [t for t in a.tags() if QgsLocatorFilter.stringMatches(t, string)] or \
                    (context.usingPrefix and not string):
                result = QgsLocatorResult()
                result.filter = self
                result.displayString = a.displayName()
                result.icon = a.icon()
                result.userData = a.id()
                if string and QgsLocatorFilter.stringMatches(a.displayName(), string):
                    result.score = float(len(string)) / len(a.displayName())
                else:
                    result.score = 0
                self.resultFetched.emit(result)
Esempio n. 2
0
def execute_in_place(alg, parameters, context=None, feedback=None):
    """Executes an algorithm modifying features in-place in the active layer.

    The input layer must be editable or an exception is raised.

    :param alg: algorithm to run
    :type alg: QgsProcessingAlgorithm
    :param parameters: parameters of the algorithm
    :type parameters: dict
    :param context: context, defaults to None
    :param context: QgsProcessingContext, optional
    :param feedback: feedback, defaults to None
    :param feedback: QgsProcessingFeedback, optional
    :raises QgsProcessingException: raised when the layer is not editable or the layer cannot be found in the current project
    :return: a tuple with true if success and results
    :rtype: tuple
    """

    parameters['INPUT'] = QgsProcessingFeatureSourceDefinition(
        iface.activeLayer().id(), True)
    ok, results = execute_in_place_run(alg,
                                       iface.activeLayer(),
                                       parameters,
                                       context=context,
                                       feedback=feedback)
    if ok:
        iface.activeLayer().triggerRepaint()
    return ok, results
Esempio n. 3
0
    def createWidget(self):
        if self.dialogType == DIALOG_STANDARD:
            widget = QWidget()
            layout = QHBoxLayout()
            layout.setMargin(0)
            layout.setContentsMargins(0, 0, 0, 0)
            layout.setSpacing(2)
            self.combo = QgsMapLayerComboBox()
            layout.addWidget(self.combo)
            btn = QToolButton()
            btn.setText('...')
            btn.setToolTip(self.tr("Select file"))
            btn.clicked.connect(self.selectFile)
            layout.addWidget(btn)

            widget.setLayout(layout)

            if self.param.optional:
                self.combo.setAllowEmptyLayer(True)

            self.combo.setFilters(QgsMapLayerProxyModel.VectorLayer)
            self.combo.setExcludedProviders(['grass'])
            try:
                if iface.activeLayer().type() == QgsMapLayer.VectorLayer:
                    self.combo.setLayer(iface.activeLayer())
            except:
                pass

            self.combo.currentIndexChanged.connect(lambda: self.widgetValueHasChanged.emit(self))
            self.combo.currentTextChanged.connect(lambda: self.widgetValueHasChanged.emit(self))
            return widget

        elif self.dialogType == DIALOG_BATCH:
            return BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog)
        else:
            self.combo = QComboBox()
            layers = self.dialog.getAvailableValuesOfType(ParameterRaster, OutputRaster)
            self.combo.setEditable(True)
            tables = self.dialog.getAvailableValuesOfType(ParameterTable, OutputTable)
            layers = self.dialog.getAvailableValuesOfType(ParameterVector, OutputVector)
            if self.param.optional:
                self.combo.addItem(self.NOT_SELECTED, None)
            for table in tables:
                self.combo.addItem(self.dialog.resolveValueDescription(table), table)
            for layer in layers:
                self.combo.addItem(self.dialog.resolveValueDescription(layer), layer)

            widget = QWidget()
            layout = QHBoxLayout()
            layout.setMargin(0)
            layout.setContentsMargins(0, 0, 0, 0)
            layout.setSpacing(2)
            layout.addWidget(self.combo)
            btn = QToolButton()
            btn.setText('...')
            btn.setToolTip(self.tr("Select file"))
            btn.clicked.connect(self.selectFile)
            layout.addWidget(btn)
            widget.setLayout(layout)
            return widget
Esempio n. 4
0
    def fetchResults(self, string, context, feedback):
        # collect results in main thread, since this method is inexpensive and
        # accessing the processing registry/current layer is not thread safe

        if iface.activeLayer() is None or iface.activeLayer().type() != QgsMapLayer.VectorLayer:
            return

        for a in QgsApplication.processingRegistry().algorithms():
            if not a.flags() & QgsProcessingAlgorithm.FlagSupportsInPlaceEdits:
                continue

            if not a.supportInPlaceEdit(iface.activeLayer()):
                continue

            if QgsLocatorFilter.stringMatches(a.displayName(), string) or [t for t in a.tags() if QgsLocatorFilter.stringMatches(t, string)] or \
                    (context.usingPrefix and not string):
                result = QgsLocatorResult()
                result.filter = self
                result.displayString = a.displayName()
                result.icon = a.icon()
                result.userData = a.id()
                if string and QgsLocatorFilter.stringMatches(a.displayName(), string):
                    result.score = float(len(string)) / len(a.displayName())
                else:
                    result.score = 0
                self.resultFetched.emit(result)
Esempio n. 5
0
    def __init__(self, alg):
        super(FieldsCalculatorDialog, self).__init__(None)
        self.setupUi(self)

        self.executed = False
        self._wasExecuted = False
        self.alg = alg
        self.layer = None

        self.cmbInputLayer.setFilters(QgsMapLayerProxyModel.VectorLayer)
        try:
            if iface.activeLayer().type() == QgsMapLayerType.VectorLayer:
                self.cmbInputLayer.setLayer(iface.activeLayer())
        except:
            pass

        self.cmbInputLayer.layerChanged.connect(self.updateLayer)
        self.btnBrowse.clicked.connect(self.selectFile)
        self.mNewFieldGroupBox.toggled.connect(self.toggleExistingGroup)
        self.mUpdateExistingGroupBox.toggled.connect(self.toggleNewGroup)
        self.mOutputFieldTypeComboBox.currentIndexChanged.connect(
            self.setupSpinboxes)

        # Default values for field width and precision
        self.mOutputFieldWidthSpinBox.setValue(10)
        self.mOutputFieldPrecisionSpinBox.setValue(3)

        # Output is a shapefile, so limit maximum field name length
        self.mOutputFieldNameLineEdit.setMaxLength(10)

        self.manageGui()
Esempio n. 6
0
    def eventFilter(self, obj, event):
        if event is None or self is None or QEvent is None:
            return False
        if event.type() == QEvent.ContextMenu:
            layer = iface.activeLayer()
            #if layer is not None and layer.type() == QgsMapLayer.VectorLayer:
            (index,indexStr) = self.checkLayerAttribute( layer, False )
            if index != -1:
                globalPos = iface.mapCanvas().mapToGlobal(event.pos())
                myMenu = QMenu()
                str1 = self.tr("Add selected tile raster layer(s)")
                str3 = self.tr("Add all tile raster layer(s)")
                str2 = self.tr("Show tile previews in map")
                if len(layer.selectedFeatures()) != 0: 
                    myMenu.addAction(QIcon(":/plugins/tileindex/icon/mActionAddImage.png"),str1)
                myMenu.addAction(QIcon(":/plugins/tileindex/icon/mActionAddRasterLayer.png"),str3)
                myMenu.addAction(QIcon(":/plugins/tileindex/icon/mActionMapTips.png"),str2)
                selectedAction = myMenu.exec_(globalPos)
                if selectedAction:
                    if selectedAction.text() == str1:
                        count = self.addSelectedTiles( iface.activeLayer() )
                    elif selectedAction.text() == str3:
                        self.addAllTiles( iface.activeLayer() )
                    elif selectedAction.text() == str2:
                        self.showPreview(layer)
                    else:
                        return False
                    return True
                return False

        return False
Esempio n. 7
0
    def __init__(self, alg):
        super(FieldsCalculatorDialog, self).__init__(None)
        self.setupUi(self)

        self.executed = False
        self._wasExecuted = False
        self.alg = alg
        self.layer = None

        self.cmbInputLayer.setFilters(QgsMapLayerProxyModel.VectorLayer)
        try:
            if iface.activeLayer().type() == QgsMapLayer.VectorLayer:
                self.cmbInputLayer.setLayer(iface.activeLayer())
        except:
            pass

        self.cmbInputLayer.layerChanged.connect(self.updateLayer)
        self.btnBrowse.clicked.connect(self.selectFile)
        self.mNewFieldGroupBox.toggled.connect(self.toggleExistingGroup)
        self.mUpdateExistingGroupBox.toggled.connect(self.toggleNewGroup)
        self.mOutputFieldTypeComboBox.currentIndexChanged.connect(self.setupSpinboxes)

        # Default values for field width and precision
        self.mOutputFieldWidthSpinBox.setValue(10)
        self.mOutputFieldPrecisionSpinBox.setValue(3)

        # Output is a shapefile, so limit maximum field name length
        self.mOutputFieldNameLineEdit.setMaxLength(10)

        self.manageGui()
Esempio n. 8
0
 def edit_reset_clicked(self):
     """When bulk load frame btn_reset_save clicked"""
     self.edit_dialog.ids = []
     self.edit_dialog.building_outline_id = None
     iface.actionSelect().trigger()
     iface.activeLayer().removeSelection()
     # reset and disable comboboxes
     self.edit_dialog.circle_tool = None
     self.disable_UI_functions()
Esempio n. 9
0
    def mapaPlantillaPdf(self):
        import time

        registry = QgsMapLayerRegistry.instance()
        layers = registry.mapLayers().values()
        layerName = iface.activeLayer().name()
        # Add layer to map render
        myMapRenderer = QgsMapRenderer()
        myMapRenderer.setLayerSet(layerName)
        myMapRenderer.setProjectionsEnabled(False)

        # Load template
        layer = iface.activeLayer()
        canvas = iface.mapCanvas()
        extent = layer.extent()
        #canvas = QgsMapCanvas()
        ms = canvas.mapSettings()
        myComposition = QgsComposition(ms)

        # uso plantilla
        if (extent.width() > extent.height()):
            tipo = 'h'
            myFile = os.path.join(os.path.dirname(__file__), 'template_h2.qpt')
        else:
            # plantilla vertical
            tipo = 'v'
            myFile = os.path.join(os.path.dirname(__file__), 'template_v2.qpt')
        #myFile = '/home/jose/Documentos/pyqgis/template_h.qpt'
        myTemplateFile = file(myFile, 'rt')
        myTemplateContent = myTemplateFile.read()
        myTemplateFile.close()
        myDocument = QDomDocument()
        myDocument.setContent(myTemplateContent)
        myComposition.loadFromTemplate(myDocument)

        # Sustituir textos
        substitution_map = {'TITULO': u'TEMÁTICO','EDIFICIO':self.dlg.comboBoxEdificio.currentText(),'FECHA': time.strftime("%d/%m/%Y") ,'AUTOR': u'José Manuel Mira','ORGANISMO': 'Universidad de Alicante'}
        myComposition.loadFromTemplate(myDocument, substitution_map)

        # Zoom a capa
        myMap = myComposition.getComposerMapById(0)
        myExtent = iface.activeLayer().extent()
        myMap.setNewExtent(myExtent)

        # Save image
        salidaPNG = "mapa_" + layer.name() + "_" + time.strftime("%Y%m%d%H%M%S") + ".png"
        myImage = myComposition.printPageAsRaster(0)
        myImage.save(salidaPNG)

        # export PDF
        import time
        salidaPDF = "mapa_" + layer.name() + "_" + time.strftime("%Y%m%d%H%M%S") + ".pdf"
        myComposition.exportAsPDF(salidaPDF)

        QMessageBox.information(self.iface.mainWindow(), "Resultado", "Los mapas, " + salidaPNG + " y "+ salidaPDF+ " han sido creados exitosamente.")
Esempio n. 10
0
 def edit_reset_clicked(self):
     """
         When production frame btn_edit_reset clicked
     """
     self.edit_dialog.ids = []
     self.edit_dialog.building_outline_id = None
     # restart editing
     iface.actionSelect().trigger()
     iface.activeLayer().removeSelection()
     # reset and disable comboboxes
     self.disable_UI_functions()
Esempio n. 11
0
 def setRelSoglia(self, dlg):
     #Gestisce lo slider che indica la soglia di visualizzazione in base all'overlay temporale delle relazioni
     soglia = dlg.horizontalSlider.value()
     if soglia >= 65:
         expr = "overlay = 'dentro'"
     if soglia < 65 and soglia >= 45:
         expr = "overlay = 'parziale'"
     if soglia < 45 and soglia >= 10:
         expr = "overlay = 'fuori'"
     if soglia < 10:
         expr = "overlay = 'dentro' or overlay = 'parziale' or overlay = 'fuori'"
     iface.activeLayer().setSubsetString(expr)
Esempio n. 12
0
 def edit_reset_clicked(self):
     """
         When production frame btn_edit_reset clicked
     """
     self.editing_layer.geometryChanged.disconnect(self.geometry_changed)
     iface.actionCancelEdits().trigger()
     self.editing_layer.geometryChanged.connect(self.geometry_changed)
     self.edit_dialog.geoms = {}
     # restart editing
     iface.actionToggleEditing().trigger()
     iface.actionVertexTool().trigger()
     iface.activeLayer().removeSelection()
     # reset and disable comboboxes
     self.disable_UI_functions()
Esempio n. 13
0
def change_color():
    active_layer = iface.activeLayer()
    renderer = active_layer.rendererV2()
    symbol = renderer.symbol()
    symbol.setColor(QColor(Qt.red))
    iface.mapCanvas().refresh()
    iface.legendInterface().refreshLayerSymbology(active_layer)
Esempio n. 14
0
    def tematico(self):
        layer = iface.activeLayer()
        usos = {
            u"Administración": ("#b3cde3", u"Administración"),
            "Despacho": ("#fbb4ae", "Despacho"),
            "Docencia": ("#ccebc5", "Docencia"),
            "Laboratorio": ("#decbe4", "Laboratorio"),
            "Salas": ("#fed9a6", "Salas"),
            "Muros": ("#808080", "Muros"),
            "": ("white", "Resto")}
        categorias = []
        for estancia, (color, label) in usos.items():
            sym = QgsSymbolV2.defaultSymbol(layer.geometryType())
            sym.setColor(QColor(color))
            category = QgsRendererCategoryV2(estancia, sym, label)
            categorias.append(category)

            field = "activresum"
            index = layer.fieldNameIndex("activresum")
            # comprueba que existe el campo activresum
            if (index == -1):
                QMessageBox.critical(None, "Field error", "No existe el campo activresum. Seleccione la capa adecuada")
                break

            renderer = QgsCategorizedSymbolRendererV2(field, categorias)
            layer.setRendererV2(renderer)
            QgsMapLayerRegistry.instance().addMapLayer(layer)
            layer.triggerRepaint()
            layer.setName(layer.name()[:6] + u' (uso)')
            # actualizar metadatos
            layer.setTitle(u"Planta de edificio " + layer.name()[:6] + u' (uso)' )
            layer.setAbstract(u"Edificio procedente del Sistema de Informacion Geografica de la Universidad de Alicante (SIGUA)")
    def calazim(self):
        layer = iface.activeLayer()
        field = QgsField('id', QVariant.Double)

        cal = QgsAuxiliaryStorage()
        auxlyr = cal.createAuxiliaryLayer(field, layer)
        layer.setAuxiliaryLayer(auxlyr)
        auxLayer = layer.auxiliaryLayer()
        vdef = QgsPropertyDefinition("azim", 1, "azimute",
                                     "calcula angulo azimute", "angulo")
        auxLayer.addAuxiliaryField(vdef)
        auxFields = auxLayer.fields()
        features = layer.getFeatures()
        for feature in features:
            geom = feature.geometry()
            ombb = geom.orientedMinimumBoundingBox()
            auxFeature = QgsFeature(auxFields)
            auxFeature['ASPK'] = feature['id']
            angazim = ombb[2]
            if ombb[4] < ombb[3]:
                angazim = ombb[2] - 90
                if angazim < 0:
                    angazim = ombb[2] + 90
            auxFeature['angulo_azim'] = angazim
            '''
            auxFeature['lado_lar'] = ombb[3]*1000
            auxFeature['lado_alt'] = ombb[4]*1000
            auxFeature['ver_boll'] = invertido
            '''
            auxLayer.addFeature(auxFeature)
            print("testeaqui")
Esempio n. 16
0
    def initMask(self, layout):

        layer = iface.activeLayer()  # load the layer as you want
        ext = iface.mapCanvas().extent()
        #ext = layer.extent()
        xmin = ext.xMinimum()
        xmax = ext.xMaximum()
        ymin = ext.yMinimum()
        ymax = ext.yMaximum()
        coords = "%f,%f,%f,%f" % (xmin, xmax, ymin, ymax)
        self.extent = QtWidgets.QLineEdit()
        self.extent.setText(coords)
        TitleLayout("Raster extent", self.extent, layout)

        self.res = QtWidgets.QLineEdit()
        xres = (xmax - xmin) / 100
        yres = (ymax - ymin) / 100
        self.res.setText(str(xres) + ',' + str(yres))
        TitleLayout("Raster resolution X,Y (m)", self.res, layout)

        self.valin = QtWidgets.QLineEdit()
        self.valin.setText(str(50))
        TitleLayout("Resolution inside in m", self.valin, layout)

        self.valout = QtWidgets.QLineEdit()
        self.valout.setText(str(10000))
        TitleLayout("Resolution outside in m", self.valout, layout)

        self.runLayout = CancelRunLayout(self, "calculate", self.apply_mask,
                                         layout)
        self.runLayout.runButton.setEnabled(True)
        self.setLayout(layout)
Esempio n. 17
0
    def endDrawLine(self):
        iface.actionToggleEditing().triggered.disconnect(self.endDrawLine)
        self.show()
        vlayer = iface.activeLayer()

        selection = vlayer.getFeatures()
        count = vlayer.featureCount()
        #print("当前选择层有特征数:%d" % count)
        for feature in selection:
            geom = feature.geometry()
            geomSingleType = QgsWkbTypes.isSingleType(geom.wkbType())
            if geom.type() == QgsWkbTypes.LineGeometry:
                if geomSingleType:
                    x = geom.asPolyline()
                    print("Line: ", x, "length: ", geom.length())
                    pstr_list = []
                    for index in range(len(x) - 1):
                        resStr = "{},{},{},{}".format(x[index].x(),
                                                      x[index].y(),
                                                      x[index + 1].x(),
                                                      x[index + 1].y())
                        pstr_list.append(resStr)

                    print(pstr_list)
                    self.startEndPointEdt.setText(';'.join(pstr_list))
Esempio n. 18
0
    def save_color_map(self):
        """
        Save the currently open color-map as a qml-file into the project folder.
        :return:
        :rtype:
        """
        from mole import extensions

        layer = iface.activeLayer()
        selected_layer = self.layers_dropdown.currentText()
        if layer.name() != selected_layer:
            layer = layer_interaction.find_layer_by_name(selected_layer)

        out_path = os.path.dirname(layer.publicSource())
        out_path = os.path.join(out_path, layer.name() + '.qml')
        self.update_color_values()
        entry_written = self.color_entry_manager.write_color_map_as_qml(layer.name(), out_path)
        if entry_written:
            self.message_label.setStyleSheet(_fromUtf8("color: green;"))
            self.message_label.setText('Success - Legend was successfully written to \n\t"{}".'.format(out_path))
        else:
            self.message_label.setStyleSheet(_fromUtf8("color: red;"))
            self.message_label.setText('Failure - Could not write legend to to \n\t"{}".'.format(out_path))
        activeextensions = extensions.by_layername(layer.name())
        try:
            activeextensions[0].colortable = out_path
        except:
            pass
Esempio n. 19
0
    def paste(self):
        paste_dect = self.field_list
        paste_layer = iface.activeLayer()
        paste_field = paste_layer.fields().names()
        paste_sel = paste_layer.selectedFeatures()

        count = paste_layer.selectedFeatureCount()

        if count != 0:

            if paste_layer.isEditable():

                for paste_feature in paste_sel:
                    for f in paste_field:
                        if str(f) in paste_dect:
                            my_key = str(f)
                            my_value = str(paste_dect.get(my_key))
                            #print(my_key+"::"+ my_value)

                            paste_feature.setAttribute(
                                paste_feature.fieldNameIndex(my_key), my_value)
                    paste_layer.updateFeature(paste_feature)

                self.iface.messageBar().pushMessage(
                    "Pasted attributes succesfully")
                self.field_list = dict()
                self.pasteAction.setEnabled(False)

            else:
                self.iface.messageBar().pushMessage("layer is not editable")

        else:
            self.iface.messageBar().pushMessage("Select atleast one feature")
    def run(self):
        """Run method that identifies counties and display"""

       # Create the dialog with elements (after translation) and keep reference
        if self.first_start == True:
            self.first_start = False
            self.dlg = shapefile_loaderDialog()
        self.dlg.label.setText("")
        layer = iface.activeLayer()
        name1 =""
        #cc1 = []
        #for i in range(0, 47):
        feat = layer.getFeature(19)
        name1 = feat['NAME_1']
            #cc1 = feat['CC_1']
        #mbsa_id = 1
        #mbsa_ind = cc1.index[mbsa_id]
        #mbsa_name = name1[]
            
        message = "YOU ARE FROM {} COUNTY.".format(name1)
        self.dlg.label.setText(message)
                
        

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed

        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass
Esempio n. 21
0
    def onOk(self):
      self.ui.textEdit.clear()
      self.ui.view.scene().clear()
            
      aLayer = iface.activeLayer()   
      
      if aLayer is None:
	QMessageBox.warning(self, unicode("DiagLeg"),
				  unicode("Please select a Layer and try again!"),
				  QMessageBox.Ok
				  );
	return
      
      provider = aLayer.dataProvider()
      	
      listFields = []
      fields = aLayer.pendingFields()
      
      for i in range(fields.count()):
	field = fields[i]
	listFields.append(field.name())
    
      #First we create the system temp to get the name, and then a .qml created by Qgis when it saved the style
      f = tempfile.NamedTemporaryFile(delete=True)      
      aLayer.saveNamedStyle(f.name);
                  
      strTmp=f.name+".qml"      
      
      self.importDOM(strTmp,listFields)      
     
      #Remember to delete both files!
      f.close()
      b=QFile(strTmp).remove()
Esempio n. 22
0
    def save_color_map(self):
        """
        Save the currently open color-map as a qml-file into the project folder.
        :return:
        :rtype:
        """
        from mole import extensions

        layer = iface.activeLayer()
        selected_layer = self.layers_dropdown.currentText()
        if layer.name() != selected_layer:
            layer = layer_interaction.find_layer_by_name(selected_layer)

        out_path = os.path.dirname(layer.publicSource())
        out_path = os.path.join(out_path, layer.name() + '.qml')
        self.update_color_values()
        entry_written = self.color_entry_manager.write_color_map_as_qml(
            layer.name(), out_path)
        if entry_written:
            self.message_label.setStyleSheet(_fromUtf8("color: green;"))
            self.message_label.setText(
                'Success - Legend was successfully written to \n\t"{}".'.
                format(out_path))
        else:
            self.message_label.setStyleSheet(_fromUtf8("color: red;"))
            self.message_label.setText(
                'Failure - Could not write legend to to \n\t"{}".'.format(
                    out_path))
        activeextensions = extensions.by_layername(layer.name())
        try:
            activeextensions[0].colortable = out_path
        except:
            pass
Esempio n. 23
0
def spaceBarPressed():
    global myIt, activeLayerId
    aLayer = iface.activeLayer()
    if not aLayer or not aLayer.type() == QgsMapLayer.VectorLayer:
        iface.messageBar().pushInfo(
            "Feature iterator",
            "First select a vector layer in the layers panel.")
        return
    if activeLayerId != aLayer.id():
        activeLayerId = aLayer.id()
        myIt = None
    if not myIt:
        request = QgsFeatureRequest().setFlags(
            QgsFeatureRequest.NoGeometry).setNoAttributes()
        myIt = aLayer.getFeatures(request)

    feat = next(myIt, None)
    if feat:
        aLayer.selectByIds([feat.id()])
        if aLayer.geometryType() == QgsWkbTypes.PointGeometry:
            iface.actionPanToSelected().trigger()  # Pan to points
        else:
            iface.actionZoomToSelected().trigger()  # Zoom to the rest
    else:
        iface.messageBar().pushInfo("Feature iterator",
            "We reached the last feature of this layer already.\n" + \
            "If you want to restart press the Escape key.")
Esempio n. 24
0
    def run_write_csv(self):
        """Run method that performs all the real work"""

        # initializes the logger, makes it available here, but also in the
        # fmsf_hms_utils operations by using logging.getLogger("fmsf2hms")
        logger = make_logger()

        self.dlg = WriteCSVDialog()
        self.dlg.outputDirectoryButton.clicked.connect(
            self.select_output_directoy)

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()

        if result:

            res_type = self.dlg.buttonGroup.checkedButton().text()
            out_dir = self.dlg.outputDirectory.text()
            logger.debug(res_type)

            layer = iface.activeLayer()
            dw = HMSDataWriter(layer, res_type)

            output = dw.write_csv(out_dir)
            iface.messageBar().pushMessage("Success",
                                           "CSV created: " + output,
                                           level=Qgis.Success,
                                           duration=0)
Esempio n. 25
0
def dms (lat, lon):
    """
    Add a point at the lat and lon for the current layer using DMS notation
    """

    lat,lon = lat, lon

    l_lat = lat.upper().split()
    l_lon = lon.upper().split()

    # need to add validation tests

    if l_lat[3] == 'N':
        ddlat = float(l_lat[0])+(float(l_lat[1])/60)+float(l_lat[2])/3600
    elif l_lat[3] == 'S':
        ddlat = (float(l_lat[0])+float(l_lat[1])/60+float(l_lat[2])/3600)*-1
    else:
        ddlat = '0'

    if l_lon [3] == 'E':
        ddlon = float(l_lon[0])+float(l_lon[1])/60+float(l_lon[2])/3600
    elif l_lon[3] == 'W':
        ddlon = (float(l_lon[0])+float(l_lon[1])/60+float(l_lon[2])/3600)*-1
    else:
        ddlon = '0'

    layer = iface.activeLayer()
    f = QgsFeature(layer.pendingFields())
    geom = QgsGeometry.fromPoint(QgsPoint(ddlon,ddlat))
    f.setGeometry(geom)
    layer.addFeature(f)
    iface.mapCanvas().refresh()
Esempio n. 26
0
    def __init__(self, alg, in_place=False, parent=None):
        super().__init__(parent)

        self.feedback_dialog = None
        self.in_place = in_place
        self.active_layer = None

        self.context = None
        self.feedback = None

        self.setAlgorithm(alg)
        self.setMainWidget(self.getParametersPanel(alg, self))

        if not self.in_place:
            self.runAsBatchButton = QPushButton(QCoreApplication.translate("AlgorithmDialog", "Run as Batch Process…"))
            self.runAsBatchButton.clicked.connect(self.runAsBatch)
            self.buttonBox().addButton(self.runAsBatchButton, QDialogButtonBox.ResetRole) # reset role to ensure left alignment
        else:
            self.active_layer = iface.activeLayer()
            self.runAsBatchButton = None
            has_selection = self.active_layer and (self.active_layer.selectedFeatureCount() > 0)
            self.buttonBox().button(QDialogButtonBox.Ok).setText(QCoreApplication.translate("AlgorithmDialog", "Modify Selected Features")
                                                                 if has_selection else QCoreApplication.translate("AlgorithmDialog", "Modify All Features"))
            self.buttonBox().button(QDialogButtonBox.Close).setText(QCoreApplication.translate("AlgorithmDialog", "Cancel"))
            self.setWindowTitle(self.windowTitle() + ' | ' + self.active_layer.name())
Esempio n. 27
0
def execute_in_place(alg, parameters, context=None, feedback=None):
    """Executes an algorithm modifying features in-place, if the INPUT
    parameter is not defined, the current active layer will be used as
    INPUT.

    :param alg: algorithm to run
    :type alg: QgsProcessingAlgorithm
    :param parameters: parameters of the algorithm
    :type parameters: dict
    :param context: context, defaults to None
    :param context: QgsProcessingContext, optional
    :param feedback: feedback, defaults to None
    :param feedback: QgsProcessingFeedback, optional
    :raises QgsProcessingException: raised when the layer is not editable or the layer cannot be found in the current project
    :return: a tuple with true if success and results
    :rtype: tuple
    """

    if feedback is None:
        feedback = QgsProcessingFeedback()
    if context is None:
        context = dataobjects.createContext(feedback)

    if not 'INPUT' in parameters or not parameters['INPUT']:
        parameters['INPUT'] = iface.activeLayer()
    ok, results = execute_in_place_run(alg, parameters, context=context, feedback=feedback)
    if ok:
        if isinstance(parameters['INPUT'], QgsProcessingFeatureSourceDefinition):
            layer = alg.parameterAsVectorLayer({'INPUT': parameters['INPUT'].source}, 'INPUT', context)
        elif isinstance(parameters['INPUT'], QgsVectorLayer):
            layer = parameters['INPUT']
        if layer:
            layer.triggerRepaint()
    return ok, results
Esempio n. 28
0
    def guardarValor(self):
        autenticado = self.validarAuth()
        if autenticado:

            if self.dockwidget.tableWidgetAtributosEdit.rowCount() > 0:

                #Obtenemos las propiedades de la capa
                self.capa = iface.activeLayer()
                self.capaActual = self.capa
                self.features = self.capaActual.selectedFeatures()[0]

                #Activamos el modo de edicion
                self.capaActual.startEditing()

                for x in range(0, len(self.features.attributes())):
                    self.features[
                        x] = self.dockwidget.tableWidgetAtributosEdit.item(
                            x, 1).text()

                self.capaActual.updateFeature(self.features)
                self.capaActual.commitChanges()
                self.createAlert('Se guardo correctamente',
                                 QMessageBox.Information,
                                 'Edicion de atributos')
                self.actualizarCapa()
            else:
                self.createAlert("Necesitas seleccionar una capa",
                                 QMessageBox.Warning, 'Edicion de atributos')

        elif autenticado == False:
            self.createAlert("Tu inicio de sesion expiro", QMessageBox.Warning,
                             'Sesion expiro edicion de atributos')

        print('se presiono el boton de guarda valor')
Esempio n. 29
0
    def selection_changed(self) -> None:

        try:
            # Obtenim una llista de les Features seleccionades a la capa activa del mapa
            layer = iface.activeLayer()
            if not layer: return
            selected_features = layer.selectedFeatures()

            # Revisem si l'usuari no ha seleccionat res, en aquest cas deixem d'executar
            if len(selected_features) == 0:
                return

            # Get primary key
            field_id = tools_gw.execute_procedure('gw_fct_getpkeyfield',
                                                  f"'{layer.name()}'")

            list_ids = []
            # Desem l'ID de l'últim Feature seleccionat i ho mostrem a la consola
            for i in selected_features:
                attr_id = i.attribute(field_id)
                list_ids.append(attr_id)

            tools_qt.set_widget_text(self.dlg, self.dlg.lbl_selected_items,
                                     ','.join(list_ids))

        except Exception as e:
            tools_log.log_warning(f"Exception: {type(e).__name__}, {e}")

        finally:
            # Tanquem la subscripció de l'event per evitar la duplicació
            iface.mapCanvas().selectionChanged.disconnect(
                self.selection_changed)
            iface.actionPan().trigger()
Esempio n. 30
0
    def __init__(self, alg, in_place=False, parent=None):
        super().__init__(parent)

        self.feedback_dialog = None
        self.in_place = in_place
        self.active_layer = None

        self.context = None
        self.feedback = None

        self.setAlgorithm(alg)
        self.setMainWidget(self.getParametersPanel(alg, self))

        if not self.in_place:
            self.runAsBatchButton = QPushButton(
                QCoreApplication.translate("AlgorithmDialog",
                                           "Run as Batch Process…"))
            self.runAsBatchButton.clicked.connect(self.runAsBatch)
            self.buttonBox().addButton(self.runAsBatchButton,
                                       QDialogButtonBox.ResetRole
                                       )  # reset role to ensure left alignment
        else:
            self.active_layer = iface.activeLayer()
            self.runAsBatchButton = None
            has_selection = self.active_layer and (
                self.active_layer.selectedFeatureCount() > 0)
            self.buttonBox().button(QDialogButtonBox.Ok).setText(
                QCoreApplication.
                translate("AlgorithmDialog", "Modify Selected Features"
                          ) if has_selection else QCoreApplication.
                translate("AlgorithmDialog", "Modify All Features"))
            self.buttonBox().button(QDialogButtonBox.Close).setText(
                QCoreApplication.translate("AlgorithmDialog", "Cancel"))
            self.setWindowTitle(self.windowTitle() + ' | ' +
                                self.active_layer.name())
    def run(self):
        """Run method that performs all the real work"""

        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start == True:
            self.first_start = False
            self.dlg = CreateLayerFromSelectedDialog()

        # show the dialog
        # self.dlg.show()
        # Run the dialog event loop

        # Skip the dialog box
        result = True

        if result:
            # Get current active layer and copy style
            layer = iface.activeLayer()
            iface.actionCopyLayerStyle().trigger()

            # Create in memory layer from selected features
            memory_layer = layer.materialize(QgsFeatureRequest().setFilterFids(
                layer.selectedFeatureIds()))
            memory_layer.setName(memory_layer.name() + " Selection")

            # Add layer and paste style
            QgsProject.instance().addMapLayer(memory_layer)
            iface.actionPasteLayerStyle().trigger()
Esempio n. 32
0
    def setCellWrapper(self, row, column, wrapper, context):
        self.wrappers[row - 1][column] = wrapper

        widget_context = QgsProcessingParameterWidgetContext()
        widget_context.setProject(QgsProject.instance())
        if iface is not None:
            widget_context.setActiveLayer(iface.activeLayer())
            widget_context.setMapCanvas(iface.mapCanvas())

        widget_context.setMessageBar(self.parent.messageBar())

        if isinstance(self.alg, QgsProcessingModelAlgorithm):
            widget_context.setModel(self.alg)
        wrapper.setWidgetContext(widget_context)
        wrapper.registerProcessingContextGenerator(self.context_generator)

        # For compatibility with 3.x API, we need to check whether the wrapper is
        # the deprecated WidgetWrapper class. If not, it's the newer
        # QgsAbstractProcessingParameterWidgetWrapper class
        # TODO QGIS 4.0 - remove
        is_cpp_wrapper = not issubclass(wrapper.__class__, WidgetWrapper)
        if is_cpp_wrapper:
            widget = wrapper.createWrappedWidget(context)
        else:
            widget = wrapper.widget

        self.tblParameters.setCellWidget(row, column, widget)
Esempio n. 33
0
 def updateForCurrentLayer(self):
     layer = iface.activeLayer()        
     sld = ""
     geostyler = ""
     mapbox = ""
     mapserver = ""
     warnings = []
     if layer is not None:
         if (isinstance(layer, QgsRasterLayer) or
                 (isinstance(layer, QgsVectorLayer) and layer.isSpatial())):
             sld, _, sld_warnings = layerStyleAsSld(layer)
             geostyler, icons, sprites, geostyler_warnings = convert(layer)
             geostyler = json.dumps(geostyler, indent=4)
             mapbox, _, mapbox_warnings = layerStyleAsMapbox(layer)
             mapserver, _, _, mapserverWarnings = layerStyleAsMapfile(layer)
             warnings = set()
             warnings.update(sld_warnings)
             warnings.update(geostyler_warnings)
             warnings.update(mapbox_warnings)
             warnings.update(mapserverWarnings)
     self.txtSld.setText(sld)
     self.txtGeostyler.setText(geostyler)
     self.txtMapbox.setText(mapbox)
     self.txtMapserver.setText(mapserver)
     self.txtWarnings.setPlainText("\n".join(warnings))
Esempio n. 34
0
def execute_in_place(alg, parameters, context=None, feedback=None):
    """Executes an algorithm modifying features in-place, if the INPUT
    parameter is not defined, the current active layer will be used as
    INPUT.

    :param alg: algorithm to run
    :type alg: QgsProcessingAlgorithm
    :param parameters: parameters of the algorithm
    :type parameters: dict
    :param context: context, defaults to None
    :param context: QgsProcessingContext, optional
    :param feedback: feedback, defaults to None
    :param feedback: QgsProcessingFeedback, optional
    :raises QgsProcessingException: raised when the layer is not editable or the layer cannot be found in the current project
    :return: a tuple with true if success and results
    :rtype: tuple
    """

    if not 'INPUT' in parameters or not parameters['INPUT']:
        parameters['INPUT'] = iface.activeLayer()
    ok, results = execute_in_place_run(alg,
                                       parameters,
                                       context=context,
                                       feedback=feedback)
    if ok:
        parameters['INPUT'].triggerRepaint()
    return ok, results
Esempio n. 35
0
    def use_active_layer(self):
        """
        Loads coordinates extent of the active layer.
        """
        iface.actionPan().trigger()
        layers = iface.mapCanvas().layers()
        chosen_layer = str(self.layersBox.currentText())
        for layer in layers:
            if str(layer.name()) == chosen_layer:
                crs = self.format_crs_str(layer.crs().authid())
                ex_layer = layer.extent()
                east = round(ex_layer.xMaximum(), 1)
                north = round(ex_layer.yMaximum(), 1)
                west = round(ex_layer.xMinimum(), 1)
                south = round(ex_layer.yMinimum(), 1)
                spatial_extent = {
                    "west": west,
                    "east": east,
                    "north": north,
                    "south": south,
                    "crs": crs
                }
                str_format = str(spatial_extent).replace("'", '"')
                self.processgraphSpatialExtent.setText(str_format)

        if not iface.activeLayer():
            self.iface.messageBar().pushMessage(
                "Please open a new layer to get extent from.", duration=5)
def updateField():
    maCouche = iface.activeLayer()
    vYear = u"year_end"
    vStatus = u"fk_status"
    for feature in maCouche.getFeatures(QgsFeatureRequest(int([%$id%]))):
        msgBox = QtGui.QMessageBox()
        if feature[vStatus] == 13002:
            text_arch = u"L'objet ID = [%$id%] de la couche '" + str(maCouche.name()) + u"' a déjà été archivé en " + str(feature[vYear])
            msgBox.setText(text_arch)
            msgBox.exec_()
        if feature[vStatus] != 13002:
            input_rep = QtGui.QInputDialog()
            year_end, ok = input_rep.getInt(None, u"Annee d'archivage ", u"indiquez l'ann\xe9e d'archive (4 chiffres)", datetime.now().year, 1800,2999, 1)
            if ok:
                if not maCouche.isEditable():
                    maCouche.startEditing()
                feature[vStatus] = 13002
                feature[vYear] = year_end
                if iface.openFeatureForm(maCouche, feature):
                    maCouche.updateFeature(feature)
                    text = u"L'objet ID = [%$id%] de la couche '" + str(maCouche.name()) + u"' \xe9t\xe9 archiv\xe9 en " + str(year_end)
                    msgBox.setText(text)
                    msgBox.exec_()
                else:
                    pass
            else:
                pass
        else:
            pass
Esempio n. 37
0
    def __init__(self, edit_dialog):
        """Constructor"""
        BulkLoadChanges.__init__(self, edit_dialog)
        # set editing to edit polygon
        iface.actionSelect().trigger()
        selecttools = iface.attributesToolBar().findChildren(QToolButton)
        # selection actions
        iface.building_toolbar.addSeparator()
        for sel in selecttools:
            if sel.text() == "Select Feature(s)":
                for a in sel.actions()[0:3]:
                    iface.building_toolbar.addAction(a)
        iface.building_toolbar.show()

        self.disable_UI_functions()
        if len(iface.activeLayer().selectedFeatures()) > 0:
            if self.is_correct_selections():
                self.get_selections()
                self.enable_UI_functions()
                self.populate_edit_comboboxes()
                self.select_comboboxes_value()
            else:
                self.edit_dialog.ids = []
                self.edit_dialog.building_outline_id = None
                self.disable_UI_functions()
Esempio n. 38
0
    def getParameterValues(self):
        parameters = {}

        if self.mainWidget() is None:
            return parameters

        for param in self.algorithm().parameterDefinitions():
            if param.flags() & QgsProcessingParameterDefinition.FlagHidden:
                continue
            if not param.isDestination():

                if self.in_place and param.name() == 'INPUT':
                    parameters[param.name()] = iface.activeLayer()
                    continue

                try:
                    wrapper = self.mainWidget().wrappers[param.name()]
                except KeyError:
                    continue

                # For compatibility with 3.x API, we need to check whether the wrapper is
                # the deprecated WidgetWrapper class. If not, it's the newer
                # QgsAbstractProcessingParameterWidgetWrapper class
                # TODO QGIS 4.0 - remove
                if issubclass(wrapper.__class__, WidgetWrapper):
                    widget = wrapper.widget
                else:
                    widget = wrapper.wrappedWidget()

                if widget is None:
                    continue

                value = wrapper.parameterValue()
                parameters[param.name()] = value

                if not param.checkValueIsAcceptable(value):
                    raise AlgorithmDialogBase.InvalidParameterValue(
                        param, widget)
            else:
                if self.in_place and param.name() == 'OUTPUT':
                    parameters[param.name()] = 'memory:'
                    continue

                dest_project = None
                if not param.flags() & QgsProcessingParameterDefinition.FlagHidden and \
                        isinstance(param, (QgsProcessingParameterRasterDestination,
                                           QgsProcessingParameterFeatureSink,
                                           QgsProcessingParameterVectorDestination)):
                    if self.mainWidget().checkBoxes[param.name()].isChecked():
                        dest_project = QgsProject.instance()

                value = self.mainWidget().outputWidgets[
                    param.name()].getValue()
                if value and isinstance(value,
                                        QgsProcessingOutputLayerDefinition):
                    value.destinationProject = dest_project
                if value:
                    parameters[param.name()] = value

        return self.algorithm().preprocessParameters(parameters)
Esempio n. 39
0
def execute_in_place(alg, parameters, context=None, feedback=None):
    """Executes an algorithm modifying features in-place, if the INPUT
    parameter is not defined, the current active layer will be used as
    INPUT.

    :param alg: algorithm to run
    :type alg: QgsProcessingAlgorithm
    :param parameters: parameters of the algorithm
    :type parameters: dict
    :param context: context, defaults to None
    :param context: QgsProcessingContext, optional
    :param feedback: feedback, defaults to None
    :param feedback: QgsProcessingFeedback, optional
    :raises QgsProcessingException: raised when the layer is not editable or the layer cannot be found in the current project
    :return: a tuple with true if success and results
    :rtype: tuple
    """

    if feedback is None:
        feedback = QgsProcessingFeedback()
    if context is None:
        context = dataobjects.createContext(feedback)

    if 'INPUT' not in parameters or not parameters['INPUT']:
        parameters['INPUT'] = iface.activeLayer()
    ok, results = execute_in_place_run(alg, parameters, context=context, feedback=feedback)
    if ok:
        if isinstance(parameters['INPUT'], QgsProcessingFeatureSourceDefinition):
            layer = alg.parameterAsVectorLayer({'INPUT': parameters['INPUT'].source}, 'INPUT', context)
        elif isinstance(parameters['INPUT'], QgsVectorLayer):
            layer = parameters['INPUT']
        if layer:
            layer.triggerRepaint()
    return ok, results
Esempio n. 40
0
 def filter_selection(self):
     '''
     filter the active layer by selected objects
     '''
     if not self.login:
         return
     # either name of layer or group have to match a category
     active_layer = iface.activeLayer()
     categories = self.categories.keys()
     layer_error = (u'Sie müssen im Layerfenster einen '
                    u'Layer auswählen, wahlweise aus den Gruppen '
                    u'Einrichtungen oder Filter.')
     if not active_layer:
         QtGui.QMessageBox.information(self, 'Fehler', layer_error)
         return
     else:
         layer_name = active_layer.name()
         if layer_name in categories:
             category = layer_name
         else:
             project_tree = QgsProject.instance().layerTreeRoot()
             layer_item = project_tree.findLayer(active_layer.id())
             group = layer_item.parent()
             group_name = group.name()
             if group_name in categories:
                 category = group_name
             else:
                 QtGui.QMessageBox.information(self, 'Fehler', layer_error)
                 return
         selected_feats = active_layer.selectedFeatures()
         if not selected_feats:
             msg = (u'Im ausgewählten Layer {} sind keine '
                    u'Einrichtungen selektiert.'.format(layer_name))
             QtGui.QMessageBox.information(self, 'Fehler', msg)
             return
 
         parent_group = get_group('Filter')
         subgroup = get_group(category, parent_group)
         ids = [str(f.attribute('sel_id')) for f in selected_feats]
         name, ok = QtGui.QInputDialog.getText(
             self, 'Filter', 'Name des zu erstellenden Layers',
             text=get_unique_layer_name(category, subgroup))
         if not ok:
             return
         
         subset = 'sel_id in ({})'.format(','.join(ids))
         layer = QgsVectorLayer(active_layer.source(), name, "postgres")
         remove_layer(name, subgroup)
         
         QgsMapLayerRegistry.instance().addMapLayer(layer, False)
         subgroup.addLayer(layer)
         layer.setSubsetString(subset)
         symbology = SimpleSymbology(self.colors[category], shape='triangle')
         symbology.apply(layer)
         self.copy_editor_attrs(active_layer, layer)
Esempio n. 41
0
def point_at(x, y):
    """
    Add a point at the x and y for the current layer
    """
    x, y = float(x), float(y)
    layer = iface.activeLayer()
    f = QgsFeature(layer.pendingFields())
    geom = QgsGeometry.fromPoint(QgsPoint(x, y))
    f.setGeometry(geom)
    layer.addFeature(f)
    iface.mapCanvas().refresh()
Esempio n. 42
0
    def select_output_file(self):
        global nameloadfile
        filename     = QFileDialog.getOpenFileName(self.dlg, "Select output file ","", '*.*')
        nameloadfile = start_rwt.format_rwt_file(filename,self)
        layer        = iface.activeLayer()   # Cria uma layer 
        start_rwt.update_rwt_form(layer,self,filename)
        
#        if nameloadfile=='StAMPs':
#            start_rwt.update_stp_rwt_form(layer,self,filename)
#        
        print"estou no selectfile:",nameloadfile
Esempio n. 43
0
def point_at_dms(lat, lon):
    """
    Add a point at the lat and lon for the current layer using DMS notation
    """

    ddlat, ddlon = dms_to_dd(lat, lon)

    layer = iface.activeLayer()
    f = QgsFeature(layer.pendingFields())
    geom = QgsGeometry.fromPoint(QgsPoint(ddlon, ddlat))
    f.setGeometry(geom)
    layer.addFeature(f)
    iface.mapCanvas().refresh()
Esempio n. 44
0
 def canvasPressEvent(self, e):
     #QMessageBox.information(None, "hello", "click!")
     pt_canvas = e.pos()
     pt_map = self.toMapCoordinates(pt_canvas)
     geom = QgsGeometry.fromPoint(pt_map)
     minDist = 99999999
     minName = ""
     layer = iface.activeLayer()
     for f in layer.getFeatures():
         dist = f.geometry().distance(geom)
         if dist < minDist:
             minDist = dist
             minName = f["name"]
     QMessageBox.information(None, "Minimal distance", "%s -- only %f" % (minName, minDist))
Esempio n. 45
0
def execute_in_place(alg, parameters, context=None, feedback=None):
    """Executes an algorithm modifying features in-place in the active layer.

    The input layer must be editable or an exception is raised.

    :param alg: algorithm to run
    :type alg: QgsProcessingAlgorithm
    :param parameters: parameters of the algorithm
    :type parameters: dict
    :param context: context, defaults to None
    :param context: QgsProcessingContext, optional
    :param feedback: feedback, defaults to None
    :param feedback: QgsProcessingFeedback, optional
    :raises QgsProcessingException: raised when the layer is not editable or the layer cannot be found in the current project
    :return: a tuple with true if success and results
    :rtype: tuple
    """

    parameters['INPUT'] = QgsProcessingFeatureSourceDefinition(iface.activeLayer().id(), True)
    ok, results = execute_in_place_run(alg, iface.activeLayer(), parameters, context=context, feedback=feedback)
    if ok:
        iface.activeLayer().triggerRepaint()
    return ok, results
Esempio n. 46
0
 def change_color(self):
     layer = iface.activeLayer()
     # create a new single symbol renderer
     symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
     renderer = QgsSingleSymbolRendererV2(symbol)
     # define un simbolo
     properties = {'color': 'green', 'color_border': 'black'}
     symbol_layer = QgsSimpleFillSymbolLayerV2.create(properties)
     # assign the symbol layer to the symbol
     renderer.symbols()[0].changeSymbolLayer(0, symbol_layer)
     # assign the renderer to the layer
     layer.setRendererV2(renderer)
     self.iface.legendInterface().refreshLayerSymbology(layer)
     #self.iface.mapCanvas().freeze(True)
     self.iface.mapCanvas().refresh()
     layer.triggerRepaint()
Esempio n. 47
0
def feature_move(x, y):
    """
    Moves a point to the x and y for the current layer
    """
    x, y = float(x), float(y)

    layer = iface.activeLayer()
    selection = layer.selectedFeatures()
    update = False
    for feature in selection:
        fgeom = feature.geometry()
        geom = QgsGeometry.fromPoint(QgsPoint(x, y))
        same = fgeom.asPoint() == geom.asPoint()
        if not same:
            layer.changeGeometry(feature.id(), geom)
            update = True
    if update:
        iface.mapCanvas().refresh()
Esempio n. 48
0
def feature_move_dms(lat, lon):
    """
    Add a point at the lat and lon for the current layer using DMS notation
    """

    ddlat, ddlon = dms_to_dd(lat, lon)

    layer = iface.activeLayer()
    selection = layer.selectedFeatures()
    update = False
    for feature in selection:
        fgeom = feature.geometry()
        geom = QgsGeometry.fromPoint(QgsPoint(ddlon, ddlat))
        same = fgeom.asPoint() == geom.asPoint()
        if not same:
            layer.changeGeometry(feature.id(), geom)
            update = True
    if update:
        iface.mapCanvas().refresh()
Esempio n. 49
0
    def tematico2(self):
        layer = iface.activeLayer()
        # array de dptos
        idx = layer.fieldNameIndex('txt_dpto_sigua')
        dptosArr = layer.uniqueValues( idx )
        total = len(dptosArr)
        if total < 3:
            coloresArr = colorbrewer.Set3[3]
        elif total <= 12:
            coloresArr = colorbrewer.Set3[total]
        else:
            exceso = total - 12
            if exceso < 3:
                coloresArr = colorbrewer.Set3[12] + colorbrewer.Paired[3]
            else:
                coloresArr = colorbrewer.Set3[12] + colorbrewer.Paired[exceso]

        print coloresArr
        dptoDic = {}
        for i in range(0, len(dptosArr)):
            if  dptosArr[i] == u"GESTIÓN DE ESPACIOS":
                dptoDic[dptosArr[i]] = ("white", dptosArr[i])
            else:
                dptoDic[dptosArr[i]] = (coloresArr[i], dptosArr[i])

        #print dptoDic
        categories = []
        for estancia, (color, label) in dptoDic.items():
            sym = QgsSymbolV2.defaultSymbol(layer.geometryType())
            sym.setColor(QColor(color))
            category = QgsRendererCategoryV2(estancia, sym, label)
            categories.append(category)

        field = "txt_dpto_sigua"
        renderer = QgsCategorizedSymbolRendererV2(field, categories)
        layer.setRendererV2(renderer)
        QgsMapLayerRegistry.instance().addMapLayer(layer)
        layer.triggerRepaint()
        layer.setName(layer.name()[:6] + u" (organización)")
        # actualizar metadatos
        layer.setTitle(u"Planta de edificio " + layer.name()[:6] + u" (organización)")
        layer.setAbstract(u"Edificio procedente del Sistema de Información Geográfica de la Universidad de Alicante (SIGUA)")
Esempio n. 50
0
 def labelCodigo(self):
     layer = iface.activeLayer()
     palyr = QgsPalLayerSettings()
     palyr.readFromLayer(layer)
     palyr.enabled = True
     palyr.bufferDraw = True
     palyr.bufferColor = QColor("white")
     palyr.bufferSize = 1
     palyr.scaleVisibility = True
     palyr.scaleMax = 2000
     palyr.isExpression = True
     palyr.fieldName =  'if( "codigo" NOT LIKE \'%000\', right(  "codigo" ,3),"")'
     palyr.size = 15
     palyr.textColor = QColor("black")
     palyr.drawLabels = True
     palyr.fitInPolygonOnly = True  #solo dibuja las label que caben dentro del poligono
     palyr.placement = QgsPalLayerSettings.OverPoint
     palyr.setDataDefinedProperty(QgsPalLayerSettings.Size, True, True, '7', '')
     palyr.writeToLayer(layer)
     iface.mapCanvas().refresh()
# coding: utf-8
from PyQt4.QtCore import Qt
from qgis.gui import QgsMapTool
from qgis.utils import iface


class SendPointToolCoordinates(QgsMapTool):
    """ Enable to return coordinates from clic in a layer.
    """
    def __init__(self, canvas, layer):
        """ Constructor.
        """
        QgsMapTool.__init__(self, canvas)
        self.canvas = canvas
        self.layer = layer
        self.setCursor(Qt.CrossCursor)

    def canvasReleaseEvent(self, event):
        point = self.toLayerCoordinates(self.layer, event.pos())

        print(point.x(), point.y())

layer, canvas = iface.activeLayer(), iface.mapCanvas()

send_point_tool_coordinates = SendPointToolCoordinates(
    canvas,
    layer
)
canvas.setMapTool(send_point_tool_coordinates)
# coding: utf-8
from qgis.gui import QgsMultiBandColorRendererWidget
from qgis.utils import iface

layer = iface.activeLayer()  # From a multiband raster
multi_band_color_renderer_widget = QgsMultiBandColorRendererWidget(
    layer
)

multi_band_color_renderer_widget.show()
Esempio n. 53
0
def table(tablename):
    if not tablename.strip():
        layer = iface.activeLayer()
    else:
        layer = layer_by_name(tablename)
    iface.showAttributeTable(layer)
Esempio n. 54
0
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from qgis.core import *
from qgis.utils import iface

wb = QgsVectorLayer('/data/world_borders.shp', 'world_borders', 'ogr')
QgsMapLayerRegistry.instance().addMapLayer(wb)

active_layer = iface.activeLayer()
renderer = active_layer.rendererV2()
symbol = renderer.symbol()
symbol.setColor(QColor(Qt.red))
iface.mapCanvas().refresh()
iface.legendInterface().refreshLayerSymbology(active_layer)

iface.showAttributeTable(iface.activeLayer())
# coding: utf-8
from qgis.core import QgsStyleV2
from qgis.gui import QgsRendererRulePropsDialog
from qgis.utils import iface

layer = iface.activeLayer()  # You need a QgsVectorLayer with Rule-based style
canvas = iface.mapCanvas()
root_rule = layer.rendererV2().rootRule()
renderer_rule_props_dialog = QgsRendererRulePropsDialog(
    root_rule.children()[1].children()[0],  # QgsRuleBasedRendererV2.Rule
    layer,  # QgsVectorLayer
    QgsStyleV2.defaultStyle(),  # QgsStyleV2
    None,  # parent QWidget, optional
    canvas  # QgsMapCanvas, optional
)

renderer_rule_props_dialog.show()
# Looking for all the neighbours of the selected polygon

from qgis.utils import iface

# Replace the values below with values from your layer.
# Change the _NAME_FIELD value to the name of your identifier field
_NAME_FIELD = 'NAME_2'

layer = iface.activeLayer()

# Create a dictionary of all features
feature_dict = {f.id(): f for f in layer.getFeatures()}

# Set the myfeature value to the value of your polygon
myfeature = 'Wade Hampton' 

# Loop through all features and find features that touch each feature
for f in feature_dict.values():
    if f[_NAME_FIELD] == myfeature:
        geom = f.geometry()
        # Find all features that intersect the bounding box of the current feature.
        intersecting_ids = index.intersects(geom.boundingBox())
        # Initalize neighbors list
        neighbors = []
        for intersecting_id in intersecting_ids:
            # Look up the feature from the dictionary
            intersecting_f = feature_dict[intersecting_id]
            if (f != intersecting_f and
                not intersecting_f.geometry().disjoint(geom)):
                neighbors.append(intersecting_f[_NAME_FIELD])
        f[_NEW_NEIGHBORS_FIELD] = ','.join(neighbors)
# coding: utf-8
from PyQt4.QtGui import QDialog, QTableView
from qgis.core import QgsVectorLayerCache
from qgis.gui import (QgsAttributeTableModel,
                      QgsAttributeTableView,
                      QgsAttributeTableFilterModel)
from qgis.utils import iface

new_dialog = QDialog()
new_dialog.resize(800, 600)

vector_layer_cache = QgsVectorLayerCache(iface.activeLayer(), 10000)
attribute_table_model = QgsAttributeTableModel(vector_layer_cache)
attribute_table_model.loadLayer()

attribute_table_filter_model = QgsAttributeTableFilterModel(
    iface.mapCanvas(),
    attribute_table_model
)
attribute_table_view = QgsAttributeTableView(new_dialog)
attribute_table_view.setModel(attribute_table_filter_model)

new_dialog.show()

# Or display the attribute_table_model with QTableView (pure QT solution)
table_view = QTableView()
table_view.setModel(attribute_table_model)
table_view.show()
# coding: utf-8
from qgis.gui import QgsActionMenu
from qgis.utils import iface

layer = iface.activeLayer()
if iface.activeLayer().actions().size() > 0:
    features = layer.dataProvider().getFeatures()
    feat1 = features.next()
    action_menu = QgsActionMenu(
        layer,
        feat1
    )
    print(feat1.id())

    action_menu.show()
    print(action_menu.actions())
    feat2 = features.next()
    action_menu.setFeature(feat2)
    print(feat2.id())
else:
    print('No action for this layer')