コード例 #1
0
 def style_categorized(self, layer, style_by):
     # get unique values
     fni = layer.fieldNameIndex(style_by)
     unique_values = layer.dataProvider().uniqueValues(fni)
     # define categories
     categories = []
     for unique_value in unique_values:
         # initialize the default symbol for this geometry type
         symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
         # configure a symbol layer
         layer_style = {}
         layer_style['color'] = '%d, %d, %d' % (randrange(
             0, 256), randrange(0, 256), randrange(0, 256))
         layer_style['outline'] = '#000000'
         symbol_layer = QgsSimpleFillSymbolLayerV2.create(layer_style)
         # replace default symbol layer with the configured one
         if symbol_layer is not None:
             symbol.changeSymbolLayer(0, symbol_layer)
         # create renderer object
         category = QgsRendererCategoryV2(unique_value, symbol,
                                          str(unique_value))
         # entry for the list of category items
         categories.append(category)
     # create renderer object
     renderer = QgsCategorizedSymbolRendererV2(style_by, categories)
     # assign the created renderer to the layer
     if renderer is not None:
         layer.setRendererV2(renderer)
     layer.triggerRepaint()
     self.iface.legendInterface().refreshLayerSymbology(layer)
     self.iface.mapCanvas().refresh()
コード例 #2
0
ファイル: ui_elements.py プロジェクト: ChrFr/qgis_plugins
 def apply(self, layer):
     symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
     symbol_layer = QgsSimpleFillSymbolLayerV2.create({'color': self.color})
     if self.border_style:
         symbol_layer.setBorderStyle(self.border_style)
     self.renderer = QgsSingleSymbolRendererV2(symbol)
     self.renderer.symbols()[0].changeSymbolLayer(0, symbol_layer)
     super(SimpleFillSymbology, self).apply(layer)
コード例 #3
0
def vector_apply_unique_value_renderer(vector_layer, column):
    """Apply colours to each unique value for a vector layer column.

    source: https://gis.stackexchange.com/a/175114

    Args:
        vector_layer (QgsVectorLayer): A vector layer to apply unique symbology to.
        column (str): The column containing the unique values

    """

    categories = []
    uniq_vals = vector_layer.dataProvider().uniqueValues(
        vector_layer.fieldNameIndex(column))
    randcolors = random_colours(len(uniq_vals))

    for i, ea_value in enumerate(uniq_vals):
        # initialize the default symbol for this geometry type
        symbol = QgsSymbolV2.defaultSymbol(vector_layer.geometryType())

        # configure a symbol layer
        layer_style = {
            'color': '{}, {}, {}'.format(*randcolors[i]),
            'outline': '#000000'
        }

        symbol_layer = QgsSimpleFillSymbolLayerV2.create(layer_style)

        # replace default symbol layer with the configured one
        if symbol_layer is not None:
            symbol.changeSymbolLayer(0, symbol_layer)

        # create renderer object
        category = QgsRendererCategoryV2(ea_value, symbol, str(ea_value))

        # entry for the list of category items
        categories.append(category)

    # create renderer object
    renderer = QgsCategorizedSymbolRendererV2(column, categories)

    # assign the created renderer to the layer
    if renderer is not None:
        vector_layer.setRendererV2(renderer)

    # refresh
    vector_layer.triggerRepaint()
コード例 #4
0
    def saveParameters(self):
        self.updateDistricts()
        layers = self.iface.legendInterface().layers()
        selectedLayerIndex = self.dlgparameters.cmbActiveLayer.currentIndex()
        selectedLayer = layers[selectedLayerIndex]
        self.activeLayer = selectedLayer
        self.districts = self.dlgparameters.inpDistricts.value()
        self.activedistrict = 1
        self.dockwidget.lblActiveDistrict.setText("Active District: " +
                                                  str(self.activedistrict))
        self.dockwidget.sliderDistricts.setMinimum(1)
        self.dockwidget.sliderDistricts.setMaximum(self.districts)
        self.dockwidget.sliderDistricts.setValue(1)
        self.popfield = self.dlgparameters.cmbPopField.currentText()
        self.distfield = self.dlgparameters.cmbDistField.currentText()
        #        self.dispfield1 = self.dlgparameters.cmbDispField1.currentText()
        #       self.dispfield2 = self.dlgparameters.cmbDispField1.currentText()
        QgsMessageLog.logMessage("Popfield:" + str(self.popfield))
        self.totalpop = 0
        self.targetpop = 0
        for feature in self.activeLayer.getFeatures():
            self.totalpop = self.totalpop + feature[self.popfield]
        self.targetpop = int(self.totalpop / self.districts)
        self.targetpoppct = self.dlgparameters.inpTolerance.value()
        targetpoprem = int((self.targetpop / 100) * self.targetpoppct)
        self.targetpoplower = int(self.targetpop - targetpoprem)
        self.targetpophigher = int(self.targetpop + targetpoprem + 1)
        QgsMessageLog.logMessage("TargetPop:" + str(self.targetpop) + "(" +
                                 str(self.targetpoplower) + ", " +
                                 str(self.targetpophigher) + ")")
        QgsMessageLog.logMessage("Districts:" + str(self.districts))
        self.dockwidget.lblMainInfo.setText("Active Layer: " +
                                            self.activeLayer.name() +
                                            "\nActive District Field: " +
                                            self.distfield +
                                            "\nTarget Population: " +
                                            str(self.targetpop) + " (" +
                                            str(self.targetpoplower) + ", " +
                                            str(self.targetpophigher) + ")")
        self.attrdockwidget.tblPop.setRowCount(self.districts + 1)
        numDataFields = 0
        for d in dataFieldList:
            numDataFields = numDataFields + 1
            self.attrdockwidget.tblPop.setHorizontalHeaderItem(
                2 + numDataFields, QTableWidgetItem(d.name))
        self.attrdockwidget.tblPop.setColumnCount(4 + numDataFields)
        for r in range(0, self.districts + 1):
            chkBoxItem = QTableWidgetItem()
            chkBoxItem.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
            chkBoxItem.setCheckState(Qt.Unchecked)
            self.attrdockwidget.tblPop.setItem(r, 1, chkBoxItem)
        self.attrdockwidget.tblPop.setHorizontalHeaderLabels(
            ['#', 'Lock', 'Population', 'To Target'])
        numDataFields = 0
        for d in dataFieldList:
            numDataFields = numDataFields + 1
            if d.type == 1:
                self.attrdockwidget.tblPop.setHorizontalHeaderItem(
                    3 + numDataFields, QTableWidgetItem(d.name))
            else:
                self.attrdockwidget.tblPop.setHorizontalHeaderItem(
                    3 + numDataFields, QTableWidgetItem(d.name + '%'))

        if len(districtName) == 0:
            self.initializeElectorates()

        try:
            self.saveParametersToFile()
            QgsMessageLog.logMessage("Parameters file saved!")
        except:
            QgsMessageLog.logMessage("Parameters file could not be saved")

        if self.dlgparameters.chkStyleMap.isChecked():
            categories = []
            for cat in range(0, self.districts + 1):
                symbol = QgsSymbolV2.defaultSymbol(
                    self.activeLayer.geometryType())
                layer_style = {}
                layer_style['color'] = '%d, %d, %d' % (randrange(
                    0, 256), randrange(0, 256), randrange(0, 256))
                layer_style['outline'] = '#000000'
                symbol_layer = QgsSimpleFillSymbolLayerV2.create(layer_style)

                # replace default symbol layer with the configured one
                if symbol_layer is not None:
                    symbol.changeSymbolLayer(0, symbol_layer)

                # create renderer object
                category = QgsRendererCategoryV2(cat, symbol, str(cat))
                # entry for the list of category items
                categories.append(category)
            renderer = QgsCategorizedSymbolRendererV2(self.distfield,
                                                      categories)
            # assign the created renderer to the layer
            if renderer is not None:
                self.activeLayer.setRendererV2(renderer)

            self.activeLayer.triggerRepaint()
        self.updateFieldValues()
        self.updateTable()
        self.updateLockedFields()
        self.updateDistricts()
コード例 #5
0
    def __getQgsPolygonSymbolLayer(self, msstyle):
        props = {}
        type_marker = ''

        symbol = msstyle.get('symbol', False)
        if symbol:
            (type_marker, symbolname, msSymbol,
             props) = self.__getMsSymbol(symbol, props, True)

        opacity = self.__getMsOpacity(msstyle)
        color = self.__getMsColor(msstyle, props, opacity)
        self.__getMsOutlinecolor(msstyle, props, opacity)
        self.__getMsLinecap(msstyle, props)
        self.__getMsLinejoin(msstyle, props)
        self.__getMsPattern(msstyle, props)
        self.__getMsWidth(msstyle, props)
        self.__getMsOutline(msstyle, props)
        self.__getMsScale(msstyle, props)
        offset = self.__getMsOffset(msstyle, props)
        if not type_marker:
            #-linea sencilla exterior-#
            #-relleno simple (sin estilo de relleno preconfigurados)-#
            if not color:
                self.deleteProperties(props, _qgis.SIMPLE_LINE_SYMBOL_LAYER)
                qgsSymbol = QgsSimpleLineSymbolLayerV2.create(props)
            else:
                self.deleteProperties(props, _qgis.SIMPLE_FILL_SYMBOL_LAYER)
                qgsSymbol = QgsSimpleFillSymbolLayerV2.create(props)
            #-relleno de gradientes-#
            #el gradiente es para renderer por categorias continuas
            #no aplica, porque aca es para gradiente de un simbolo
        else:
            props_parent = {}
            self.__setMsOffsetXY(offset, props)
            self.__getMsAngle(msstyle, props, props_parent)
            gap = self.__getMsGap(msstyle)
            size = self.__getMsSize(msstyle, props)
            self.__getMarkerDisplacementAndRotate(msstyle, gap, size,
                                                  props_parent)

            geomtransform = msstyle.get('geomtransform', '').lower()
            if geomtransform == 'centroid':
                #-relleno de centroides-#
                self.__getMsAnchorpoint(msSymbol, props)
                qgsSubSymbol = self.__getQgsMarkerSubSymbol(
                    type_marker, msSymbol, size, props)
                #self.deleteProperties(props_parent, _qgis.CENTROID_FILL_SYMBOL_LAYER)
                qgsSymbol = QgsCentroidFillSymbolLayerV2.create({})
                qgsSymbol.setSubSymbol(qgsSubSymbol)
            elif not color:
                #-Linea exterior:linea de marcador-#
                self.__getMsAnchorpoint(msSymbol, props)
                qgsSubSymbol = self.__getQgsMarkerSubSymbol(
                    type_marker, msSymbol, size, props)
                self.deleteProperties(props_parent,
                                      _qgis.MARKER_LINE_SYMBOL_LAYER)
                qgsSymbol = QgsMarkerLineSymbolLayerV2.create(props_parent)
                qgsSymbol.setSubSymbol(qgsSubSymbol)
            elif type_marker == _ms.MS_SYMBOL_HATCH:
                if not props['use_custom_dash']:
                    #-relleno simple (con estilo de relleno)-#
                    self.deleteProperties(props,
                                          _qgis.SIMPLE_LINE_SYMBOL_LAYER)
                    qgsSymbol = QgsSimpleLineSymbolLayerV2.create(props)
                else:
                    #-Patron de relleno de linea-#
                    self.deleteProperties(props,
                                          _qgis.SIMPLE_LINE_SYMBOL_LAYER)
                    qgsSubSymbol = self.__getSubSymbol(
                        QgsLineSymbolV2, QgsSimpleLineSymbolLayerV2, QGis.Line,
                        props)
                    self.deleteProperties(props_parent,
                                          _qgis.LINE_PATTERN_FILL_SYMBOL_LAYER)
                    qgsSymbol = QgsLinePatternFillSymbolLayer.create(
                        props_parent)
                    qgsSymbol.setSubSymbol(qgsSubSymbol)
            elif type_marker == _ms.MS_SYMBOL_PIXMAP:
                #-relleno de imagen raster-#
                self.deleteProperties(props, _qgis.RASTER_FILL_SYMBOL_LAYER)
                qgsSymbol = QgsRasterFillSymbolLayer.create(props)
            elif type_marker == _ms.MS_SYMBOL_SVG:
                #-relleno SVG-#
                self.deleteProperties(props, _qgis.SIMPLE_LINE_SYMBOL_LAYER)
                qgsSubSymbol = self.__getSubSymbol(QgsLineSymbolV2,
                                                   QgsSimpleLineSymbolLayerV2,
                                                   QGis.Line, props)
                self.deleteProperties(props_parent,
                                      _qgis.SVG_FILL_SYMBOL_LAYER)
                qgsSymbol = QgsSVGFillSymbolLayer.create(props_parent)
                qgsSymbol.setSubSymbol(qgsSubSymbol)
            else:
                #-patron de relleno de puntos-#
                self.__getMsAnchorpoint(msSymbol, props)
                qgsSubSymbol = self.__getQgsMarkerSubSymbol(
                    type_marker, msSymbol, size, props)
                self.deleteProperties(props_parent,
                                      _qgis.POINT_PATTERN_FILL_SYMBOL_LAYER)
                qgsSymbol = QgsPointPatternFillSymbolLayer.create(props_parent)
                qgsSymbol.setSubSymbol(qgsSubSymbol)

        #qgsSymbol.setAlpha((opacity*1.0)/100)
        #print(props)
        return qgsSymbol