コード例 #1
0
    def createDefinedProperties(self):
        props = (('"auxiliary_storage_labeling_positionx"', QgsPalLayerSettings.PositionX),
                 ('"auxiliary_storage_labeling_positiony"',
                  QgsPalLayerSettings.PositionY),
                 ('case when "auxiliary_storage_labeling_positionx" is NULL then NULL when  "auxiliary_storage_labeling_positionx" < x( if( layer_property( @layer_name, \'geometry_type\' ) = \'Line\', closest_point( $geometry, make_point("auxiliary_storage_labeling_positionx", "auxiliary_storage_labeling_positiony") ), centroid($geometry) ) ) then \'Right\' else \'Left\' end', QgsPalLayerSettings.Hali),
                 ('\'Half\'', QgsPalLayerSettings.Vali),
                 ('if( "auxiliary_storage_labeling_positionx" is not NULL, True, False )', QgsPalLayerSettings.BufferDraw)
                 # ,('10', QgsPalLayerSettings.BufferSize)
                 )

        pc = QgsPropertyCollection('labelConnector')
        for prop in props:
            p = QgsProperty()
            p.setExpressionString(prop[0])
            pc.setProperty(prop[1], p)

        pal_layer = QgsPalLayerSettings()
        pal_layer.setDataDefinedProperties(pc)
        labeling = self.layer.labeling()
        if labeling is None:
            pal_layer.fieldName = self.layer.fields()[0].name()
            pal_layer.isExpression = False
        else:
            pal_layer.fieldName = labeling.settings().fieldName
            pal_layer.isExpression = labeling.settings().isExpression
        if self.layer.geometryType() == QgsWkbTypes.LineGeometry:
            pal_layer.placement = QgsPalLayerSettings.Line
        pal_layer.enabled = True

        labeler = QgsVectorLayerSimpleLabeling(pal_layer)

        self.layer.setLabeling(labeler)
        self.layer.setLabelsEnabled(True)
コード例 #2
0
    def linkProperty(self):
        layer = self.iface.mapCanvas().currentLayer()
        # parameters for advanced labeling -- picked up from a qgs model file
        # generic labeling properties
        layer.setCustomProperty("labeling/fieldName",
                                share.field_list[0][0])  #[0][0] )
        layer.setCustomProperty("labeling",
                                "pal")  # new gen labeling activated
        layer.setCustomProperty("labeling/multiLineLabels",
                                "true")  # default value
        layer.setCustomProperty("labeling/enabled", "true")  # default value
        layer.setCustomProperty("labeling/priority",
                                "10")  # puts a high priority to labeling layer
        layer.setCustomProperty("labeling/multilineAlign",
                                "1")  # multiline align to center

        # line properties case
        layer.setCustomProperty(
            "labeling/placement", "2"
        )  #  OnLine = 1, AboveLine = 2, BelowLine = 4, MapOrientation = 8

        # data defined properties
        layer.setCustomProperty("labeling/dataDefined/PositionX",
                                "1~~0~~~~" + share.field_list[1][0])
        layer.setCustomProperty("labeling/dataDefined/PositionY",
                                "1~~0~~~~" + share.field_list[2][0])
        layer.setCustomProperty("labeling/dataDefined/Rotation",
                                "1~~0~~~~" + share.field_list[3][0])
        layer.setCustomProperty("labeling/dataDefined/Show",
                                "1~~0~~~~" + share.field_list[4][0])
        layer.setCustomProperty("labeling/dataDefined/Hali",
                                "1~~0~~~~" + share.field_list[5][0])
        layer.setCustomProperty("labeling/dataDefined/Vali",
                                "1~~0~~~~" + share.field_list[6][0])

        # set data define in a pyqigs3 way
        # link:https://gis.stackexchange.com/questions/313898/how-to-set-qgspropertycollection-via-an-dict
        pc = QgsPropertyCollection('qpc')

        sp = {
            9: share.field_list[1][0],
            10: share.field_list[2][0],
            96: share.field_list[3][0],
            15: share.field_list[4][0],
            11: share.field_list[5][0],
            12: share.field_list[6][0]
        }

        for k, v in sp.items():
            x = QgsProperty()
            x.setField(v)
            pc.setProperty(k, x)

        pal_layer = QgsPalLayerSettings()
        pal_layer.fieldName = share.field_list[0][0]
        pal_layer.setDataDefinedProperties(pc)
        pal_layer.enabled = True
        labeler = QgsVectorLayerSimpleLabeling(pal_layer)
        layer.setLabeling(labeler)
        layer.setLabelsEnabled(True)
コード例 #3
0
    def testObstacles(self):
        w = QgsLabelObstacleSettingsWidget()
        settings = QgsLabelObstacleSettings()
        settings.setFactor(0.4)
        settings.setType(QgsLabelObstacleSettings.PolygonBoundary)
        spy = QSignalSpy(w.changed)
        w.setSettings(settings)
        self.assertEqual(len(spy), 0)
        settings = w.settings()
        self.assertEqual(settings.factor(), 0.4)
        self.assertEqual(settings.type(),
                         QgsLabelObstacleSettings.PolygonBoundary)
        settings.setFactor(1.2)
        settings.setType(QgsLabelObstacleSettings.PolygonInterior)
        w.setSettings(settings)
        self.assertEqual(len(spy), 0)
        settings = w.settings()
        self.assertEqual(settings.factor(), 1.2)
        self.assertEqual(settings.type(),
                         QgsLabelObstacleSettings.PolygonInterior)

        props = QgsPropertyCollection()
        props.setProperty(QgsPalLayerSettings.ObstacleFactor,
                          QgsProperty.fromValue(5))
        w.setDataDefinedProperties(props)

        props = QgsPropertyCollection()
        self.assertFalse(props.isActive(QgsPalLayerSettings.ObstacleFactor))
        w.updateDataDefinedProperties(props)
        self.assertTrue(props.isActive(QgsPalLayerSettings.ObstacleFactor))
        props = w.dataDefinedProperties()
        prop = props.property(QgsPalLayerSettings.ObstacleFactor)
        self.assertEqual(prop.asExpression(), '5')
    def testUpdateDataDefinedProps(self):
        settings = QgsLabelObstacleSettings()
        settings.setFactor(0.1)
        self.assertEqual(settings.factor(), 0.1)

        props = QgsPropertyCollection()
        props.setProperty(QgsPalLayerSettings.ObstacleFactor,
                          QgsProperty.fromExpression('@factor'))
        context = QgsExpressionContext()
        scope = QgsExpressionContextScope()
        scope.setVariable('factor', 9)
        context.appendScope(scope)
        settings.updateDataDefinedProperties(props, context)
        self.assertAlmostEqual(settings.factor(), 1.8, 3)
コード例 #5
0
    def testUpdateDataDefinedProps(self):
        settings = QgsLabelLineSettings()
        settings.setPlacementFlags(QgsLabeling.LinePlacementFlag.OnLine)
        settings.setOverrunDistance(5.6)
        settings.setLineAnchorPercent(0.3)
        self.assertEqual(settings.placementFlags(),
                         QgsLabeling.LinePlacementFlag.OnLine)
        self.assertEqual(settings.overrunDistance(), 5.6)
        self.assertEqual(settings.lineAnchorPercent(), 0.3)

        props = QgsPropertyCollection()
        props.setProperty(QgsPalLayerSettings.LinePlacementOptions,
                          QgsProperty.fromExpression('@placement'))
        props.setProperty(QgsPalLayerSettings.OverrunDistance,
                          QgsProperty.fromExpression('@dist'))
        props.setProperty(QgsPalLayerSettings.LineAnchorPercent,
                          QgsProperty.fromExpression('@line_anchor'))
        context = QgsExpressionContext()
        scope = QgsExpressionContextScope()
        scope.setVariable('placement', 'AL,LO')
        scope.setVariable('dist', '11.2')
        scope.setVariable('line_anchor', '0.6')
        context.appendScope(scope)
        settings.updateDataDefinedProperties(props, context)
        self.assertEqual(settings.placementFlags(),
                         QgsLabeling.LinePlacementFlag.AboveLine)
        self.assertEqual(settings.overrunDistance(), 11.2)
        self.assertEqual(settings.lineAnchorPercent(), 0.6)
コード例 #6
0
 def duplicate_plot(self, index):
     """
     Duplicates a plot and adds it to the item
     """
     if index < len(self.plot_settings):
         plot_setting = PlotSettings(self.plot_settings[index].plot_type, self.plot_settings[index].properties,
                                     self.plot_settings[index].layout, self.plot_settings[index].source_layer_id)
         plot_setting.data_defined_properties = QgsPropertyCollection(
             self.plot_settings[index].data_defined_properties)
         plot_setting.layout['bg_color'] = 'rgba(0,0,0,0)'
         self.plot_settings.insert(index + 1, plot_setting)
         return plot_setting
コード例 #7
0
 def random_cat_symb(self, layer: QgsVectorLayer, field: str,
                     properties: dict):
     categories = []
     for unique_value in self.unique_field_finder(layer, field):
         symbol = self.create_simple_fill_symbol_layer(
             layer,
             fill_color=QColor(randrange(0, 256), randrange(0, 256),
                               randrange(0, 256)))
         category = QgsRendererCategory(
             unique_value, symbol, unique_value
         )  # TODO: removed encode('Latin-1'), is this causing troubles?
         # entry for the list of category items
         categories.append(category)
     # create renderer object
     renderer = QgsCategorizedSymbolRenderer(field, categories)
     # assign the created renderer to the layer
     if renderer is not None:
         layer.setRenderer(renderer)
         property_collection = QgsPropertyCollection()
         for key, value in properties.items():
             property_collection.setProperty(key, value)
         self.change_properties(layer, property_collection)
コード例 #8
0
    def setCollectionSettings(self):
        lyrids, lyrnames = self.lyrPair()
        coll = self.setFieldsCollection()
        arial = self.setArialDict()
        ssnr = self.setSsnrDict()
        swi = self.setSwiDict()
        times = self.setTimesDict()

        for names in lyrnames.values():
            lyr = QgsProject.instance().mapLayersByName(names)[0]
            iface.setActiveLayer(lyr)
            pc = QgsPropertyCollection('qpc')
            lyr_settings = QgsPalLayerSettings()
            txt_format = QgsTextFormat()
            txt_format.setSizeUnit(QgsUnitTypes.RenderPoints)

            for nColl, fColl in coll.items():
                x = QgsProperty()
                x.setField(fColl)
                pc.setProperty(nColl, x)
                pc.setProperty(31, '/')
                pc.setProperty(32, 0.8)

                if names in arial.values():
                    txt_format.setFont(QFont("Arial"))
                    txt_format.setColor(QColor(0, 0, 0))
                elif names in ssnr.values():
                    txt_format.setFont(QFont("Xerox Sans Serif Narrow"))
                    txt_format.setColor(QColor(0, 0, 0))
                elif names in swi.values():
                    txt_format.setFont(QFont("Xerox Serif Wide"))
                    if re.search(r"\Bcotado", names):
                        txt_format.setColor(QColor(140, 58, 61))
                    elif re.search(r"\Bcurva", names):
                        txt_format.setColor(QColor(140, 58, 61))
                    else:
                        txt_format.setColor(QColor(0, 119, 189))
                elif names in times.values():
                    txt_format.setFont(QFont("Times New Roman"))
                    txt_format.setColor(QColor(0, 0, 0))
                pass

            lyr_settings.setFormat(txt_format)
            lyr_settings.setDataDefinedProperties(pc)
            lyr_settings.enabled = True
            if names == "rel_ponto_cotado_altimetrico_p":
                lyr_settings.fieldName = "cota"
            else:
                lyr_settings.fieldName = "legenda"
            lyr_settings = QgsVectorLayerSimpleLabeling(lyr_settings)
            lyr.setLabelsEnabled(True)
            lyr.setLabeling(lyr_settings)
            lyr.triggerRepaint()
コード例 #9
0
    def testBase(self):
        """ test base class """
        w = QgsLabelSettingsWidgetBase()
        spy = QSignalSpy(w.changed)

        props = QgsPropertyCollection()
        props.setProperty(QgsPalLayerSettings.ObstacleFactor,
                          QgsProperty.fromValue(5))
        props.setProperty(QgsPalLayerSettings.IsObstacle,
                          QgsProperty.fromValue(True))
        w.setDataDefinedProperties(props)
        self.assertEqual(len(spy), 0)
        dd_props = w.dataDefinedProperties()
        prop = dd_props.property(QgsPalLayerSettings.ObstacleFactor)
        self.assertEqual(prop.asExpression(), '5')
        prop = dd_props.property(QgsPalLayerSettings.IsObstacle)
        self.assertEqual(prop.asExpression(), 'TRUE')
コード例 #10
0
    def grid_labeler(self, coord_base_x, coord_base_y, px, py, u, t, dx, dy,
                     desc, fSize, fontType, expression_str, trLLUTM, llcolor,
                     layer_bound, trUTMLL):
        pgrid = QgsPoint(coord_base_x + px * u, coord_base_y + py * t)
        pgrid.transform(trLLUTM)
        pgrid = QgsPoint(pgrid.x() + dx, pgrid.y() + dy)
        if layer_bound.crs().isGeographic() == True:
            pgrid.transform(trUTMLL)
        #Label Format Settings
        settings = QgsPalLayerSettings()
        settings.placement = 1
        settings.isExpression = True
        textprop = QgsTextFormat()
        textprop.setColor(llcolor)
        textprop.setSizeUnit(4)
        textprop.setSize(fSize * 2.8346)
        textprop.setFont(QFont(fontType))
        textprop.setLineHeight(1)
        settings.setFormat(textprop)
        settings.fieldName = expression_str

        #Label Position
        settings.geometryGeneratorEnabled = True
        settings.geometryGenerator = ("make_point({}, {})".format(
            pgrid.x(), pgrid.y()))
        datadefined = QgsPropertyCollection()
        datadefined.property(20).setExpressionString('True')
        datadefined.property(20).setActive(True)
        datadefined.property(15).setExpressionString('True')
        datadefined.property(15).setActive(True)
        datadefined.property(77).setExpressionString('2')
        datadefined.property(77).setActive(True)

        #Creating and Activating Labeling Rule
        settings.setDataDefinedProperties(datadefined)
        rule = QgsRuleBasedLabeling.Rule(settings)
        rule.setDescription(desc)
        rule.setActive(True)

        return rule
コード例 #11
0
ファイル: plot_settings.py プロジェクト: yaghout/DataPlotly
    def __init__(self,
                 plot_type: str = 'scatter',
                 properties: dict = None,
                 layout: dict = None,
                 source_layer_id=None):
        # Define default plot dictionary used as a basis for plot initialization
        # prepare the default dictionary with None values
        # plot properties
        plot_base_properties = {
            'marker': 'markers',
            'custom': None,
            'hover_text': None,
            'additional_hover_text': None,
            'x_name': '',
            'y_name': '',
            'z_name': '',
            'in_color': '#8ebad9',
            'out_color': '#1f77b4',
            'marker_width': 1,
            'marker_size': 10,
            'marker_symbol': 0,
            'line_dash': 'solid',
            'box_orientation': 'v',
            'box_stat': None,
            'box_outliers': False,
            'name': '',
            'normalization': None,
            'cont_type': 'fill',
            'color_scale': None,
            'show_lines': False,
            'cumulative': False,
            'show_colorscale_legend': False,
            'invert_color_scale': False,
            'invert_hist': 'increasing',
            'bins': 0,
            'selected_features_only': False,
            'visible_features_only': False,
            'color_scale_data_defined_in_check': False,
            'color_scale_data_defined_in_invert_check': False,
            'marker_type_combo': 'Points',
            'point_combo': '',
            'line_combo': 'Solid Line',
            'contour_type_combo': 'Fill',
            'show_lines_check': False,
            'opacity': 1,
            'violin_side': None,
            'show_mean_line': False
        }

        # layout nested dictionary
        plot_base_layout = {
            'title': 'Plot Title',
            'legend': True,
            'legend_title': None,
            'legend_orientation': 'h',
            'x_title': '',
            'y_title': '',
            'z_title': '',
            'xaxis': None,
            'bar_mode': None,
            'x_type': None,
            'y_type': None,
            'x_inv': None,
            'y_inv': None,
            'range_slider': {
                'borderwidth': 1,
                'visible': False
            },
            'bargaps': 0,
            'polar': {
                'angularaxis': {
                    'direction': 'clockwise'
                }
            },
            'additional_info_expression': '',
            'bins_check': False
        }

        self.plot_base_dic = {
            'plot_type': None,
            'layer': None,
            'plot_prop': plot_base_properties,
            'layout_prop': plot_base_layout
        }

        self.data_defined_properties = QgsPropertyCollection()

        # Set class properties - we use the base dictionaries, replacing base values with
        # those from the passed properties dicts
        if properties is None:
            self.properties = plot_base_properties
        else:
            self.properties = {**plot_base_properties, **properties}
        if layout is None:
            self.layout = plot_base_layout
        else:
            self.layout = {**plot_base_layout, **layout}

        self.plot_type = plot_type

        self.x = []
        self.y = []
        self.z = []
        self.feature_ids = []
        self.additional_hover_text = []
        self.data_defined_marker_sizes = []
        self.data_defined_colors = []
        self.data_defined_stroke_colors = []
        self.data_defined_stroke_widths = []
        self.source_layer_id = source_layer_id
コード例 #12
0
ファイル: plot_settings.py プロジェクト: yaghout/DataPlotly
class PlotSettings:  # pylint: disable=too-many-instance-attributes
    """
    The PlotSettings class encapsulates all settings relating to a plot, and contains
    methods for serializing and deserializing these settings.
    """

    PROPERTY_FILTER = 1
    PROPERTY_MARKER_SIZE = 2
    PROPERTY_COLOR = 3
    PROPERTY_STROKE_COLOR = 4
    PROPERTY_STROKE_WIDTH = 5

    DYNAMIC_PROPERTIES = {
        PROPERTY_FILTER:
        QgsPropertyDefinition('filter', 'Feature filter',
                              QgsPropertyDefinition.Boolean),
        PROPERTY_MARKER_SIZE:
        QgsPropertyDefinition('marker_size', 'Marker size',
                              QgsPropertyDefinition.DoublePositive),
        PROPERTY_COLOR:
        QgsPropertyDefinition('color', 'Color',
                              QgsPropertyDefinition.ColorWithAlpha),
        PROPERTY_STROKE_COLOR:
        QgsPropertyDefinition('stroke_color', 'Stroke color',
                              QgsPropertyDefinition.ColorWithAlpha),
        PROPERTY_STROKE_WIDTH:
        QgsPropertyDefinition('stroke_width', 'Stroke width',
                              QgsPropertyDefinition.DoublePositive)
    }

    def __init__(self,
                 plot_type: str = 'scatter',
                 properties: dict = None,
                 layout: dict = None,
                 source_layer_id=None):
        # Define default plot dictionary used as a basis for plot initialization
        # prepare the default dictionary with None values
        # plot properties
        plot_base_properties = {
            'marker': 'markers',
            'custom': None,
            'hover_text': None,
            'additional_hover_text': None,
            'x_name': '',
            'y_name': '',
            'z_name': '',
            'in_color': '#8ebad9',
            'out_color': '#1f77b4',
            'marker_width': 1,
            'marker_size': 10,
            'marker_symbol': 0,
            'line_dash': 'solid',
            'box_orientation': 'v',
            'box_stat': None,
            'box_outliers': False,
            'name': '',
            'normalization': None,
            'cont_type': 'fill',
            'color_scale': None,
            'show_lines': False,
            'cumulative': False,
            'show_colorscale_legend': False,
            'invert_color_scale': False,
            'invert_hist': 'increasing',
            'bins': 0,
            'selected_features_only': False,
            'visible_features_only': False,
            'color_scale_data_defined_in_check': False,
            'color_scale_data_defined_in_invert_check': False,
            'marker_type_combo': 'Points',
            'point_combo': '',
            'line_combo': 'Solid Line',
            'contour_type_combo': 'Fill',
            'show_lines_check': False,
            'opacity': 1,
            'violin_side': None,
            'show_mean_line': False
        }

        # layout nested dictionary
        plot_base_layout = {
            'title': 'Plot Title',
            'legend': True,
            'legend_title': None,
            'legend_orientation': 'h',
            'x_title': '',
            'y_title': '',
            'z_title': '',
            'xaxis': None,
            'bar_mode': None,
            'x_type': None,
            'y_type': None,
            'x_inv': None,
            'y_inv': None,
            'range_slider': {
                'borderwidth': 1,
                'visible': False
            },
            'bargaps': 0,
            'polar': {
                'angularaxis': {
                    'direction': 'clockwise'
                }
            },
            'additional_info_expression': '',
            'bins_check': False
        }

        self.plot_base_dic = {
            'plot_type': None,
            'layer': None,
            'plot_prop': plot_base_properties,
            'layout_prop': plot_base_layout
        }

        self.data_defined_properties = QgsPropertyCollection()

        # Set class properties - we use the base dictionaries, replacing base values with
        # those from the passed properties dicts
        if properties is None:
            self.properties = plot_base_properties
        else:
            self.properties = {**plot_base_properties, **properties}
        if layout is None:
            self.layout = plot_base_layout
        else:
            self.layout = {**plot_base_layout, **layout}

        self.plot_type = plot_type

        self.x = []
        self.y = []
        self.z = []
        self.feature_ids = []
        self.additional_hover_text = []
        self.data_defined_marker_sizes = []
        self.data_defined_colors = []
        self.data_defined_stroke_colors = []
        self.data_defined_stroke_widths = []
        self.source_layer_id = source_layer_id

    def write_xml(self, document: QDomDocument):
        """
        Writes the plot settings to an XML element
        """
        element = QgsXmlUtils.writeVariant(
            {
                'plot_type':
                self.plot_type,
                'plot_properties':
                self.properties,
                'plot_layout':
                self.layout,
                'source_layer_id':
                self.source_layer_id,
                'dynamic_properties':
                self.data_defined_properties.toVariant(
                    PlotSettings.DYNAMIC_PROPERTIES)
            }, document)
        return element

    def read_xml(self, element: QDomElement) -> bool:
        """
        Reads the plot settings from an XML element
        """
        res = QgsXmlUtils.readVariant(element)
        if not isinstance(res, dict) or \
                'plot_type' not in res or \
                'plot_properties' not in res or \
                'plot_layout' not in res:
            return False

        self.plot_type = res['plot_type']
        self.properties = res['plot_properties']
        self.layout = res['plot_layout']
        self.source_layer_id = res.get('source_layer_id', None)
        self.data_defined_properties.loadVariant(
            res.get('dynamic_properties', None),
            PlotSettings.DYNAMIC_PROPERTIES)

        return True

    def write_to_project(self, document: QDomDocument):
        """
        Writes the settings to a project (represented by the given DOM document)
        """
        elem = self.write_xml(document)
        parent_elem = document.createElement('DataPlotly')
        parent_elem.appendChild(elem)

        root_node = document.elementsByTagName("qgis").item(0)
        root_node.appendChild(parent_elem)

    def read_from_project(self, document: QDomDocument):
        """
        Reads the settings from a project (represented by the given DOM document)
        """
        root_node = document.elementsByTagName("qgis").item(0)
        if root_node.isNull():
            return False

        node = root_node.toElement().firstChildElement('DataPlotly')
        if node.isNull():
            return False

        elem = node.toElement()
        return self.read_xml(elem.firstChildElement())

    def write_to_file(self, file_name: str) -> bool:
        """
        Writes the settings to an XML file
        """
        document = QDomDocument("dataplotly")
        elem = self.write_xml(document)
        document.appendChild(elem)

        try:
            with open(file_name, "w") as f:
                f.write('<?xml version="1.0" encoding="UTF-8"?>\n')
                f.write(document.toString())
                return True
        except FileNotFoundError:
            return False

    def read_from_file(self, file_name: str) -> bool:
        """
        Reads the settings from an XML file
        """
        f = QFile(file_name)
        if f.open(QIODevice.ReadOnly):
            document = QDomDocument()
            if document.setContent(f):
                if self.read_xml(document.firstChildElement()):
                    return True

        return False
コード例 #13
0
    def grid_labeler(self, coord_base_x, coord_base_y, px, py, u, t, dx, dy,
                     vAlign, hAlign, desc, fSize, fontType, expression_str,
                     trLLUTM, trUTMLL, llcolor, utmcheck, scale):
        if utmcheck:
            pgrid = QgsPoint(coord_base_x + px * u, coord_base_y + py * t)
            pgrid.transform(trLLUTM)
            pgrid = QgsPoint(pgrid.x() + dx, pgrid.y() + dy)
        else:
            pgrid = QgsPoint(coord_base_x + px * u + dx,
                             coord_base_y + py * t + dy)

        #Label Format Settings
        settings = QgsPalLayerSettings()
        settings.Placement = QgsPalLayerSettings.Free
        settings.isExpression = True
        textprop = QgsTextFormat()
        textprop.setColor(llcolor)
        textprop.setSizeUnit(1)
        textprop.setSize(fSize * scale * 1.324)
        textprop.setFont(QFont(fontType))
        textprop.setLineHeight(1)
        settings.setFormat(textprop)
        settings.fieldName = expression_str

        #Label Name and Position
        datadefined = QgsPropertyCollection()
        datadefined.setProperty(9, pgrid.x())
        datadefined.setProperty(10, pgrid.y())
        if not (hAlign == ''):
            datadefined.setProperty(11, hAlign)
        if not (vAlign == ''):
            datadefined.setProperty(12, vAlign)
        datadefined.setProperty(20, 1)

        #Creating and Activating Labeling Rule
        settings.setDataDefinedProperties(datadefined)
        rule = QgsRuleBasedLabeling.Rule(settings)
        rule.setDescription(desc)
        rule.setActive(True)

        return rule
コード例 #14
0
ファイル: mapbox2qgis.py プロジェクト: wonder-sk/mapbox2qgis
def parse_symbol_layer(json_layer):

    json_layout = json_layer['layout']
    json_paint = json_layer['paint']

    dd_properties = {}

    TEXT_SIZE_MULTIPLIER = 2  # *2 because of high-res screen?

    text_size = 16
    if 'text-size' in json_layout:
        json_text_size = json_layout['text-size']
        if isinstance(json_text_size, (float, int)):
            text_size = json_text_size
        elif isinstance(json_text_size, dict):
            dd_properties[
                QgsPalLayerSettings.Size] = parse_interpolate_by_zoom(
                    json_text_size, TEXT_SIZE_MULTIPLIER)
        else:
            print("skipping non-float text-size", json_text_size)

    # TODO: text-font

    text_color = Qt.black
    if 'text-color' in json_paint:
        json_text_color = json_paint['text-color']
        if isinstance(json_text_color, str):
            text_color = parse_color(json_text_color)
        else:
            print("skipping non-string text-color", json_text_color)

    buffer_color = QColor(0, 0, 0, 0)
    if 'text-halo-color' in json_paint:
        json_text_halo_color = json_paint['text-halo-color']
        if isinstance(json_text_halo_color, str):
            buffer_color = parse_color(json_text_halo_color)
        else:
            print("skipping non-string text-halo-color", json_text_halo_color)

    buffer_size = 0
    if 'text-halo-width' in json_paint:
        json_text_halo_width = json_paint['text-halo-width']
        if isinstance(json_text_halo_width, (float, int)):
            buffer_size = json_text_halo_width
        else:
            print("skipping non-float text-halo-width", json_text_halo_width)

    format = QgsTextFormat()
    format.setColor(text_color)
    format.setSize(text_size * TEXT_SIZE_MULTIPLIER)
    format.setSizeUnit(QgsUnitTypes.RenderPixels)
    #format.setFont(font)

    if buffer_size > 0:
        buffer_settings = QgsTextBufferSettings()
        buffer_settings.setEnabled(True)
        buffer_settings.setSize(buffer_size * PX_TO_MM * TEXT_SIZE_MULTIPLIER)
        buffer_settings.setColor(buffer_color)
        format.setBuffer(buffer_settings)

    label_settings = QgsPalLayerSettings()
    label_settings.fieldName = '"name:latin"'  # TODO: parse field name
    label_settings.isExpression = True
    label_settings.placement = QgsPalLayerSettings.OverPoint
    label_settings.priority = min(text_size / 3., 10.)
    label_settings.setFormat(format)

    if dd_properties:
        for dd_key, dd_expression in dd_properties.items():
            prop_collection = QgsPropertyCollection()
            prop_collection.setProperty(
                dd_key, QgsProperty.fromExpression(dd_expression))
        label_settings.setDataDefinedProperties(prop_collection)

    lb = QgsVectorTileBasicLabelingStyle()
    lb.setGeometryType(QgsWkbTypes.PointGeometry)
    lb.setLabelSettings(label_settings)
    return lb
コード例 #15
0
    def testBasic(self):
        props = QgsVectorLayerElevationProperties(None)
        self.assertEqual(props.zScale(), 1)
        self.assertEqual(props.zOffset(), 0)
        self.assertFalse(props.extrusionEnabled())
        self.assertEqual(props.extrusionHeight(), 0)
        self.assertTrue(props.hasElevation())
        self.assertEqual(props.clamping(), Qgis.AltitudeClamping.Terrain)
        self.assertEqual(props.binding(), Qgis.AltitudeBinding.Centroid)
        self.assertTrue(props.respectLayerSymbology())
        self.assertEqual(props.type(),
                         Qgis.VectorProfileType.IndividualFeatures)
        self.assertEqual(props.profileSymbology(),
                         Qgis.ProfileSurfaceSymbology.Line)
        self.assertFalse(props.showMarkerSymbolInSurfacePlots())

        props.setZOffset(0.5)
        props.setZScale(2)
        props.setClamping(Qgis.AltitudeClamping.Relative)
        props.setBinding(Qgis.AltitudeBinding.Vertex)
        props.setExtrusionHeight(10)
        props.setExtrusionEnabled(True)
        props.setRespectLayerSymbology(False)
        props.setType(Qgis.VectorProfileType.ContinuousSurface)
        props.setProfileSymbology(Qgis.ProfileSurfaceSymbology.FillBelow)
        props.setShowMarkerSymbolInSurfacePlots(True)

        self.assertEqual(props.zScale(), 2)
        self.assertEqual(props.zOffset(), 0.5)
        self.assertEqual(props.extrusionHeight(), 10)
        self.assertTrue(props.hasElevation())
        self.assertTrue(props.extrusionEnabled())
        self.assertEqual(props.clamping(), Qgis.AltitudeClamping.Relative)
        self.assertEqual(props.binding(), Qgis.AltitudeBinding.Vertex)
        self.assertFalse(props.respectLayerSymbology())
        self.assertEqual(props.type(),
                         Qgis.VectorProfileType.ContinuousSurface)
        self.assertEqual(props.profileSymbology(),
                         Qgis.ProfileSurfaceSymbology.FillBelow)
        self.assertTrue(props.showMarkerSymbolInSurfacePlots())

        props.dataDefinedProperties().setProperty(
            QgsMapLayerElevationProperties.ExtrusionHeight,
            QgsProperty.fromExpression('1*5'))
        self.assertEqual(
            props.dataDefinedProperties().property(
                QgsMapLayerElevationProperties.ExtrusionHeight).asExpression(),
            '1*5')
        properties = QgsPropertyCollection()
        properties.setProperty(QgsMapLayerElevationProperties.ZOffset,
                               QgsProperty.fromExpression('9'))
        props.setDataDefinedProperties(properties)
        self.assertFalse(props.dataDefinedProperties().isActive(
            QgsMapLayerElevationProperties.ExtrusionHeight))
        self.assertEqual(
            props.dataDefinedProperties().property(
                QgsMapLayerElevationProperties.ZOffset).asExpression(), '9')

        sym = QgsLineSymbol.createSimple({
            'outline_color': '#ff4433',
            'outline_width': 0.5
        })
        props.setProfileLineSymbol(sym)
        self.assertEqual(props.profileLineSymbol().color().name(), '#ff4433')

        sym = QgsFillSymbol.createSimple({
            'color': '#ff4455',
            'outline_width': 0.5
        })
        props.setProfileFillSymbol(sym)
        self.assertEqual(props.profileFillSymbol().color().name(), '#ff4455')

        sym = QgsMarkerSymbol.createSimple({
            'color': '#ff1122',
            'outline_width': 0.5
        })
        props.setProfileMarkerSymbol(sym)
        self.assertEqual(props.profileMarkerSymbol().color().name(), '#ff1122')

        doc = QDomDocument("testdoc")
        elem = doc.createElement('test')
        props.writeXml(elem, doc, QgsReadWriteContext())

        props2 = QgsVectorLayerElevationProperties(None)
        props2.readXml(elem, QgsReadWriteContext())
        self.assertEqual(props2.zScale(), 2)
        self.assertEqual(props2.zOffset(), 0.5)
        self.assertEqual(props2.clamping(), Qgis.AltitudeClamping.Relative)
        self.assertEqual(props2.binding(), Qgis.AltitudeBinding.Vertex)
        self.assertEqual(props2.extrusionHeight(), 10)
        self.assertTrue(props2.extrusionEnabled())
        self.assertFalse(props2.respectLayerSymbology())
        self.assertEqual(props2.type(),
                         Qgis.VectorProfileType.ContinuousSurface)
        self.assertEqual(props2.profileSymbology(),
                         Qgis.ProfileSurfaceSymbology.FillBelow)
        self.assertTrue(props2.showMarkerSymbolInSurfacePlots())

        self.assertEqual(props2.profileLineSymbol().color().name(), '#ff4433')
        self.assertEqual(props2.profileFillSymbol().color().name(), '#ff4455')
        self.assertEqual(props2.profileMarkerSymbol().color().name(),
                         '#ff1122')

        self.assertEqual(
            props2.dataDefinedProperties().property(
                QgsMapLayerElevationProperties.ZOffset).asExpression(), '9')

        props_clone = props.clone()
        self.assertEqual(props_clone.zScale(), 2)
        self.assertEqual(props_clone.zOffset(), 0.5)
        self.assertEqual(props_clone.clamping(),
                         Qgis.AltitudeClamping.Relative)
        self.assertEqual(props_clone.binding(), Qgis.AltitudeBinding.Vertex)
        self.assertEqual(props_clone.extrusionHeight(), 10)
        self.assertTrue(props_clone.extrusionEnabled())
        self.assertFalse(props_clone.respectLayerSymbology())
        self.assertEqual(props_clone.type(),
                         Qgis.VectorProfileType.ContinuousSurface)
        self.assertEqual(props_clone.profileSymbology(),
                         Qgis.ProfileSurfaceSymbology.FillBelow)
        self.assertTrue(props_clone.showMarkerSymbolInSurfacePlots())

        self.assertEqual(props_clone.profileLineSymbol().color().name(),
                         '#ff4433')
        self.assertEqual(props_clone.profileFillSymbol().color().name(),
                         '#ff4455')
        self.assertEqual(props_clone.profileMarkerSymbol().color().name(),
                         '#ff1122')

        self.assertEqual(
            props_clone.dataDefinedProperties().property(
                QgsMapLayerElevationProperties.ZOffset).asExpression(), '9')