Пример #1
0
    def __init__(self, parent, layer):
        '''
        Constructor
        '''
        QDialog.__init__(self, parent)
        self.ui = Ui_VectorLayerProPertyDialog()
        self.ui.setupUi(self)

        self.ui.txtLayerName.setText(layer.name())
        self.ui.txtLayerSource.setText(layer.source())
        self.ui.txtCrs.setText(layer.crs().authid() + " - " +
                               layer.crs().description())
        self.ui.btnCrsSelect.clicked.connect(self.selectCrs)
        self.mCrs = layer.crs()
        self.vLayer = layer
        self.ui.mOptionsListWidget.currentRowChanged.connect(
            self.changeStackWidget)
        ''' init RenderV2 Widget'''
        self.mRendererDialog = QgsRendererV2PropertiesDialog(
            self.vLayer, QgsStyleV2.defaultStyle(), True)
        self.ui.stackedWidget.insertWidget(1, self.mRendererDialog)
        self.ui.buttonBox.accepted.connect(self.OK)

        frame_Label = QFrame()
        verticalLayout_Label = QVBoxLayout(frame_Label)
        self.mLabelWidget = QgsFieldExpressionWidget()
        self.mLabelWidget.setLayer(layer)
        verticalLayout_Label.addWidget(self.mLabelWidget)

        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        verticalLayout_Label.addItem(spacerItem)
        frame_Label.setLayout(verticalLayout_Label)
        self.ui.stackedWidget.insertWidget(2, frame_Label)
    def on_mShapeStyleButton_clicked(self):
        if self.timeStart != 0:
            self.timeEnd = time.time()
            print self.timeEnd
            if self.timeEnd - self.timeStart <= 2:
                self.timeStart = 0
                return
        if (not self.mComposerShape):
            return

        # use the atlas coverage layer, if any
        coverageLayer = self.atlasCoverageLayer()

        newSymbol = self.mComposerShape.shapeStyleSymbol().clone()
        d = QgsSymbolV2SelectorDialog(newSymbol, QgsStyleV2.defaultStyle(),
                                      coverageLayer, self)
        d.setExpressionContext(self.mComposerShape.createExpressionContext())

        if (d.exec_() == QDialog.Accepted):

            self.mComposerShape.beginCommand(QString("Shape style changed"))
            self.mComposerShape.setShapeStyleSymbol(newSymbol)
            self.updateShapeStyle()
            self.mComposerShape.endCommand()
        self.timeStart = time.time()
Пример #3
0
def ramp_color_rgb(values, feature, parent):
    """
        Return only the rgb part of a defined color ramp
        
        <h4>Syntax</h4>
        <p>ramp_color_rgb(<i>ramp_name,value</i>)</p>

        <h4>Arguments</h4>
        <p><i>  ramp_name</i> &rarr; the name of the color ramp as a string, for example 'Spectral'.<br>
        <i>  value</i> &rarr; the position on the ramp to select the color from as a real number between 0 and 1.<br></p>
        
        <h4>Example</h4>
        <p><!-- Show example of function.-->
             ramp_color_rgb('Spectral',0.3) &rarr; '253,190,115'</p>
        
        <h4>Note:</h4>
        <p>The color ramps available vary between QGIS installations.  This function
        may not give the expected results if you move your Quantum project.
        </p>
    """  
    ramp_name = values[0]
    ramp_position = values[1]
    
    ramp = QgsStyleV2.defaultStyle().colorRampRef(ramp_name)
    if not ramp:
        parent.setEvalErrorString( QObject.tr( '"{}" is not a valid color ramp'.format(ramp_name)))
        return QColor(0,0,0).name()
    
    value, error = getFloat(ramp_position)
    if error:
        parent.setEvalErrorString(error)
    
    color = ramp.color(value)
    return "{},{},{}".format(color.red(), color.green(), color.blue())
Пример #4
0
    def on_mPageStyleButton_clicked(self):
        if self.timeStart != 0:
            self.timeEnd = time.time()
            print self.timeEnd
            if self.timeEnd - self.timeStart <= 2:
                self.timeStart = 0
                return
        if ( not self.mComposition ):
            return

        coverageLayer = None
        # use the atlas coverage layer, if any
        if ( self.mComposition.atlasComposition().enabled() ):
            coverageLayer = self.mComposition.atlasComposition().coverageLayer()

        newSymbol = self.mComposition.pageStyleSymbol().clone()
        if ( not newSymbol ):
            newSymbol = QgsFillSymbolV2()
        d = QgsSymbolV2SelectorDialog( newSymbol, QgsStyleV2.defaultStyle(), coverageLayer, self)
        d.setExpressionContext( self.mComposition.createExpressionContext() )

        if ( d.exec_() == QDialog.Accepted ):

            self.mComposition.setPageStyleSymbol( newSymbol )
            self.updatePageStyle()
        self.timeStart = time.time()
    def validate(self):
        """Check to see that all required gui elements have been entered and are valid."""
        try:
            errorList = []
            rast_sym = rs.RASTER_SYMBOLOGY[self.cboType.currentText()]
            # check to see if the colour ramp is installed
            qgs_styles = QgsStyleV2().defaultStyle()

            if rast_sym['colour_ramp'] != '' and rast_sym[
                    'colour_ramp'] not in qgs_styles.colorRampNames():
                errorList = [
                    'PAT symbology does not exist. See user manual for install instructions'
                ]

            if len(errorList) > 0:
                raise ValueError(errorList)

        except ValueError as e:
            self.cleanMessageBars(True)
            if len(errorList) > 0:
                for i, ea in enumerate(errorList):
                    self.send_to_messagebar(unicode(ea),
                                            level=QgsMessageBar.WARNING,
                                            duration=(i + 1) * 5)
                return False

        return True
    def on_mLineStyleButton_clicked(self):
        if self.timeStart != 0:
            self.timeEnd = time.time()
            print self.timeEnd
            if self.timeEnd - self.timeStart <= 2:
                self.timeStart = 0
                return
        if (not self.mArrow):
            return

        newSymbol = self.mArrow.lineSymbol().clone()
        d = QgsSymbolV2SelectorDialog(newSymbol, QgsStyleV2.defaultStyle(),
                                      None, self)
        d.setExpressionContext(self.mArrow.createExpressionContext())

        if (d.exec_() == QDialog.Accepted):

            self.mArrow.beginCommand(QString("Arrow line style changed"))
            self.mArrow.setLineSymbol(newSymbol)
            self.updateLineSymbolMarker()
            self.mArrow.endCommand()
            self.mArrow.update()
        else:
            pass
            # delete newSymbol;
        self.timeStart = time.time()
Пример #7
0
def ramp_color_rgb(values, feature, parent):
    """
        Return only the rgb part of a defined color ramp
        
        <p><h4>Syntax</h4>
        ramp_color_rgb(<i>ramp_name,value</i>)</p>

        <p><h4>Arguments</h4>
        <i>  ramp_name</i> &rarr; the name of the color ramp as a string, for example 'Spectral'.<br>
        <i>  value</i> &rarr; the position on the ramp to select the color from as a real number between 0 and 1.<br></p>
        
        <p><h4>Example</h4>
        <!-- Show example of function.-->
             ramp_color_rgb('Spectral',0.3) &rarr; '253,190,115'</p>
        
        <p><h4>Note:</h4>
        The color ramps available vary between QGIS installations.  This function
        may not give the expected results if you move your Quantum project.
        </p>
    """
    ramp_name = values[0]
    ramp_position = values[1]

    ramp = QgsStyleV2.defaultStyle().colorRampRef(ramp_name)
    if not ramp:
        parent.setEvalErrorString(QObject.tr('"{}" is not a valid color ramp'.format(ramp_name)))
        return QColor(0, 0, 0).name()

    value, error = getFloat(ramp_position)
    if error:
        parent.setEvalErrorString(error)

    color = ramp.color(value)
    return "{},{},{}".format(color.red(), color.green(), color.blue())
 def on_mMapMarkerButton_clicked(self):
     if ( self.mMarkerSymbol == None ):
         return
     markerSymbol = self.mMarkerSymbol.clone() 
     dlg = QgsSymbolV2SelectorDialog ( markerSymbol, QgsStyleV2.defaultStyle(), None, self )
     if ( dlg.exec_()!= QDialog.Rejected ):
         self.mMarkerSymbol = markerSymbol
         self.updateCenterIcon()
Пример #9
0
 def changeColorRamp(self, idx):
     currentItem = self.dlg.TECAttrList.currentItem()
     if not idx == 0:
         selectedRamp = self.dlg.colorRampSelector.currentColorRamp()
         currentItem.setColorRamp(selectedRamp.clone())
     else:
         greyRamp = QgsStyleV2().defaultStyle().colorRamp('Greys').clone()
         currentItem.setColorRamp(greyRamp)
Пример #10
0
 def arrangeColorRamp(self, attr_ramp):
     defaultStyle = QgsStyleV2().defaultStyle()
     ramp = dict()
     for item in attr_ramp:
         if type(item) == str:
             ramp.update({item: defaultStyle.colorRamp('Greys')})
         else:
             ramp.update({item[0]: item[1]})
     self.colorRamp = ramp
Пример #11
0
def create_join_renderer(layer, field, classes, mode, color='Blues'):
    symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
    style = QgsStyleV2().defaultStyle()
    colorRamp = style.colorRampRef(color)
    renderer = QgsGraduatedSymbolRendererV2.createRenderer(
        layer, field, classes, mode, symbol, colorRamp)
    label_format = create_join_label_format(2)
    renderer.setLabelFormat(label_format)
    return renderer
Пример #12
0
 def setAttributeList(self):
     greyRamp = QgsStyleV2().defaultStyle().colorRamp('Greys').clone()
     for attr in self.attributes:
         if type(attr) == str:
             item = attrItem(self.dlg.TECAttrList, attr, greyRamp)
             self.dlg.TECAttrList.addItem(item)
             self.svgNameList.append(item.svgName)
             if item.svgName not in self.iconList:
                 self.iconList.append(item.svgName)
         elif type(attr) == list:
             item = attrItem(self.dlg.TECAttrList, attr[0], attr[1])
             self.dlg.TECAttrList.addItem(item)
             if item.svgName not in self.iconList:
                 self.iconList.append(item.svgName)
Пример #13
0
    def __init__(self, parent=None):
        super(MapWidget, self).__init__(parent)
        self.setupUi(self)

        self.canvas.setCanvasColor(Qt.white)
        self.canvas.enableAntiAliasing(True)
        self.canvas.setWheelAction(QgsMapCanvas.WheelZoomToMouseCursor)
        self.canvas.mapRenderer().setLabelingEngine(QgsPalLabeling())
        self.style = QgsStyleV2.defaultStyle()
        self.styledlg = None
        self.bridge = QgsLayerTreeMapCanvasBridge(QgsProject.instance().layerTreeRoot(), self.canvas)
        self.bridge.setAutoSetupOnFirstLayer(False)
        QgsProject.instance().writeProject.connect(self.bridge.writeProject)
        QgsProject.instance().readProject.connect(self.bridge.readProject)

        self.applyStyleButton.pressed.connect(self.apply_style)
Пример #14
0
    def __init__(self, parent=None):
        super(MapWidget, self).__init__(parent)
        self.setupUi(self)

        self.canvas.setCanvasColor(Qt.white)
        self.canvas.enableAntiAliasing(True)
        self.canvas.setWheelAction(QgsMapCanvas.WheelZoomToMouseCursor)
        self.canvas.mapRenderer().setLabelingEngine(QgsPalLabeling())
        self.style = QgsStyleV2.defaultStyle()
        self.styledlg = None
        self.bridge = QgsLayerTreeMapCanvasBridge(QgsProject.instance().layerTreeRoot(), self.canvas)
        self.bridge.setAutoSetupOnFirstLayer(False)
        QgsProject.instance().writeProject.connect(self.bridge.writeProject)
        QgsProject.instance().readProject.connect(self.bridge.readProject)

        self.applyStyleButton.pressed.connect(self.apply_style)
Пример #15
0
    def edit_style(self):
        from qgis.gui import QgsSingleSymbolRendererV2Widget
        from qgis.core import QgsStyleV2

        style = QgsStyleV2()
        sw = QStackedWidget()
        sw.addWidget
        for i in range(3):
            w = QgsSingleSymbolRendererV2Widget(self.__layer, style,
                                                self.__renderers[i])
            sw.addWidget(w)

        combo = QComboBox()
        combo.addItem("Points")
        combo.addItem("Line")
        combo.addItem("Polygon")

        combo.currentIndexChanged[int].connect(sw.setCurrentIndex)
        combo.setCurrentIndex(self.__render_type)

        dlg = QDialog()

        vbox = QVBoxLayout()

        btn = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        btn.accepted.connect(dlg.accept)
        btn.rejected.connect(dlg.reject)

        vbox.addWidget(combo)
        vbox.addWidget(sw)
        vbox.addWidget(btn)

        dlg.setLayout(vbox)
        dlg.resize(800, 600)

        r = dlg.exec_()
        if r == QDialog.Accepted:
            self.set_render_type(combo.currentIndex())
            self.set_renderer(sw.currentWidget().renderer().clone())
            self.update()
# coding:utf-8
from qgis.core import QgsStyleV2
from qgis.gui import QgsGraduatedSymbolRendererV2Widget
from qgis.utils import iface

layer = iface.activeLayer()
canvas = iface.mapCanvas()
graduated_symbol_renderer_v2_widget = QgsGraduatedSymbolRendererV2Widget(
    layer,
    QgsStyleV2.defaultStyle(),
    layer.rendererV2()
)

graduated_symbol_renderer_v2_widget.setMapCanvas(canvas)


def on_widget_changed():
    layer.setRendererV2(
        graduated_symbol_renderer_v2_widget.renderer()
    )
    if canvas.isCachingEnabled():
        layer.setCacheImage(None)
        layer.triggerRepaint()
    else:
        canvas.refresh()

graduated_symbol_renderer_v2_widget.widgetChanged.connect(on_widget_changed)
graduated_symbol_renderer_v2_widget.show()
Пример #17
0
# coding: utf-8
from qgis.core import QgsStyleV2
from qgis.gui import QgsRendererV2PropertiesDialog
from qgis.utils import iface

layer = iface.activeLayer()

renderer_v2_properties = QgsRendererV2PropertiesDialog(
    layer, QgsStyleV2.defaultStyle(), True)

renderer_v2_properties.show()
Пример #18
0
# coding: utf-8
from qgis.core import QgsStyleV2
from qgis.gui import QgsSymbolV2SelectorDialog
from qgis.utils import iface

layer = iface.activeLayer()
symbol_v2_selector_dialog = QgsSymbolV2SelectorDialog(
    layer.rendererV2().symbol(),  # Symbol,
    QgsStyleV2.defaultStyle(),  # Style,
    layer,  # QgsVectorLayer
    None,  # Parent
    False  # Embedded
)

symbol_v2_selector_dialog.show()
Пример #19
0
# coding: utf-8
from qgis.core import QgsStyleV2
from qgis.gui import QgsStyleV2ExportImportDialog

style_v2_export_import_dialog = QgsStyleV2ExportImportDialog(
    QgsStyleV2.defaultStyle())

style_v2_export_import_dialog.show()
# coding: utf-8
from qgis.core import QgsStyleV2
from qgis.gui import QgsStyleV2ManagerDialog

style_v2_manager_dialog = QgsStyleV2ManagerDialog(QgsStyleV2.defaultStyle())

style_v2_manager_dialog.show()
Пример #21
0
    def __init__(self, app):
        """
        constructor
        - initialize UI elements
        - connect UI elements to callback            
        """
        super(WidgetResult, self).__init__()
        self.ui = Ui_widgetResult()
        self.ui.setupUi(self)

        # create canvas
        self.canvas = QgsMapCanvas(self.ui.widget_map)
        self.canvas.setGeometry(
            0,  # x
            self.ui.widget_map_menu_l.x() +
            self.ui.widget_map_menu_l.height(),  # y  
            self.ui.widget_map.width() - 2 * UI_PADDING,  # width
            self.ui.widget_map.width() - 2 * UI_PADDING  # height
        )

        self.canvas.setCanvasColor(Qt.white)
        self.canvas.enableAntiAliasing(True)
        self.canvas.mapRenderer().setProjectionsEnabled(True)
        self.canvas.mapRenderer().setDestinationCrs(
            QgsCoordinateReferenceSystem(
                4326, QgsCoordinateReferenceSystem.PostgisCrsId))
        self.canvas.zoomNextStatusChanged.connect(self.checkRendering)
        self.canvas.xyCoordinates.connect(self.currentLocation)
        self.registry = QgsMapLayerRegistry.instance()

        self.map_layers = [None] * len(self.LAYER_NAMES)
        self.map_layer_renderer = [None] * len(self.LAYER_NAMES)
        for idx, str_style in enumerate(self.LAYER_STYLES):
            rdoc = QDomDocument("renderer")
            rdoc.setContent(str_style)
            self.map_layer_renderer[idx] = QgsFeatureRendererV2.load(
                rdoc.firstChild().toElement())

        # populate export list
        self.ui.cb_export_format.clear()
        for export_format in self.EXPORT_FORMATS.keys():
            self.ui.cb_export_format.addItem(export_format)

        # style object required for QgsRendererV2PropertiesDialog
        self.style = QgsStyleV2()

        # create the map tools
        self.toolPan = QgsMapToolPan(self.canvas)
        self.toolZoomIn = QgsMapToolZoom(self.canvas, False)  # false = in
        self.toolZoomOut = QgsMapToolZoom(self.canvas, True)  # true = out
        self.toolInfo = QgsMapToolEmitPoint(self.canvas)
        self.toolInfo.canvasClicked.connect(self.showInfo)
        self.canvas.setMapTool(self.toolPan)

        # additional
        self.dlgResultDetail = DialogResult()
        self.dlgResultDetail.setModal(True)

        # set link to application main controller
        self.app = app

        # reset project
        self._project = None

        # default export setting
        self.export_format = ExportTypes.Shapefile

        # connect slots (ui event)
        self.ui.btn_zoom_full.clicked.connect(self.mapZoomFull)
        self.ui.btn_zoom_in.clicked.connect(self.mapZoomIn)
        self.ui.btn_zoom_out.clicked.connect(self.mapZoomOut)
        self.ui.btn_stop.clicked.connect(self.stopRendering)
        self.ui.btn_zoom_layer.clicked.connect(self.mapZoomLayer)
        self.ui.btn_pan.clicked.connect(self.mapPan)
        self.ui.btn_theme.clicked.connect(self.mapEditTheme)
        self.ui.btn_info.clicked.connect(self.mapIdentify)

        self.ui.btn_zoom_to_feature.clicked.connect(self.searchFeature)

        self.ui.cb_export_format.currentIndexChanged[str].connect(
            self.exportFormatChanged)
        self.ui.btn_export.clicked.connect(self.exportData)
        self.ui.btn_export_select_path.clicked.connect(self.selectExportFile)
Пример #22
0
def raster_apply_unique_value_renderer(raster_layer,
                                       band_num=1,
                                       n_decimals=0,
                                       color_ramp='',
                                       invert=False):
    """
    Apply a random colour to each each unique value for a raster band.

    In some case the unique values are floating, n_decimals allows these to be rounded for display

    Args:
        raster_layer (QgsRasterLayer): input raster layer
        band_num (int):    the band number used to determine unique values
        n_decimals (int):  number of decimals to round values to
    """
    qgsStyles = QgsStyleV2().defaultStyle()
    # check to see if the colour ramp is installed
    if color_ramp != '' and color_ramp not in qgsStyles.colorRampNames():
        raise ValueError(
            'PAT symbology does not exist. See user manual for install instructions'
        )

    # get unique values
    band = rasterio.open(raster_layer.source()).read(band_num, masked=True)
    uniq_vals = np.unique(band[band.mask == False])

    if n_decimals > 0:
        uniq_vals = np.around(list(uniq_vals), decimals=3)

    if color_ramp == '':
        rmp_colors = [
            QColor(*colour) for colour in random_colours(len(uniq_vals))
        ]
        #rmp_colors = random_colours(len(uniq_vals))

    else:
        # get an existing color ramp
        ramp = qgsStyles.colorRamp(color_ramp)

        rmp_colors = [ramp.color1().name()]  # the first
        rmp_colors += [ea.color.name() for ea in ramp.stops()]

        # check that the last colors not already there
        if rmp_colors[-1] != ramp.color2().name():
            rmp_colors += [ramp.color2().name()]

        if invert:
            rmp_colors = list(reversed(rmp_colors))

        #use this to create a matplotlib color ramp
        cmSeg = colors.LinearSegmentedColormap.from_list('myramp',
                                                         rmp_colors,
                                                         N=256)

        # get the colors distributed evenly across the ramp
        rmp_colors = [
            QColor(*cmSeg(idx, bytes=True))
            for idx in np.linspace(0, 1, len(uniq_vals))
        ]

    # instantiate the specialized ramp shader object
    col_rmp_shd = QgsColorRampShader()

    # name a type for the ramp shader. In this case, we use an INTERPOLATED shader:
    col_rmp_shd.setColorRampType(QgsColorRampShader.EXACT)
    qri = QgsColorRampShader.ColorRampItem

    sym_classes = []
    for class_val, class_color in zip(uniq_vals, rmp_colors):
        sym_classes.append(qri(class_val, class_color, str(class_val)))

    # assign the color ramp to our shader:
    col_rmp_shd.setColorRampItemList(sym_classes)

    # create a generic raster shader object:
    raster_shader = QgsRasterShader()
    # tell the generic raster shader to use the color ramp:
    raster_shader.setRasterShaderFunction(col_rmp_shd)

    # create a raster renderer object with the shader, specifying band number 1
    ps = QgsSingleBandPseudoColorRenderer(raster_layer.dataProvider(), 1,
                                          raster_shader)

    # assign the renderer to the raster layer:
    raster_layer.setRenderer(ps)

    # refresh
    raster_layer.triggerRepaint()
Пример #23
0
# coding:utf-8
from qgis.core import QgsStyleV2
from qgis.gui import QgsSingleSymbolRendererV2Widget
from qgis.utils import iface

layer = iface.activeLayer()
canvas = iface.mapCanvas()
single_symbol_renderer_v2_widget = QgsSingleSymbolRendererV2Widget(
    layer, QgsStyleV2.defaultStyle(), layer.rendererV2())

single_symbol_renderer_v2_widget.setMapCanvas(canvas)


def on_widget_changed():
    layer.setRendererV2(single_symbol_renderer_v2_widget.renderer())
    if canvas.isCachingEnabled():
        layer.setCacheImage(None)
        layer.triggerRepaint()
    else:
        canvas.refresh()


single_symbol_renderer_v2_widget.widgetChanged.connect(on_widget_changed)
single_symbol_renderer_v2_widget.show()
Пример #24
0
def check_pat_symbols():
    pat_xml = os.path.join(PLUGIN_DIR, 'PAT_Symbols.xml')
    if not os.path.exists(pat_xml):
        return

    loaded_date = read_setting(PLUGIN_NAME + "/PAT_SYMBOLOGY")
    if loaded_date is not None:
        loaded_date = datetime.strptime(loaded_date,'%Y-%m-%d %H:%M:%S')

    xml_date = datetime.fromtimestamp(os.path.getmtime(pat_xml)).replace(microsecond=0)

    if loaded_date is None or xml_date > loaded_date:
        style = QgsStyleV2.defaultStyle()

        # add a group if it doesn't exist.
        group_id = style.groupId('PAT')
        if group_id == 0:
            group_id = style.addGroup('PAT')

        xml_file = QFile(pat_xml)

        document = QDomDocument()
        if not document.setContent(xml_file):
            LOGGER.debug('Could not open file {}'.format(xml_file))
            return

        xml_file.close()

        document_element = document.documentElement()
        if document_element.tagName() != 'qgis_style':
            LOGGER.debug("File {} doesn't contain qgis styles".format(xml_file))
            return

        # Get all the symbols
        symbols = []
        symbols_element = document_element.firstChildElement('symbols')
        symbol_element = symbols_element.firstChildElement()
        while not symbol_element.isNull():
            if symbol_element.tagName() == 'symbol':
                symbol = QgsSymbolLayerV2Utils.loadSymbol(symbol_element)
                if symbol:
                    symbols.append({
                        'name': symbol_element.attribute('name'),
                        'symbol': symbol
                    })
            symbol_element = symbol_element.nextSiblingElement()

        # Get all the colorramps
        colorramps = []
        ramps_element = document_element.firstChildElement('colorramps')
        ramp_element = ramps_element.firstChildElement()
        while not ramp_element.isNull():
            if ramp_element.tagName() == 'colorramp':
                colorramp = QgsSymbolLayerV2Utils.loadColorRamp(ramp_element)
                if colorramp:
                    colorramps.append({
                        'name': ramp_element.attribute('name'),
                        'colorramp': colorramp
                    })

            ramp_element = ramp_element.nextSiblingElement()

        for symbol in symbols:
            if style.addSymbol(symbol['name'], symbol['symbol'], True):
                style.group(QgsStyleV2.SymbolEntity, symbol['name'], group_id)

        for colorramp in colorramps:
            if style.addColorRamp(colorramp['name'], colorramp['colorramp'], True):
                style.group(QgsStyleV2.ColorrampEntity, colorramp['name'], group_id)

        LOGGER.info(
            'Loaded {} symbols and {} colour ramps into group {}'.format(len(symbols), len(colorramps),
                                                                         style.groupName(group_id)))

        write_setting(PLUGIN_NAME + '/PAT_SYMBOLOGY', xml_date.strftime('%Y-%m-%d %H:%M:%S'))

    return
Пример #25
0
    def __init__(self, layer, renderer, parent=None):
        QDialog.__init__(self, parent)

        self.__layer = layer
        self.__renderer = renderer

        from qgis.gui import QgsSingleSymbolRendererV2Widget, QgsRuleBasedRendererV2Widget, QgsCategorizedSymbolRendererV2Widget, QgsGraduatedSymbolRendererV2Widget
        from qgis.core import QgsSingleSymbolRendererV2, QgsRuleBasedRendererV2, QgsCategorizedSymbolRendererV2, QgsGraduatedSymbolRendererV2
        from qgis.core import QgsStyleV2

        vbox = QVBoxLayout()
        hbox = QHBoxLayout()

        self.__combo = QComboBox()

        self.__load_btn = QPushButton("Charger style")
        self.__save_btn = QPushButton("Sauver style")
        self.__load_btn.clicked.connect(self.on_load_style)
        self.__save_btn.clicked.connect(self.on_save_style)
        hbox.addWidget(self.__combo)
        hbox.addWidget(self.__load_btn)
        hbox.addWidget(self.__save_btn)

        self.__sw = QStackedWidget()
        self.__classes = [(u"Symbole unique", QgsSingleSymbolRendererV2,
                           QgsSingleSymbolRendererV2Widget),
                          (u"Ensemble de règles", QgsRuleBasedRendererV2,
                           QgsRuleBasedRendererV2Widget),
                          (u"Catégorisé", QgsCategorizedSymbolRendererV2,
                           QgsCategorizedSymbolRendererV2Widget),
                          (u"Gradué", QgsGraduatedSymbolRendererV2,
                           QgsGraduatedSymbolRendererV2Widget)]
        self.__styles = [
            QgsStyleV2(),
            QgsStyleV2(),
            QgsStyleV2(),
            QgsStyleV2()
        ]
        for i, c in enumerate(self.__classes):
            name, cls, wcls = c
            w = wcls.create(self.__layer, self.__styles[i], self.__renderer)
            self.__sw.addWidget(w)
            self.__combo.addItem(name)

        self.__combo.currentIndexChanged.connect(self.__sw.setCurrentIndex)

        for i, c in enumerate(self.__classes):
            _, cls, _ = c
            if self.__renderer.__class__ == cls:
                self.__combo.setCurrentIndex(i)
                break

        btn = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        btn.accepted.connect(self.accept)
        btn.rejected.connect(self.reject)

        vbox.addLayout(hbox)
        vbox.addWidget(self.__sw)
        vbox.addWidget(btn)

        self.setLayout(vbox)
        self.resize(800, 600)
    def style_maps(self, layer=None, style_by=None):
        if layer is None:
            layer = self.layer
        if style_by is None:
            style_by = self.default_field_name
        symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
        # see properties at:
        # https://qgis.org/api/qgsmarkersymbollayerv2_8cpp_source.html#l01073
        symbol.setAlpha(1)  # opacity
        if isinstance(symbol, QgsMarkerSymbolV2):
            # do it only for the layer with points
            self._set_symbol_size(symbol)
            symbol.symbolLayer(0).setOutlineStyle(Qt.PenStyle(Qt.NoPen))

        style = get_style(layer, self.iface.messageBar())

        # this is the default, as specified in the user settings
        ramp = QgsVectorGradientColorRampV2(style['color_from'],
                                            style['color_to'])
        mode = style['mode']

        # in most cases, we override the user-specified setting, and use
        # instead a setting that was required by scientists
        if self.output_type in OQ_TO_LAYER_TYPES:
            default_qgs_style = QgsStyleV2().defaultStyle()
            default_color_ramp_names = default_qgs_style.colorRampNames()
            if self.output_type in ('dmg_by_asset', 'losses_by_asset',
                                    'avg_losses-stats'):
                # options are EqualInterval, Quantile, Jenks, StdDev, Pretty
                # jenks = natural breaks
                mode = QgsGraduatedSymbolRendererV2.Jenks
                ramp_type_idx = default_color_ramp_names.index('Reds')
                inverted = False
            elif self.output_type in ('hmaps', 'gmf_data', 'ruptures'):
                # options are EqualInterval, Quantile, Jenks, StdDev, Pretty
                if self.output_type == 'ruptures':
                    mode = QgsGraduatedSymbolRendererV2.Pretty
                else:
                    mode = QgsGraduatedSymbolRendererV2.EqualInterval
                ramp_type_idx = default_color_ramp_names.index('Spectral')
                inverted = True
            ramp = default_qgs_style.colorRamp(
                default_color_ramp_names[ramp_type_idx])
        graduated_renderer = QgsGraduatedSymbolRendererV2.createRenderer(
            layer,
            style_by,
            style['classes'],
            mode,
            symbol,
            ramp,
            inverted=inverted)
        label_format = graduated_renderer.labelFormat()
        # label_format.setTrimTrailingZeroes(True)  # it might be useful
        label_format.setPrecision(2)
        graduated_renderer.setLabelFormat(label_format, updateRanges=True)
        # add a class for 0 values, unless while styling ruptures
        if self.output_type != 'ruptures':
            VERY_SMALL_VALUE = 1e-20
            graduated_renderer.updateRangeLowerValue(0, VERY_SMALL_VALUE)
            symbol_zeros = QgsSymbolV2.defaultSymbol(layer.geometryType())
            symbol_zeros.setColor(QColor(240, 240, 240))  # very light grey
            if isinstance(symbol, QgsMarkerSymbolV2):
                # do it only for the layer with points
                self._set_symbol_size(symbol_zeros)
                symbol_zeros.symbolLayer(0).setOutlineStyle(
                    Qt.PenStyle(Qt.NoPen))
            zeros_min = 0.0
            zeros_max = VERY_SMALL_VALUE
            range_zeros = QgsRendererRangeV2(
                zeros_min, zeros_max, symbol_zeros,
                " %.2f - %.2f" % (zeros_min, zeros_max), True)
            graduated_renderer.addClassRange(range_zeros)
            graduated_renderer.moveClass(
                len(graduated_renderer.ranges()) - 1, 0)
        layer.setRendererV2(graduated_renderer)
        layer.setLayerTransparency(30)  # percent
        layer.triggerRepaint()
        self.iface.legendInterface().refreshLayerSymbology(layer)
        self.iface.mapCanvas().refresh()
 def __init__(self, collection_id):
     """Constructor of the base class."""
     BaseResourceHandler.__init__(self, collection_id)
     # Init the default style
     self.style = QgsStyle.defaultStyle()
Пример #28
0
# coding: utf-8
from qgis.core import QgsStyleV2
from qgis.gui import Qgs25DRendererWidget
from qgis.utils import iface

layer = iface.activeLayer()
renderer_25D_widget = Qgs25DRendererWidget(layer, QgsStyleV2.defaultStyle(),
                                           layer.rendererV2())

renderer_25D_widget.show()

renderer_25D_widget_create = Qgs25DRendererWidget.create(
    layer, QgsStyleV2.defaultStyle(), layer.rendererV2())

renderer_25D_widget_create.show()
Пример #29
0
 def setColorRampBox(self):
     style = QgsStyleV2().defaultStyle()
     self.colorRampSelector.populate(style)
     self.colorRampSelector.insertItem(0, 'default')
     self.colorRampSelector.setCurrentIndex(0)
# coding: utf-8
from PyQt4.QtGui import QDialog
from qgis.core import QgsStyleV2
from qgis.gui import QgsColorRampComboBox

# Create dialog and resize it
new_dialog = QDialog()
new_dialog.resize(800, 600)

style = QgsStyleV2().defaultStyle()

color_ramp_combo_box = QgsColorRampComboBox(new_dialog)
color_ramp_combo_box.populate(style)


def on_color_ramp_changed():
    print(color_ramp_combo_box.currentColorRamp())
    print(color_ramp_combo_box.currentText())
    print("Color ramp changed")


color_ramp_combo_box.currentIndexChanged.connect(on_color_ramp_changed)

new_dialog.show()
Пример #31
0
def raster_apply_classified_renderer(raster_layer,
                                     rend_type,
                                     num_classes,
                                     color_ramp,
                                     invert=False,
                                     band_num=1):

    # get an existing color ramp
    qgsStyles = QgsStyleV2().defaultStyle()

    # check to see if the colour ramp is installed
    if color_ramp != '' and color_ramp not in qgsStyles.colorRampNames():
        raise ValueError(
            'PAT symbology does not exist. See user manual for install instructions'
        )

    ramp = qgsStyles.colorRamp(color_ramp)

    rmp_colors = [ramp.color1().name()]  # the first
    rmp_colors += [ea.color.name() for ea in ramp.stops()]

    # check that the last colors not already there
    if rmp_colors[-1] != ramp.color2().name():
        rmp_colors += [ramp.color2().name()]
    if invert:
        rmp_colors = list(reversed(rmp_colors))

    # convert to qcolor
    rmp_colors = [QColor(col) for col in rmp_colors]

    band = rasterio.open(raster_layer.source()).read(band_num, masked=True)

    classes = []
    if rend_type.lower() == 'quantile':
        classes = np.interp(np.linspace(0, ma.count(band), num_classes + 1),
                            np.arange(ma.count(band)),
                            np.sort(ma.compressed(band)))

    elif rend_type.lower() == 'equal interval':
        classes, bin_width = np.linspace(np.nanmin(band),
                                         np.nanmax(band),
                                         num_classes + 1,
                                         endpoint=True,
                                         retstep=True)

    classes = [float('{:.3g}'.format(ea)) for ea in classes]

    del band

    #Apply raster layer enhancement/stretch
    stretch = QgsContrastEnhancement.StretchToMinimumMaximum
    limits = QgsRaster.ContrastEnhancementMinMax
    raster_layer.setContrastEnhancement(stretch, limits)

    # Create the symbology
    color_ramp_shd = QgsColorRampShader()
    color_ramp_shd.setColorRampType(QgsColorRampShader.DISCRETE)
    qri = QgsColorRampShader.ColorRampItem

    sym_classes = []
    low_class = 0

    for class_color, up_class in zip(rmp_colors, classes[1:]):
        if low_class == 0:
            sym_classes.append(
                qri(up_class, class_color, '<= {} '.format(up_class)))
        elif up_class == classes[-1]:
            sym_classes.append(
                qri(float("inf"), class_color, '> {} '.format(low_class)))
        else:
            sym_classes.append(
                qri(up_class, class_color,
                    '{} - {} '.format(low_class, up_class)))

        low_class = up_class

    color_ramp_shd.setColorRampItemList(sym_classes)

    #Apply symbology to layer
    raster_shader = QgsRasterShader()
    raster_shader.setRasterShaderFunction(color_ramp_shd)
    pseudo_renderer = QgsSingleBandPseudoColorRenderer(
        raster_layer.dataProvider(), 1, raster_shader)
    raster_layer.setRenderer(pseudo_renderer)
    raster_layer.triggerRepaint()
Пример #32
0
 def __init__(self, collection_id):
     """Constructor of the base class."""
     BaseResourceHandler.__init__(self, collection_id)
     # Initialize with the default style
     self.style = QgsStyle.defaultStyle()
Пример #33
0
# coding: utf-8
from PyQt4.QtGui import QMenu
from qgis.core import QgsStyleV2
from qgis.gui import QgsSymbolsListWidget
from qgis.utils import iface

layer = iface.activeLayer()
symbols_list_widget = QgsSymbolsListWidget(layer.rendererV2().symbol(),
                                           QgsStyleV2.defaultStyle(), QMenu(),
                                           None, layer)

symbols_list_widget.show()