Exemplo n.º 1
0
    def run(self):
        """
        Start the images generation
        """

        main_dir_path = os.path.join(
            os.path.dirname(os.path.realpath(__file__)), os.pardir)

        s = QSettings()
        svg_paths = []
        svg_paths.append(os.path.join(main_dir_path, 'result/libreria/svg/'))
        s.setValue('svg/searchPathsForSVG', svg_paths)

        style = QgsStyle.defaultStyle()
        style.importXml(
            os.path.join(main_dir_path, 'result/libreria/libreria.xml'))

        with open(self.list_file) as f:
            for i, symbol_name in enumerate(f.readlines()):

                symbol_name = symbol_name.strip()
                symbol = self._get_symbol(symbol_name)

                pixmap = self._create_pixmap_from_symbol(
                    symbol,
                    *self._calculate_scale_factor_padding(symbol, symbol_name))

                self._save_pixmap_into_png(
                    pixmap,
                    os.path.join(self.output_directory, symbol_name + ".png"))
Exemplo n.º 2
0
    def testRenderZRange(self):
        layer = QgsPointCloudLayer(
            unitTestDataPath() + '/point_clouds/ept/sunshine-coast/ept.json',
            'test', 'ept')
        self.assertTrue(layer.isValid())

        renderer = QgsPointCloudAttributeByRampRenderer()
        renderer.setAttribute('Intensity')
        renderer.setMinimum(200)
        renderer.setMaximum(1000)
        ramp = QgsStyle.defaultStyle().colorRamp("Viridis")
        shader = QgsColorRampShader(200, 1000, ramp)
        shader.classifyColorRamp()
        renderer.setColorRampShader(shader)

        layer.setRenderer(renderer)
        layer.renderer().setPointSize(2)
        layer.renderer().setPointSizeUnit(QgsUnitTypes.RenderMillimeters)

        mapsettings = QgsMapSettings()
        mapsettings.setOutputSize(QSize(400, 400))
        mapsettings.setOutputDpi(96)
        mapsettings.setDestinationCrs(layer.crs())
        mapsettings.setExtent(QgsRectangle(498061, 7050991, 498069, 7050999))
        mapsettings.setLayers([layer])
        mapsettings.setZRange(QgsDoubleRange(74.7, 75))

        renderchecker = QgsMultiRenderChecker()
        renderchecker.setMapSettings(mapsettings)
        renderchecker.setControlPathPrefix('pointcloudrenderer')
        renderchecker.setControlName('expected_ramp_zfilter')
        result = renderchecker.runTest('expected_ramp_zfilter')
        TestQgsPointCloudAttributeByRampRenderer.report += renderchecker.report(
        )
        self.assertTrue(result)
Exemplo n.º 3
0
    def testLegend(self):
        renderer = QgsPointCloudAttributeByRampRenderer()
        renderer.setAttribute('Intensity')
        renderer.setMinimum(200)
        renderer.setMaximum(800)
        ramp = QgsStyle.defaultStyle().colorRamp("Viridis")
        shader = QgsColorRampShader(200, 800, ramp.clone())
        shader.setClassificationMode(QgsColorRampShader.EqualInterval)
        shader.classifyColorRamp(classes=4)
        renderer.setColorRampShader(shader)

        layer = QgsPointCloudLayer(
            unitTestDataPath() + '/point_clouds/ept/sunshine-coast/ept.json',
            'test', 'ept')
        layer_tree_layer = QgsLayerTreeLayer(layer)
        nodes = renderer.createLegendNodes(layer_tree_layer)
        self.assertEqual(len(nodes), 4)
        self.assertEqual(nodes[0].data(Qt.DisplayRole), '200')
        self.assertEqual(nodes[1].data(Qt.DisplayRole), '400')
        self.assertEqual(nodes[2].data(Qt.DisplayRole), '600')
        self.assertEqual(nodes[3].data(Qt.DisplayRole), '800')

        shader = QgsColorRampShader(200, 600, ramp.clone())
        shader.setClassificationMode(QgsColorRampShader.EqualInterval)
        shader.classifyColorRamp(classes=2)
        renderer.setColorRampShader(shader)
        nodes = renderer.createLegendNodes(layer_tree_layer)
        self.assertEqual(len(nodes), 2)
        self.assertEqual(nodes[0].data(Qt.DisplayRole), '200')
        self.assertEqual(nodes[1].data(Qt.DisplayRole), '600')
Exemplo n.º 4
0
    def testRenderCrsTransform(self):
        layer = QgsPointCloudLayer(unitTestDataPath() + '/point_clouds/ept/sunshine-coast/ept.json', 'test', 'ept')
        self.assertTrue(layer.isValid())

        renderer = QgsPointCloudAttributeByRampRenderer()
        renderer.setAttribute('Intensity')
        renderer.setMinimum(200)
        renderer.setMaximum(1000)
        ramp = QgsStyle.defaultStyle().colorRamp("Viridis")
        shader = QgsColorRampShader(200, 1000, ramp)
        shader.classifyColorRamp()
        renderer.setColorRampShader(shader)

        layer.setRenderer(renderer)
        layer.renderer().setPointSize(2)
        layer.renderer().setPointSizeUnit(QgsUnitTypes.RenderMillimeters)

        mapsettings = QgsMapSettings()
        mapsettings.setOutputSize(QSize(400, 400))
        mapsettings.setOutputDpi(96)
        mapsettings.setDestinationCrs(QgsCoordinateReferenceSystem('EPSG:4326'))
        mapsettings.setExtent(QgsRectangle(152.980508492, -26.662023491, 152.980586020, -26.662071137))
        mapsettings.setLayers([layer])
        renderchecker = QgsMultiRenderChecker()
        renderchecker.setMapSettings(mapsettings)
        renderchecker.setControlPathPrefix('pointcloudrenderer')
        renderchecker.setControlName('expected_ramp_render_crs_transform')
        result = renderchecker.runTest('expected_ramp_render_crs_transform')
        TestQgsPointCloudAttributeByRampRenderer.report += renderchecker.report()
        self.assertTrue(result)
Exemplo n.º 5
0
    def testBasic(self):
        renderer = QgsPointCloudAttributeByRampRenderer()
        renderer.setAttribute('attr')
        self.assertEqual(renderer.attribute(), 'attr')
        renderer.setMinimum(5)
        self.assertEqual(renderer.minimum(), 5)
        renderer.setMaximum(15)
        self.assertEqual(renderer.maximum(), 15)
        ramp = QgsStyle.defaultStyle().colorRamp("Viridis")
        shader = QgsColorRampShader(20, 30, ramp)
        renderer.setColorRampShader(shader)
        self.assertEqual(renderer.colorRampShader().minimumValue(), 20)
        self.assertEqual(renderer.colorRampShader().maximumValue(), 30)

        renderer.setMaximumScreenError(18)
        renderer.setMaximumScreenErrorUnit(QgsUnitTypes.RenderInches)
        renderer.setPointSize(13)
        renderer.setPointSizeUnit(QgsUnitTypes.RenderPoints)
        renderer.setPointSizeMapUnitScale(QgsMapUnitScale(1000, 2000))

        rr = renderer.clone()
        self.assertEqual(rr.maximumScreenError(), 18)
        self.assertEqual(rr.maximumScreenErrorUnit(),
                         QgsUnitTypes.RenderInches)
        self.assertEqual(rr.pointSize(), 13)
        self.assertEqual(rr.pointSizeUnit(), QgsUnitTypes.RenderPoints)
        self.assertEqual(rr.pointSizeMapUnitScale().minScale, 1000)
        self.assertEqual(rr.pointSizeMapUnitScale().maxScale, 2000)

        self.assertEqual(rr.attribute(), 'attr')
        self.assertEqual(rr.minimum(), 5)
        self.assertEqual(rr.maximum(), 15)
        self.assertEqual(rr.colorRampShader().minimumValue(), 20)
        self.assertEqual(rr.colorRampShader().maximumValue(), 30)
        self.assertEqual(rr.colorRampShader().sourceColorRamp().color1(),
                         renderer.colorRampShader().sourceColorRamp().color1())
        self.assertEqual(rr.colorRampShader().sourceColorRamp().color2(),
                         renderer.colorRampShader().sourceColorRamp().color2())

        doc = QDomDocument("testdoc")
        elem = renderer.save(doc, QgsReadWriteContext())

        r2 = QgsPointCloudAttributeByRampRenderer.create(
            elem, QgsReadWriteContext())
        self.assertEqual(r2.maximumScreenError(), 18)
        self.assertEqual(r2.maximumScreenErrorUnit(),
                         QgsUnitTypes.RenderInches)
        self.assertEqual(r2.pointSize(), 13)
        self.assertEqual(r2.pointSizeUnit(), QgsUnitTypes.RenderPoints)
        self.assertEqual(r2.pointSizeMapUnitScale().minScale, 1000)
        self.assertEqual(r2.pointSizeMapUnitScale().maxScale, 2000)
        self.assertEqual(r2.attribute(), 'attr')
        self.assertEqual(r2.minimum(), 5)
        self.assertEqual(r2.maximum(), 15)
        self.assertEqual(r2.colorRampShader().minimumValue(), 20)
        self.assertEqual(r2.colorRampShader().maximumValue(), 30)
        self.assertEqual(r2.colorRampShader().sourceColorRamp().color1(),
                         renderer.colorRampShader().sourceColorRamp().color1())
        self.assertEqual(r2.colorRampShader().sourceColorRamp().color2(),
                         renderer.colorRampShader().sourceColorRamp().color2())
Exemplo n.º 6
0
    def _import_library_into_qgis(self):
        s = QSettings()
        svg_paths = []
        svg_paths.append(os.path.join(self.library_directory, 'svg/'))
        s.setValue('svg/searchPathsForSVG', svg_paths)

        style = QgsStyle.defaultStyle()
        style.importXml(os.path.join(self.library_directory, 'libreria.xml'))
Exemplo n.º 7
0
    def testDefault(self):
        self.assertEqual(QgsStyle.defaultStyle().defaultPatchAsQPolygonF(QgsSymbol.Hybrid, QSizeF(1, 1)), [])
        self.assertEqual(QgsStyle.defaultStyle().defaultPatchAsQPolygonF(QgsSymbol.Hybrid, QSizeF(10, 10)), [])

        # markers
        self.assertEqual(self.polys_to_list(QgsStyle.defaultStyle().defaultPatchAsQPolygonF(QgsSymbol.Marker, QSizeF(1, 1))), [[[[0.0, 0.0]]]])
        self.assertEqual(self.polys_to_list(QgsStyle.defaultStyle().defaultPatchAsQPolygonF(QgsSymbol.Marker, QSizeF(2, 2))),
                         [[[[1.0, 1.0]]]])
        self.assertEqual(self.polys_to_list(QgsStyle.defaultStyle().defaultPatchAsQPolygonF(QgsSymbol.Marker, QSizeF(10, 2))), [[[[5.0, 1.0]]]])

        # lines
        self.assertEqual(self.polys_to_list(QgsStyle.defaultStyle().defaultPatchAsQPolygonF(QgsSymbol.Line, QSizeF(1, 1))), [[[[0.0, 0.5], [1.0, 0.5]]]])
        self.assertEqual(self.polys_to_list(QgsStyle.defaultStyle().defaultPatchAsQPolygonF(QgsSymbol.Line, QSizeF(10, 2))), [[[[0.0, 1.0], [10.0, 1.0]]]])
        self.assertEqual(self.polys_to_list(QgsStyle.defaultStyle().defaultPatchAsQPolygonF(QgsSymbol.Line, QSizeF(9, 3))), [[[[0.0, 1.5], [9.0, 1.5]]]])

        # fills
        self.assertEqual(self.polys_to_list(QgsStyle.defaultStyle().defaultPatchAsQPolygonF(QgsSymbol.Fill, QSizeF(1, 1))), [[[[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0], [0.0, 0.0]]]])
        self.assertEqual(self.polys_to_list(QgsStyle.defaultStyle().defaultPatchAsQPolygonF(QgsSymbol.Fill, QSizeF(10, 2))), [[[[0.0, 0.0], [10.0, 0.0], [10.0, 2.0], [0.0, 2.0], [0.0, 0.0]]]])
    def layer_properties(self):
        layer = self.view.currentLayer()
        # if it is a vector layer and has a valid geometry
        if layer.type() == 0 and layer.geometryType() not in [3, 4]:
            # wrap style dialog with the buttons ok and cancel so that we can apply changes
            dlg = QDialog()
            dlg.widget = QgsRendererPropertiesDialog(self.view.currentLayer(),
                                                     QgsStyle.defaultStyle(),
                                                     True)
            dlg.layout = QVBoxLayout(dlg)
            dlg.buttons = QDialogButtonBox(dlg)
            dlg.layout.addWidget(dlg.widget)
            dlg.layout.addWidget(dlg.buttons)
            dlg.buttons.setOrientation(Qt.Horizontal)
            dlg.buttons.setStandardButtons(QDialogButtonBox.Cancel
                                           | QDialogButtonBox.Ok)

            # set signals
            def on_style_edit_accept(d):
                # this will update the layer's style
                dlg.widget.onOK()
                dlg.accept()

            dlg.buttons.accepted.connect(lambda d=dlg: on_style_edit_accept(d))
            dlg.buttons.rejected.connect(dlg.reject)
            dlg.exec_()
            self.canvas.refresh()
        elif layer.type() == 1 and layer.rasterType() != 2:
            dlg = QDialog()
            dlg.widget = QgsSingleBandPseudoColorRendererWidget(layer)
            dlg.layout = QVBoxLayout(dlg)
            dlg.buttons = QDialogButtonBox(dlg)
            dlg.layout.addWidget(dlg.widget)
            dlg.layout.addWidget(dlg.buttons)
            dlg.buttons.setOrientation(Qt.Horizontal)
            dlg.buttons.setStandardButtons(QDialogButtonBox.Cancel
                                           | QDialogButtonBox.Ok)

            # set signals
            def on_rasterstyle_edit_accept(d):
                # this will update the layer's style
                renderer = dlg.widget.renderer()
                layer.setRenderer(renderer)
                dlg.accept()

            dlg.buttons.accepted.connect(
                lambda d=dlg: on_rasterstyle_edit_accept(d))
            dlg.buttons.rejected.connect(dlg.reject)
            dlg.exec_()
            self.canvas.refresh()
        elif layer.type() == 1 and layer.rasterType() == 2:
            logger.info("multiband")
Exemplo n.º 9
0
    def importStyle(self):
        styleName = os.path.splitext(os.path.basename(self.dlg.lineEdit.text()))[0]  # name of the style.
        tempStyle = self.tempDir + os.sep + styleName + '.xml'

        try:
            with codecs.open(tempStyle, encoding='utf-8', mode='w') as saveFile:
                saveFile.write(self.styleMaker(self.colorList, styleName))

            styleMan = QgsStyle.defaultStyle()  # QgsStyle style.
            styleMan.importXml(tempStyle)  # Importing the style file. It does not save. So this handled in below line.
            styleMan.saveColorRamp(styleName, styleMan.colorRamp(styleName), 7,
                                   ['SVG2ColoR'])  # Saving the imported style.

            QMessageBox.information(None, "Information", 'The style has been succesfully imported.')

        except Exception as importError:
            QMessageBox.critical(None, "Information", ("An error has occured: " + str(importError)))
Exemplo n.º 10
0
    def _add_features(self, layer_points, layer_lines, layer_polygons):
        start_x = 2710000
        start_y = 1114000
        step_x = 0
        step_y = -20
        style = QgsStyle.defaultStyle()

        with open(self.list_file) as f:
            for i, symbol_name in enumerate(f.readlines()):
                pos_x = start_x + (step_x * i)
                pos_y = start_y + (step_y * i)

                if symbol_name.startswith('P_'):
                    layer = layer_points
                    geometry = QgsGeometry.fromPointXY(QgsPointXY(
                        pos_x, pos_y))
                elif symbol_name.startswith('L_'):
                    layer = layer_lines
                    points = []
                    points.append(QgsPointXY(pos_x, pos_y))
                    points.append(QgsPointXY(pos_x + 200, pos_y))
                    geometry = QgsGeometry.fromPolylineXY(points)
                elif symbol_name.startswith('S_'):
                    layer = layer_polygons
                    points = []
                    points.append(QgsPointXY(pos_x, pos_y))
                    points.append(QgsPointXY(pos_x + 200, pos_y))
                    points.append(QgsPointXY(pos_x + 200, pos_y + 10))
                    points.append(QgsPointXY(pos_x, pos_y + 10))
                    points.append(QgsPointXY(pos_x, pos_y))
                    geometry = QgsGeometry.fromPolygonXY([points])

                data_provider = layer.dataProvider()
                feature = QgsFeature()
                feature.setFields(layer.fields())
                feature.setGeometry(geometry)
                feature['id'] = symbol_name
                data_provider.addFeatures([feature])
                layer.updateExtents()

                category = QgsRendererCategory(
                    symbol_name, style.symbol(symbol_name.strip()),
                    symbol_name)

                layer.renderer().addCategory(category)
Exemplo n.º 11
0
    def testVaryingColorFixedWidth(self):
        """ test that rendering a interpolated line with fixed width and varying color"""

        interpolated_width = QgsInterpolatedLineWidth()
        interpolated_color = QgsInterpolatedLineColor()

        interpolated_width.setIsVariableWidth(False)
        interpolated_width.setFixedStrokeWidth(5)
        color_ramp = QgsColorRampShader(
            0, 7,
            QgsStyle.defaultStyle().colorRamp('Viridis'),
            QgsColorRampShader.Interpolated)
        color_ramp.classifyColorRamp(10)
        interpolated_color.setColor(color_ramp)
        interpolated_color.setColoringMethod(
            QgsInterpolatedLineColor.ColorRamp)

        self.renderImage(interpolated_width, interpolated_color,
                         'interpolatedlinesymbollayer_2')
Exemplo n.º 12
0
    def launch(self):
        log = self.logger.getChild('l')
        pars_dir = self.session.pars_dir
        #=======================================================================
        # filepath
        #=======================================================================

        fp = os.path.join(pars_dir, 'CanFlood.xml')
        assert os.path.exists(
            fp), 'requested xml filepath does not exist: %s' % fp

        #=======================================================================
        # add the sylte
        #=======================================================================
        style = QgsStyle.defaultStyle()  #get the users style database

        if style.importXml(fp):
            log.push('imported styles from %s' % fp)
        else:
            log.error('failed to import styles')
Exemplo n.º 13
0
    def setSelectedLayerStyleWidget(self, layerType, selected, unselected):
        """
        Get selected layer and display the corresponding style widget
        in the right panel
        """
        lt = self.layersTable[layerType]
        table = lt['tableWidget']
        sm = table.selectionModel()
        lines = sm.selectedRows()
        showStyle = True

        # Empty label widget if style must not been displayed
        w = QLabel()
        w.setText('')
        layer = None

        # Refresh Style tab
        if len(lines) != 1:
            showStyle = False

        if showStyle:
            row = lines[0].row()

            # Get layer
            layerId = table.item(row, 0).data(Qt.EditRole)
            lr = QgsProject.instance()
            layer = lr.mapLayer(layerId)
            if not layer:
                showStyle = False
            else:
                self.styleLayer = layer

        if showStyle and layer:
            # Choose widget depending on layer
            if layer.type() == 0 and layer.geometryType() not in [3, 4]:
                w = QgsRendererPropertiesDialog(layer, QgsStyle.defaultStyle(), True)

        # Make the widget visible
        self.styleWidget = w
        self.styleLayer = layer
        self.dlg.styleScrollArea.setWidget(w)
Exemplo n.º 14
0
    def testVaryingColorVaryingWidthDiscrete(self):
        """ test that rendering a interpolated line with varying width and varying color with discrete color ramp """

        interpolated_width = QgsInterpolatedLineWidth()
        interpolated_color = QgsInterpolatedLineColor()

        interpolated_width.setIsVariableWidth(True)
        interpolated_width.setMinimumValue(1)
        interpolated_width.setMaximumValue(8)
        interpolated_width.setMinimumWidth(1)
        interpolated_width.setMaximumWidth(10)
        color_ramp = QgsColorRampShader(
            2, 7,
            QgsStyle.defaultStyle().colorRamp('RdGy'),
            QgsColorRampShader.Discrete)
        color_ramp.classifyColorRamp(5)
        interpolated_color.setColor(color_ramp)
        interpolated_color.setColoringMethod(
            QgsInterpolatedLineColor.ColorRamp)

        self.renderImage(interpolated_width, interpolated_color,
                         'interpolatedlinesymbollayer_5')
Exemplo n.º 15
0
    def testVaryingColorVaryingWidthExact(self):
        """ test that rendering a interpolated line with varying width and varying color with exact color ramp """

        interpolated_width = QgsInterpolatedLineWidth()
        interpolated_color = QgsInterpolatedLineColor()

        interpolated_width.setIsVariableWidth(True)
        interpolated_width.setMinimumValue(1)
        interpolated_width.setMaximumValue(8)
        interpolated_width.setMinimumWidth(1)
        interpolated_width.setMaximumWidth(10)
        color_ramp = QgsColorRampShader(
            0, 10,
            QgsStyle.defaultStyle().colorRamp('Viridis'),
            QgsColorRampShader.Exact)
        color_ramp.classifyColorRamp(10)
        interpolated_color.setColor(color_ramp)
        interpolated_color.setColoringMethod(
            QgsInterpolatedLineColor.ColorRamp)

        self.renderImage(interpolated_width, interpolated_color,
                         'interpolatedlinesymbollayer_6')
Exemplo n.º 16
0
    def load_style_xml(self): #load the xml style file
        #=======================================================================
        #setup the logger
        #=======================================================================
        from hlpr.plug import logger
        log = logger(self)
        
        #=======================================================================
        # filepath
        #=======================================================================
        
        fp = os.path.join(self.pars_dir, 'CanFlood.xml')
        assert os.path.exists(fp), 'requested xml filepath does not exist: %s'%fp
        
        #=======================================================================
        # add the sylte
        #=======================================================================
        style = QgsStyle.defaultStyle() #get the users style database

        if style.importXml(fp):
            log.push('imported styles from %s'%fp)
        else:
            log.error('failed to import styles')
Exemplo n.º 17
0
    def importStyle(self):
        styleName = os.path.splitext(os.path.basename(
            self.dlg.lineEdit.text()))[0]  # name of the style.
        tempStyle = self.tempDir + os.sep + styleName + '.xml'

        try:
            with codecs.open(tempStyle, encoding='utf-8',
                             mode='w') as saveFile:
                saveFile.write(self.styleMaker(self.colorList, styleName))

            styleMan = QgsStyle.defaultStyle()  # QgsStyle style.
            styleMan.importXml(
                tempStyle
            )  # Importing the style file. It does not save. So this handled in below line.
            styleMan.saveColorRamp(styleName, styleMan.colorRamp(styleName), 7,
                                   ['SVG2ColoR'])  # Saving the imported style.

            QMessageBox.information(
                None, "Information",
                'The style has been succesfully imported.')

        except Exception as importError:
            QMessageBox.critical(None, "Information",
                                 ("An error has occured: " + str(importError)))
Exemplo n.º 18
0
    def testStylePaths(self):
        p = QgsProjectStyleSettings()
        spy = QSignalSpy(p.styleDatabasesChanged)

        model = QgsProjectStyleDatabaseModel(p)
        model_with_default = QgsProjectStyleDatabaseModel(p)
        model_with_default.setShowDefaultStyle(True)
        proxy_model = QgsProjectStyleDatabaseProxyModel(model_with_default)
        proxy_model.setFilters(
            QgsProjectStyleDatabaseProxyModel.Filter.FilterHideReadOnly)

        project_style = QgsStyle()
        project_style.setName('project')
        model_with_project_style = QgsProjectStyleDatabaseModel(p)
        model_with_project_style.setShowDefaultStyle(True)
        model_with_project_style.setProjectStyle(project_style)

        self.assertFalse(p.styleDatabasePaths())
        self.assertFalse(p.styles())
        self.assertEqual(p.combinedStyleModel().rowCount(), 0)
        self.assertEqual(model.rowCount(QModelIndex()), 0)
        self.assertFalse(
            model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole))
        self.assertEqual(model_with_default.rowCount(QModelIndex()), 1)
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'Default')
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(0, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            QgsStyle.defaultStyle())

        self.assertEqual(model_with_project_style.rowCount(QModelIndex()), 2)
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(0, 0, QModelIndex()),
                Qt.DisplayRole), 'project')
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(0, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole), project_style)
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(1, 0, QModelIndex()),
                Qt.DisplayRole), 'Default')
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(1, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            QgsStyle.defaultStyle())

        self.assertEqual(proxy_model.rowCount(QModelIndex()), 1)
        self.assertEqual(
            proxy_model.data(proxy_model.index(0, 0, QModelIndex()),
                             Qt.DisplayRole), 'Default')
        self.assertEqual(
            proxy_model.data(proxy_model.index(0, 0, QModelIndex()),
                             QgsProjectStyleDatabaseModel.StyleRole),
            QgsStyle.defaultStyle())

        p.addStyleDatabasePath(unitTestDataPath() + '/style1.db')
        self.assertEqual(len(spy), 1)
        self.assertEqual(p.styleDatabasePaths(),
                         [unitTestDataPath() + '/style1.db'])
        self.assertEqual(p.combinedStyleModel().rowCount(), 1)
        self.assertEqual(
            p.combinedStyleModel().data(p.combinedStyleModel().index(0, 0)),
            'style1')
        self.assertEqual(len(p.styles()), 1)
        self.assertEqual(p.styles()[0].fileName(),
                         unitTestDataPath() + '/style1.db')
        self.assertEqual(p.styles()[0].name(), 'style1')
        self.assertEqual(model.rowCount(QModelIndex()), 1)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'style1')
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()),
                       QgsProjectStyleDatabaseModel.StyleRole),
            p.styles()[0])
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()),
                       QgsProjectStyleDatabaseModel.PathRole),
            unitTestDataPath() + '/style1.db')

        self.assertEqual(model_with_default.rowCount(QModelIndex()), 2)
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'Default')
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(0, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            QgsStyle.defaultStyle())
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(1, 0, QModelIndex()), Qt.DisplayRole),
            'style1')
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(1, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            p.styles()[0])
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(1, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.PathRole),
            unitTestDataPath() + '/style1.db')

        self.assertEqual(model_with_project_style.rowCount(QModelIndex()), 3)
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(0, 0, QModelIndex()),
                Qt.DisplayRole), 'project')
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(0, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole), project_style)
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(1, 0, QModelIndex()),
                Qt.DisplayRole), 'Default')
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(1, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            QgsStyle.defaultStyle())
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(2, 0, QModelIndex()),
                Qt.DisplayRole), 'style1')
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(2, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            p.styles()[0])
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(2, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.PathRole),
            unitTestDataPath() + '/style1.db')

        self.assertEqual(proxy_model.rowCount(QModelIndex()), 2)
        self.assertEqual(
            proxy_model.data(proxy_model.index(0, 0, QModelIndex()),
                             Qt.DisplayRole), 'Default')
        self.assertEqual(
            proxy_model.data(proxy_model.index(0, 0, QModelIndex()),
                             QgsProjectStyleDatabaseModel.StyleRole),
            QgsStyle.defaultStyle())
        self.assertEqual(
            proxy_model.data(proxy_model.index(1, 0, QModelIndex()),
                             Qt.DisplayRole), 'style1')
        self.assertEqual(
            proxy_model.data(proxy_model.index(1, 0, QModelIndex()),
                             QgsProjectStyleDatabaseModel.StyleRole),
            p.styles()[0])
        self.assertEqual(
            proxy_model.data(proxy_model.index(1, 0, QModelIndex()),
                             QgsProjectStyleDatabaseModel.PathRole),
            unitTestDataPath() + '/style1.db')

        # try re-adding path which is already present
        p.addStyleDatabasePath(unitTestDataPath() + '/style1.db')
        self.assertEqual(len(spy), 1)
        self.assertEqual(p.styleDatabasePaths(),
                         [unitTestDataPath() + '/style1.db'])
        self.assertEqual(p.combinedStyleModel().rowCount(), 1)
        self.assertEqual(
            p.combinedStyleModel().data(p.combinedStyleModel().index(0, 0)),
            'style1')
        self.assertEqual(model.rowCount(QModelIndex()), 1)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'style1')
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()),
                       QgsProjectStyleDatabaseModel.StyleRole),
            p.styles()[0])
        self.assertEqual(model_with_default.rowCount(QModelIndex()), 2)
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'Default')
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(0, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            QgsStyle.defaultStyle())
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(1, 0, QModelIndex()), Qt.DisplayRole),
            'style1')
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(1, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            p.styles()[0])

        p.addStyleDatabasePath(unitTestDataPath() + '/style2.db')
        self.assertEqual(len(spy), 2)
        self.assertEqual(p.styleDatabasePaths(), [
            unitTestDataPath() + '/style1.db',
            unitTestDataPath() + '/style2.db'
        ])
        self.assertEqual(p.styles()[0].fileName(),
                         unitTestDataPath() + '/style1.db')
        self.assertEqual(p.styles()[0].name(), 'style1')
        self.assertEqual(p.styles()[1].fileName(),
                         unitTestDataPath() + '/style2.db')
        self.assertEqual(p.styles()[1].name(), 'style2')
        self.assertEqual(p.combinedStyleModel().rowCount(), 2)
        self.assertEqual(
            p.combinedStyleModel().data(p.combinedStyleModel().index(0, 0)),
            'style1')
        self.assertEqual(
            p.combinedStyleModel().data(p.combinedStyleModel().index(1, 0)),
            'style2')
        self.assertEqual(model.rowCount(QModelIndex()), 2)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'style1')
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()),
                       QgsProjectStyleDatabaseModel.StyleRole),
            p.styles()[0])
        self.assertEqual(
            model.data(model.index(1, 0, QModelIndex()), Qt.DisplayRole),
            'style2')
        self.assertEqual(
            model.data(model.index(1, 0, QModelIndex()),
                       QgsProjectStyleDatabaseModel.StyleRole),
            p.styles()[1])
        self.assertEqual(model_with_default.rowCount(QModelIndex()), 3)
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'Default')
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(0, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            QgsStyle.defaultStyle())
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(1, 0, QModelIndex()), Qt.DisplayRole),
            'style1')
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(1, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            p.styles()[0])
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(2, 0, QModelIndex()), Qt.DisplayRole),
            'style2')
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(2, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            p.styles()[1])

        self.assertEqual(model_with_project_style.rowCount(QModelIndex()), 4)
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(0, 0, QModelIndex()),
                Qt.DisplayRole), 'project')
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(0, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole), project_style)
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(1, 0, QModelIndex()),
                Qt.DisplayRole), 'Default')
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(1, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            QgsStyle.defaultStyle())
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(2, 0, QModelIndex()),
                Qt.DisplayRole), 'style1')
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(2, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            p.styles()[0])
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(3, 0, QModelIndex()),
                Qt.DisplayRole), 'style2')
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(3, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            p.styles()[1])

        self.assertEqual(p.styleAtPath(unitTestDataPath() + '/style1.db'),
                         p.styles()[0])
        self.assertEqual(p.styleAtPath(unitTestDataPath() + '/style2.db'),
                         p.styles()[1])
        self.assertFalse(p.styleAtPath('.xxx'))

        p.setStyleDatabasePaths([unitTestDataPath() + '/style3.db'])
        self.assertEqual(len(spy), 3)
        self.assertEqual(p.styleDatabasePaths(),
                         [unitTestDataPath() + '/style3.db'])

        self.assertEqual(p.combinedStyleModel().rowCount(), 1)
        self.assertEqual(
            p.combinedStyleModel().data(p.combinedStyleModel().index(0, 0)),
            'style3')

        self.assertEqual(model.rowCount(QModelIndex()), 1)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'style3')
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()),
                       QgsProjectStyleDatabaseModel.StyleRole),
            p.styles()[0])
        self.assertEqual(model_with_default.rowCount(QModelIndex()), 2)
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'Default')
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(0, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            QgsStyle.defaultStyle())
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(1, 0, QModelIndex()), Qt.DisplayRole),
            'style3')
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(1, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            p.styles()[0])

        self.assertEqual(model_with_project_style.rowCount(QModelIndex()), 3)
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(0, 0, QModelIndex()),
                Qt.DisplayRole), 'project')
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(0, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole), project_style)
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(1, 0, QModelIndex()),
                Qt.DisplayRole), 'Default')
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(1, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            QgsStyle.defaultStyle())
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(2, 0, QModelIndex()),
                Qt.DisplayRole), 'style3')
        self.assertEqual(
            model_with_project_style.data(
                model_with_project_style.index(2, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            p.styles()[0])

        self.assertEqual(p.styles()[0].fileName(),
                         unitTestDataPath() + '/style3.db')
        self.assertEqual(p.styles()[0].name(), 'style3')

        p.setStyleDatabasePaths([unitTestDataPath() + '/style3.db'])
        self.assertEqual(len(spy), 3)
        self.assertEqual(p.combinedStyleModel().rowCount(), 1)
        self.assertEqual(
            p.combinedStyleModel().data(p.combinedStyleModel().index(0, 0)),
            'style3')

        self.assertEqual(model.rowCount(QModelIndex()), 1)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'style3')
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()),
                       QgsProjectStyleDatabaseModel.StyleRole),
            p.styles()[0])
        self.assertEqual(model_with_default.rowCount(QModelIndex()), 2)
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'Default')
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(0, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            QgsStyle.defaultStyle())
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(1, 0, QModelIndex()), Qt.DisplayRole),
            'style3')
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(1, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            p.styles()[0])

        p.setStyleDatabasePaths([])
        self.assertEqual(len(spy), 4)
        self.assertFalse(p.styleDatabasePaths())
        self.assertFalse(p.styles())
        self.assertEqual(p.combinedStyleModel().rowCount(), 0)

        self.assertEqual(model.rowCount(QModelIndex()), 0)
        self.assertEqual(model_with_default.rowCount(QModelIndex()), 1)
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'Default')
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(0, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            QgsStyle.defaultStyle())

        # test using a .xml path
        p.addStyleDatabasePath(unitTestDataPath() + '/categorized.xml')
        self.assertEqual(p.styles()[0].fileName(),
                         unitTestDataPath() + '/categorized.xml')
        self.assertEqual(p.combinedStyleModel().rowCount(), 4)
        self.assertEqual(
            p.combinedStyleModel().data(p.combinedStyleModel().index(0, 0)),
            'categorized')
        self.assertEqual(
            p.combinedStyleModel().data(p.combinedStyleModel().index(1, 0)),
            ' ----c/- ')
        self.assertEqual(
            p.combinedStyleModel().data(p.combinedStyleModel().index(2, 0)),
            'B ')
        self.assertEqual(
            p.combinedStyleModel().data(p.combinedStyleModel().index(3, 0)),
            'a')

        self.assertEqual(model.rowCount(QModelIndex()), 1)
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'categorized')
        self.assertEqual(
            model.data(model.index(0, 0, QModelIndex()),
                       QgsProjectStyleDatabaseModel.StyleRole),
            p.styles()[0])
        self.assertEqual(model_with_default.rowCount(QModelIndex()), 2)
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(0, 0, QModelIndex()), Qt.DisplayRole),
            'Default')
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(0, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            QgsStyle.defaultStyle())
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(1, 0, QModelIndex()), Qt.DisplayRole),
            'categorized')
        self.assertEqual(
            model_with_default.data(
                model_with_default.index(1, 0, QModelIndex()),
                QgsProjectStyleDatabaseModel.StyleRole),
            p.styles()[0])
        # read only style should not be included
        self.assertEqual(proxy_model.rowCount(QModelIndex()), 1)
        self.assertEqual(
            proxy_model.data(proxy_model.index(0, 0, QModelIndex()),
                             Qt.DisplayRole), 'Default')
        self.assertEqual(
            proxy_model.data(proxy_model.index(0, 0, QModelIndex()),
                             QgsProjectStyleDatabaseModel.StyleRole),
            QgsStyle.defaultStyle())
Exemplo n.º 19
0
def getDefaultStyle():
    return QgsStyle.defaultStyle()
def sigmena():
    #lo que pongamos aqui se va a reproducir cada vez que se abra un qgis en forma de ventana a la que hay que dar a aceptar, vale para informacion muy importante pero es un toston
    #QMessageBox.information(None, "SIGMENA", "Abres un QGIS configurado por SIGMENA") 
    iface.messageBar().pushMessage("SIGMENA", "Acabas de abrir una instancia de QGIS configurada por SIGMENA", duration=15)
    
#respecto a los sistemas de referencia con ello lo definimos por defecto a nivel usuario.
    crs = 'EPSG:25830'
    
    QSettings().setValue('/Projections/layerDefaultCrs', crs)
    QSettings().setValue("/app/projections/defaultProjectCrs", crs )
    QSettings().setValue("/app/projections/unknownCrsBehavior","UseProjectCrs")
    QSettings().setValue("/app/projections/newProjectCrsBehavior","UsePresetCrs")
    QSettings().setValue("/Projections/EPSG:23030//EPSG:25830_coordinateOp","+proj=pipeline +step +inv +proj=utm +zone=30 +ellps=intl +step +proj=hgridshift +grids=SPED2ETV2.gsb +step +proj=utm +zone=30 +ellps=GRS80")
    #Projections/showDatumTransformDialog
    
#informacion nueva en sigmena
    QSettings().setValue('/core/NewsFeed\httpsfeedqgisorg\disabled','false')

    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210324/title',"Complemento calcula hectareas mientras editas")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210324/content',"<p style=color:green;>Este complemento os ayudará a cuadrar las superficies en las propuestas</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20191201/image',"O:/sigmena/logos/LogoSIGMENA.jpg")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210324/link',"O:/sigmena/notas/blog_sigmena/EDICION.html")



    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210225/title',"Ortofotos 2020")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210225/content',"<p>Empiezan a estar disponibles las ortofotos de PNOA 2020. En teoría tendremos disponible toda la provincia pero han empezado a liberar la zona oeste y norte. Pincha en este texto para ampliar</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20191201/image',"O:/sigmena/logos/LogoSIGMENA.jpg")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210225/link',"O:/sigmena/notas/blog_sigmena/ORTOFOTOS.html")

    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210414/title',"Fotovoltaicos y Eolicos")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210414/content',"<p>Desde QGIS puedes visualizar la cartografia del MITECO de sensibilidad ambiental a estos parques. Pincha en este texto para ampliar</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20191201/image',"O:/sigmena/logos/LogoSIGMENA.jpg")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210414/link',"O:/sigmena/notas/blog_sigmena/RENOVABLES.html")

    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210224/title',"Actualización a SIGPAC 2021")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210224/content',"<p> Nos han pasado desde Agricultura la cartografía del <b>Sigpac actualizada a 2021</b>. Si utilizais el complemento ya os carga la cartografía nueva. He aprovechado para actualizar el botón. Pincha en este texto para ampliar</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20191201/image',"O:/sigmena/logos/LogoSIGMENA.jpg")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210224/link',"O:/sigmena/notas/blog_sigmena/SIGPAC.html")


    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210220/title',"Plan de Monitorización de Fauna")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210220/content',"<p style=color:red;> Tenemos nueva cartografía del <b>Plan de Monitorización de Fauna</b>. Pincha en este texto para ampliar</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20191201/image',"O:/sigmena/logos/LogoSIGMENA.jpg")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210220/link',"O:/sigmena/notas/blog_sigmena/ESPECIES.html")

    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210219/title',"Visor MACOTE")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210219/content',"<p> Tragsa ha generado un visor para tratar de estimar las zonas con en las que es posible la <b>extración de madera con Teleferico</b>. Pincha en este texto para ampliar</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20191201/image',"O:/sigmena/logos/LogoSIGMENA.jpg")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210219/link',"O:/sigmena/notas/blog_sigmena/TODOS_LOS_ARTICULOS.html")

    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210212/title',"Estado vuelos LiDAR - PNOA")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210212/content',"<p> Hay en el Blog información nueva respecto al estado del vuelo <b>LiDAR</b>. Pincha en este texto para ampliar</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20191201/image',"O:/sigmena/logos/LogoSIGMENA.jpg")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210212/link',"O:/sigmena/notas/blog_sigmena/LIDAR.html")

    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210209/title',"CARTOGRAFÍA FORESTACIÓN DE TIERRAS AGRÁRIAS")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210209/content',"<p> En el Blog he añadido una entrada referente a la cartografía que han recopilado desde Tragsa del programa de <b>forestación</b> de tierras agrárias. Pincha en este texto para ampliar</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20191201/image',"O:/sigmena/logos/LogoSIGMENA.jpg")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210209/link',"O:/sigmena/notas/blog_sigmena/FORESTACION.html")

    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210211/title',"PERÍMETRO INCENDIOS 2020")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210211/content',"<p> En el Blog he añadido una entrada para que sepais que ya está la capa de perímetros de incendios 2020. Pincha en este texto para ampliar</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20191201/image',"O:/sigmena/logos/LogoSIGMENA.jpg")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210211/link',"O:/sigmena/notas/Blog_Sigmena/INCENDIOS.html")
    
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210202/title',"IMAGENES DE SENTINEL")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210202/content',"<p> En el Blog he añadido una entrada referente a como cargar imagenes de Sentinel que he descargado del 2020. Pincha en este texto para ampliar</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20191201/image',"O:/sigmena/logos/LogoSIGMENA.jpg")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210202/link',"O:/sigmena/notas/Blog_Sigmena/SENTINEL.html")
    
    

    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210124/title',"Blog SIGMENA")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210124/content',"<p>He creado un blog para teneros informados de las novedades que vayamos teniendo en SIGMENA. Haz click aquí para acceder.</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20200124/image',"file:///o:/sigmena/logos/LogoSIGMENA.jpg")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210124/link',"O:/sigmena/notas/Blog_Sigmena/TODOS_LOS_ARTICULOS.html")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20210124/sticky','true')


    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20200124/title',"MANUAL COMPLEMENTOS SIGMENA")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20200124/content',"<p>Animacion para ver como funcionan los complementos SIGMENA. Pincha en este texto para saber mas</p>")
    #QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20200124/image',"file:///o:/sigmena/logos/LogoSIGMENA.jpg")
    QSettings().setValue('/core/NewsFeed/httpsfeedqgisorg/20200124/link',r"O:/sigmena/utilidad/PROGRAMA/QGIS/Complementos/Manual/Manual_complementos_SIGMENA.htm")
    
#repositorio de complementos sigmena  
    QSettings().setValue('/app/plugin_installer/checkOnStart','false')
    QSettings().setValue('/app/plugin_repositories/SIGMENA/url','https://raw.githubusercontent.com/diezrabanos/qgis_plugins/master/servidor_descargas_sigmena.xml')
    QSettings().setValue('/app/plugin_repositories/SIGMENA/authcfg','')
    QSettings().setValue('/app/plugin_repositories/Repositorio%20oficial%20de%20complementos%20de%20QGIS\enabled','false')
    QSettings().setValue('/app/plugin_repositories/SIGMENA/enabled','true')

#compruebo que existe la carpeta con los complementos
    directorio = home_plugin_path
    #try:
    #print("empiezo",file=debug)
    if os.path.isdir(directorio):
        os.stat(directorio)
        #print(len(complementos_con_version),file=debug)
        #if len(complementos_con_version)==0:
        versioninstalada="0.0.0"
        #para desinstalar si no la version correcta de un complemento
        for i in range(0,len(complementos_con_version)):
                #print("todos los complementos de la lista", file=debug)
                #print(complementos_con_version[i][0], file=debug)
                
                for x in findPlugins(home_plugin_path):
                    #print("todos los complementos que encuentra", file=debug)
                    #print(x[0], file=debug)
                    #print(x[0], file=debug)       
                    if x[0]==complementos_con_version[i][0]:
                         
                        
                        versioninstalada=str(x[1].get('general',"version"))
                        #print(versioninstalada, file=debug)
                        
                    #else:
                        #versioninstalada="0.0.0"
                        #print("pongo version 0.0.0", file=debug)
                        

                if versioninstalada==complementos_con_version[i][1]:
                    #print("no deberia hacer nada porque no hay ninguna actualziacion", file=debug)
                    
                
                    continue
                else:
                    #print ("se supone que desinstalo",complementos_con_version[i][0], file = debug)
                    #print(versioninstalada,complementos_con_version[i][1], file = debug)
                    unloadPlugin(complementos_con_version[i][0])#desinstala si version antigua de un complemento instalado
                    #print("plugins a instalar ",complementos_con_version[i][0], file = debug)
                    #para instalar un complemento                
                    # Installing
                    zip_ref = zipfile.ZipFile('O:/sigmena/utilidad/PROGRAMA/QGIS/Complementos/'+complementos_con_version[i][0]+'.zip', 'r')
                    zip_ref.extractall(home_plugin_path)
                    zip_ref.close()
                    loadPlugin(complementos_con_version[i][0])
                    startPlugin(complementos_con_version[i][0])
                    #print("desinstalo e instalo",file=debug)
     

    else:
        os.mkdir(directorio)
        for i in range(0,len(complementos_con_version)):
        #para instalar un complemento                
                        # Installing
                        zip_ref = zipfile.ZipFile('O:/sigmena/utilidad/PROGRAMA/QGIS/Complementos/'+complementos_con_version[i][0]+'.zip', 'r')
                        zip_ref.extractall(home_plugin_path)
                        zip_ref.close()
                        loadPlugin(complementos_con_version[i][0])
                        startPlugin(complementos_con_version[i][0])

     

  
    
    #esto es para que si estan instalados los active    
    try:  
        QSettings().setValue('/PythonPlugins/zoomSigmena','true')
        QSettings().setValue('/PythonPlugins/alidadas','true')
        QSettings().setValue('/PythonPlugins/gpsDescargaCarga','true')
        QSettings().setValue('/PythonPlugins/hectareas','true')
        QSettings().setValue('/PythonPlugins/sigpac','true')
        QSettings().setValue('/PythonPlugins/silvilidar','true')
        QSettings().setValue('/PythonPlugins/puntossigmena','true')
        QSettings().setValue('/PythonPlugins/ptos2pol','true')
        QSettings().setValue('/PythonPlugins/censosPuntos','true')
        QSettings().setValue('/PythonPlugins/HectareasEdicion','true')
        
    except:
        pow
#para que no pierda tiempo buscando si hay actualizaciones de los complementos instalados
    QSettings().setValue("/app/plugin_installer/checkOnStart","false")

#para anadir los wms que sean interesantes, TIRA DE LAS DOS LISTAS DE ARRIBA

    for WMS_URL, WMS_NAME in zip(lista_WMS_URL,lista_WMS_NAME):
        if "Qgis/WMS/%s/authcfg" % WMS_NAME not in QSettings().allKeys():
            QSettings().setValue("/qgis/WMS/%s/authcfg" % WMS_NAME, "")
            QSettings().setValue("/qgis/WMS/%s/username" % WMS_NAME, "")
            QSettings().setValue("/qgis/WMS/%s/password" % WMS_NAME, "")
            QSettings().setValue("/qgis/connections-wms/%s/dpiMode" % WMS_NAME, 7)
            QSettings().setValue("/qgis/connections-wms/%s/ignoreAxisOrientation" % WMS_NAME, False)
            QSettings().setValue("/qgis/connections-wms/%s/ignoreGetFeatureInfoURI" % WMS_NAME, False)
            QSettings().setValue("/qgis/connections-wms/%s/ignoreGetMapURI" % WMS_NAME, False)
            QSettings().setValue("/qgis/connections-wms/%s/invertAxisOrientation" % WMS_NAME, False)
            QSettings().setValue("/qgis/connections-wms/%s/referer" % WMS_NAME, "")
            QSettings().setValue("/qgis/connections-wms/%s/smoothPixmapTransform" % WMS_NAME, "")
            QSettings().setValue("/qgis/connections-wms/%s/url" % WMS_NAME, WMS_URL)

#para anadir las imagenes de teselas

    for xyz_name, xyz_url in zip(lista_xyz_name,lista_xyz_url):
        if "qgis/connections-xyz/%s/url" % xyz_name not in QSettings().allKeys():
            #QSettings().setValue("/qgis/connections-xyz/Bing%20Sat%E9lite/url","http://ecn.t3.tiles.virtualearth.net/tiles/a{q}.jpeg?g=0&dir=dir_n\x2019")
            #QSettings().setValue("/qgis/connections-xyz/relieve/url","https://mt1.google.com/vt/lyrs=t&x={x}&y={y}&z={z}")
            QSettings().setValue("/qgis/connections-xyz/%s/url" % xyz_name, "%s" % xyz_url)
# Remove a QGIS toolbar (e.g., the File toolbar)
    #fileToolBar = self.iface.fileToolBar()
    #self.iface.mainWindow().removeToolBar( fileToolBar )
            
#para importar estilos de un archivo xml

    style=QgsStyle.defaultStyle()
    style.importXml(archivosestilos)
    for estilo in estilosfavoritos:
        print (estilo)
        style.addFavorite(QgsStyle.SymbolEntity, estilo)
#style.addFavorite(QgsStyle.SymbolEntity, 'vvpp')

#para que muestre el wms de sentibilidad ambiental
    QSettings().setValue("/qgis/connections-wms/Sensibilidad_ambiental_eolicos/ignoreGetMapURI","true")
    QSettings().setValue("/qgis/connections-wms/Sensibilidad_ambiental_fotovoltaicos/ignoreGetMapURI","true")

#para que por defecto coja la ruta donde estan las plantillas de mapas, composiciones de mapas en formato qpt
    QSettings().setValue("/app/LastComposerTemplateDir","O:/sigmena/leyendas")

#para evitar problemas con la codificacion de las capas, caracteres extranos
    QSettings().setValue("/UI/encoding","UTF-8")
    QSettings().setValue("/qgis/ignoreShapeEncoding","false")

#para establecer colores por defecto, la seleccion si no dice otra cosa el proyecto se hace en amarillo y semitransparente.
    QSettings().setValue("/qgis/default_selection_color_red","255")
    QSettings().setValue("/qgis/default_selection_color_green","255")
    QSettings().setValue("/qgis/default_selection_color_blue","0")
    QSettings().setValue("/qgis/default_selection_color_alpha","120")

#para hacer que las mediciones sean planimetricas, evitando el error por medir sobre el elipsoide
    #QSettings().setValue("/qgis/measure/planimetric","true")
    QSettings().setValue("/core/measure/planimetric","true")

#para que no compruebe si hay nuevas versiones
    QSettings().setValue("/qgis/checkVersion","false")

#para que el snapping este desactivado por defecto porque ralentiza mucho la edicion
    QSettings().setValue("/qgis/digitizing/default_snap_enabled","false")


#copiar el archivo de rejilla necesario, no me deja por los permisos de usuario lo hago con un bat
    
    #shutil.copy('O:/sigmena/utilidad/PROGRAMA/QGIS/SPED2ETV2.gsb', 'C:/Program Files/QGIS 3.10/share/proj/SPED2ETV2.gsb')


#activo la personalizacion de la visualizacion
    QSettings().setValue("/UI/Customization/enabled","true")
#copiar el archivo de configuracion visual de qgis
    usuario= QgsApplication.qgisSettingsDirPath()
    shutil.copy('O:/sigmena/utilidad/PROGRAMA/QGIS/QGISCUSTOMIZATION3.ini', os.path.join(usuario,'QGIS/QGISCUSTOMIZATION3.ini'))



#para copiar la funcion al usuario si no la tiene
    rutaexpresiones = home_plugin_path[:-7]+'expressions'
    if rutaexpresiones not in sys.path:
        sys.path.append(rutaexpresiones) 

    if os.path.isdir(rutaexpresiones):
        os.stat(rutaexpresiones)
        for elem in funciones:
            miruta=rutaexpresiones+'/'+elem+'.py'
            origen="O:/sigmena/utilidad/PROGRAMA/QGIS/Funciones/"+elem+'.py'
            if os.path.isfile(miruta):
                pass
            else: 
                copyfile(origen, miruta)
                #from intersecciona import intersecciona
                #QgsExpression.registerFunction(intersecciona)
                module = __import__(elem)
                func = getattr(module, elem)
                QgsExpression.registerFunction(func)
                
    else:
        os.mkdir(rutaexpresiones)
        for elem in funciones:
            miruta=rutaexpresiones+'/'+elem+'.py'
            origen="O:/sigmena/utilidad/PROGRAMA/QGIS/Funciones/"+elem+'.py'
            copyfile(origen, miruta)
            #from intersecciona import intersecciona
            #QgsExpression.registerFunction(intersecciona)
            module = __import__(elem)
            func = getattr(module, elem)
            QgsExpression.registerFunction(func)

    
    


#desabilito el snapping
    #iface.mainWindow().findChild(QDockWidget, 'Snapping and Digitizing Options').findChild(QDialog).findChild(QComboBox,'mSnapModeComboBox').setCurrentIndex(0) #0 = current layer 1 = all layers 2 = advanced
    #for item in QgsMapLayerRegistry.instance().mapLayers().values():
        #QgsProject.instance().setSnapSettingsForLayer(item.id(), False, 2, 0, 2, True)
    
    #iface.mapCanvas().snappingUtils().toggleEnabled()

#para incluir un decorador 
    from qgis.PyQt.Qt import QTextDocument
    from qgis.PyQt.QtGui import QFont
    mQFont = "Sans Serif"

    mQFontsize = 10
    mLabelQString = "SIGMENA"
    mMarginHorizontal = 0
    mMarginVertical = 0
    mLabelQColor = "#006600"
    mLabelQColor2 = "#FFFFFF"
    INCHES_TO_MM = 0.0393700787402 # 1 millimeter = 0.0393700787402 inches
    case = 3
    def add_copyright(p, text, xOffset, yOffset):
        p.translate( xOffset , yOffset )
        text.drawContents(p)
        p.setWorldTransform( p.worldTransform() )
    def _on_render_complete(p):
        deviceHeight = p.device().height() # Get paint device height on which this painter is currently painting
        deviceWidth = p.device().width() # Get paint device width on which this painter is currently painting
        # Create new container for structured rich text
        text = QTextDocument()
        font = QFont()
        font.setFamily(mQFont)
        font.setPointSize(int(mQFontsize))
        text.setDefaultFont(font)
        style = "<style type=\"text/css\"> p { color: " + mLabelQColor + " ; background: " + mLabelQColor2 + " }</style>" 
        text.setHtml( style + "<p>" + mLabelQString + "</p>" )
        # Text Size
        size = text.size()
        # RenderMillimeters
        pixelsInchX = p.device().logicalDpiX()
        pixelsInchY = p.device().logicalDpiY()
        xOffset = pixelsInchX * INCHES_TO_MM * int(mMarginHorizontal)
        yOffset = pixelsInchY * INCHES_TO_MM * int(mMarginVertical)
        # Calculate positions
        if case == 0:
            # Top Left
            add_copyright(p, text, xOffset, yOffset)
        elif case == 1:
            # Bottom Left
            yOffset = deviceHeight - yOffset - size.height()
            add_copyright(p, text, xOffset, yOffset)
        elif case == 2:
            # Top Right
            xOffset = deviceWidth - xOffset - size.width()
            add_copyright(p, text, xOffset, yOffset)
        elif case == 3:
            # Bottom Right
            yOffset = deviceHeight - yOffset - size.height()
            xOffset = deviceWidth - xOffset - size.width()
            add_copyright(p, text, xOffset, yOffset)
        elif case == 4:
            # Top Center
            xOffset = deviceWidth / 2
            add_copyright(p, text, xOffset, yOffset)
        else:
            # Bottom Center
            yOffset = deviceHeight - yOffset - size.height()
            xOffset = deviceWidth / 2
            add_copyright(p, text, xOffset, yOffset)
    # Emitted when the canvas has rendered
    iface.mapCanvas().renderComplete.connect(_on_render_complete)
    # Repaint the canvas map
    iface.mapCanvas().refresh()
Exemplo n.º 21
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()