def processAlgorithm(self, parameters, context, feedback):
        if Qgis.QGIS_VERSION_INT >= 31400:
            connection_name = self.parameterAsConnectionName(
                parameters, self.CONNECTION_NAME, context)
            schema = self.parameterAsSchema(parameters, self.SCHEMA, context)
        else:
            connection_name = self.parameterAsString(parameters,
                                                     self.CONNECTION_NAME,
                                                     context)
            schema = self.parameterAsString(parameters, self.SCHEMA, context)

        # Set global variable
        # noinspection PyCallByClass,PyArgumentList
        QgsExpressionContextUtils.setProjectVariable(
            context.project(), 'veloroutes_connection_name', connection_name)
        feedback.pushInfo(
            'Connection PostgreSQL à la base vvv "{}"'.format(connection_name))

        QgsExpressionContextUtils.setProjectVariable(context.project(),
                                                     'veloroutes_schema',
                                                     schema)
        feedback.pushInfo(
            'Schema PostgreSQL de la base vvv "{}"'.format(schema))

        msg = 'La configuration a été faite'
        feedback.pushInfo(msg)
        status = 1

        return {self.OUTPUT_STATUS: status, self.OUTPUT_STRING: msg}
Exemplo n.º 2
0
    def create_count(self):

        layer = self.layers['section']

        selected_count = layer.selectedFeatureCount()
        if selected_count == 0:
            push_info("Veuillez sélectionner un tronçon")
            return
        elif selected_count > 1:
            push_info("Veuillez ne sélectionner qu'un tronçon")
            return
        else:
            selected_feature = next(layer.getSelectedFeatures())

            lanes = self.get_lanes_of_section(selected_feature.attribute('id'))
            installation = self.get_installation_of_lane(
                next(lanes).attribute('id'))

            # Save the id of the installation related to the selected section
            # so we can use in the count form to automatically select the
            # installation in the combobox
            QgsExpressionContextUtils.setProjectVariable(
                QgsProject.instance(), 'selected_installation',
                installation.attribute('id'))
            self.layers['count'].startEditing()
            iface.setActiveLayer(self.layers['count'])
            iface.actionAddFeature().trigger()
Exemplo n.º 3
0
def certificate_preprocess(plot, plots):
    """
    Utility function that loads and renders plots that belong to a specific
    scheme.
    """
    scheme_plot_layer = lht_plot_layer(plot.scheme_id, CERTIFICATE_PLOT)
    QgsMapLayerRegistry.instance().addMapLayer(scheme_plot_layer)
    # Get the EPSG code of the plot
    epsg_code = plot.cb_check_lht_plot_crs.value
    # Setting the project CRS variable
    QgsExpressionContextUtils.setProjectVariable('flts_source_crs', epsg_code)

    # Styling reference plot using primary key
    filter_exp = '"id" = ' + str(plot.id)
    scheme_symbol = QgsSymbolV2.defaultSymbol(scheme_plot_layer.geometryType())
    # Rule-based rendering
    rule_renderer = QgsRuleBasedRendererV2(scheme_symbol)
    root_rule = rule_renderer.rootRule()

    # Rule for highlighting reference plot
    scheme_rule = root_rule.children()[0].clone()
    scheme_rule.setLabel('Reference Plot')
    scheme_rule.setFilterExpression(filter_exp)
    scheme_symbol_layer = scheme_rule.symbol().symbolLayer(0)
    scheme_symbol_layer.setFillColor(Qt.yellow)
    scheme_symbol_layer.setOutlineColor(Qt.black)
    scheme_symbol_layer.setBorderWidth(0.5)
    root_rule.appendChild(scheme_rule)

    # Rule for other plots
    def_rule = root_rule.children()[0].clone()
    def_rule.setLabel('Plots')
    def_rule.setIsElse(True)
    def_symbol_layer = def_rule.symbol().symbolLayer(0)
    def_symbol_layer.setFillColor(Qt.transparent)
    def_symbol_layer.setOutlineColor(Qt.black)
    root_rule.appendChild(def_rule)

    # Remove default rule
    root_rule.removeChildAt(0)

    # Set renderer
    scheme_plot_layer.setRendererV2(rule_renderer)

    # Enable labeling
    scheme_plot_layer.setCustomProperty("labeling", "pal")
    scheme_plot_layer.setCustomProperty("labeling/enabled", "true")
    scheme_plot_layer.setCustomProperty("labeling/fontFamily", "Arial")
    scheme_plot_layer.setCustomProperty("labeling/fontSize", "5.5")
    scheme_plot_layer.setCustomProperty("labeling/fieldName", "plot_number")
    scheme_plot_layer.setCustomProperty("labeling/placement", "1")
    scheme_plot_layer.setCustomProperty("labeling/centroidInside", "true")
    scheme_plot_layer.setCustomProperty("labeling/centroidWhole", "false")

    scheme_plot_layer.triggerRepaint()

    iface.mapCanvas().setExtent(scheme_plot_layer.extent())
    QgsApplication.processEvents()

    return True
Exemplo n.º 4
0
    def do_export_plan_action(self, count_id):
        plan_creator = PlanCreator(self.layers)
        file_dialog = QFileDialog()
        file_dialog.setDefaultSuffix('*.PDF')
        title = 'Exporter plan de pose'
        path = os.path.join(self.settings.value('config_export_directory'),
                            "{}.pdf".format("plan_de_pose"))
        file = QFileDialog.getSaveFileName(file_dialog, title, path,
                                           "Config file (*.PDF)")[0]

        if not file:
            return

        # Highlight the current sections and installation in the layout
        previous_highlightes_sections = self.layers.highlighted_sections
        self.layers.highlighted_sections = \
            self.layers.get_section_ids_of_count(count_id)
        QgsExpressionContextUtils.setProjectVariable(
            QgsProject.instance(), 'highlighted_installation',
            self.layers.get_installation_name_of_count(count_id))

        plan_creator.export_pdf(count_id, file)

        self.layers.highlighted_sections = previous_highlightes_sections
        QgsExpressionContextUtils.setProjectVariable(
            QgsProject.instance(), 'highlighted_installation', '')
        self.layers.layers['section'].triggerRepaint()
Exemplo n.º 5
0
 def changeCurrentIndex(i):
     QgsExpressionContextUtils.setProjectVariable(
         QgsProject.instance(),
         'level',
         self.dockwidget.levelComboBox.currentText()
     )
     self.iface.mapCanvas().refresh()
Exemplo n.º 6
0
    def ODKLoadLayerStateAction(self, fileName=None):
        if not fileName:
            workDir = QgsProject.instance().readPath("./")
            fileName = QFileDialog().getOpenFileName(
                None, self.tr("Load QGISODK project"), workDir, "*.json")
        if fileName:
            with open(fileName, "r") as json_file:
                restoreDict = json.load(json_file)
            ODKProjectName = QFileInfo(fileName).baseName()
            self.settingsDlg.importSettings(restoreDict['settings'])
            self.dlg.treeView.recover(restoreDict)
            self.dlg.setWindowTitle("QGISODK - " + ODKProjectName)
            #print restoreDict['targetLayer']['id']
            current_idx = self.dlg.layersComboBox.findData(
                restoreDict['targetLayer']['id'])
            if current_idx == -1:
                current_idx = self.dlg.layersComboBox.findText(
                    restoreDict['targetLayer']['name'])
                if current_idx == -1:
                    current_idx = 0
            #print current_idx

            #If found sets layers combo box with provided layer, disconnecting update signals....
            try:
                self.dlg.layersComboBox.currentIndexChanged.disconnect(
                    self.VectorLayerComboChanged)
            except:
                pass
            self.dlg.layersComboBox.setCurrentIndex(current_idx)
            self.dlg.layersComboBox.currentIndexChanged.connect(
                self.VectorLayerComboChanged)
            S = QSettings()
            QgsExpressionContextUtils.setProjectVariable(
                'QgisODK_current_project', fileName)
Exemplo n.º 7
0
 def store_variable(self, name: str, value):
     """Store UI values in the QGIS project variables
     :param name: The name of the variable to store
     :param value: The value of the variable to store
     """
     project = QgsProject.instance()
     QgsExpressionContextUtils.setProjectVariable(
         project, self.var_format.format(self.prefix, name), value)
Exemplo n.º 8
0
    def setConvergencia(self, conv):
        convergencia = self.generateDMS(conv)
        self.convergenciaEdit.setText(convergencia)

        proj = QgsProject.instance()
        QgsExpressionContextUtils.setProjectVariable(proj, 'convergenciaGMS',
                                                     convergencia)
        QgsExpressionContextUtils.setProjectVariable(proj, 'convergenciaGD',
                                                     conv)
Exemplo n.º 9
0
    def setDeclinacao(self, decl):
        declinacao = self.generateDMS(decl)
        self.declinacaoEdit.setText(declinacao)

        proj = QgsProject.instance()
        QgsExpressionContextUtils.setProjectVariable(proj, 'declinacaoGMS',
                                                     declinacao)
        QgsExpressionContextUtils.setProjectVariable(proj, 'declinacaoGD',
                                                     decl)
Exemplo n.º 10
0
   def processAlgorithm(self, parameters, context, feedback):
       """Here is where the processing itself takes place."""
       for [name,desc,default,paramtype] in self.PROPS:
           QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(), name,
                                                        self.parameterAsString(parameters, name, context))
       return {}
 
       
 
       
    def processAlgorithm(self, parameters, context, feedback):
        street_layer = self.parameterAsString(parameters, self.STREET_LAYER,
                                              context)
        address_layer = self.parameterAsString(parameters, self.ADDRESS_LAYER,
                                               context)

        QgsExpressionContextUtils.setProjectVariable(context.project(),
                                                     GESTION_ADRESSE_VOIE,
                                                     street_layer)
        QgsExpressionContextUtils.setProjectVariable(
            context.project(), GESTION_ADRESSE_POINT_ADRESSE, address_layer)
        return {}
Exemplo n.º 12
0
    def load_layers(self):
        settings = Settings()

        group_comptages = QgsProject.instance().layerTreeRoot().findGroup(
            'Comptages')
        group_extra = QgsProject.instance().layerTreeRoot().findGroup('Extra')

        if group_comptages is None:
            group_comptages = QgsProject.instance().layerTreeRoot().addGroup(
                'Comptages')

        if group_extra is None and settings.value("extra_layers"):
            group_extra = group_comptages.addGroup('Extra')

        for key in LAYER_DEFINITIONS:
            layer_definition = LAYER_DEFINITIONS[key]

            if not QgsProject.instance().mapLayersByName(
                    layer_definition['display_name']):

                layer = self.load_layer(
                    'comptages',  # Schema
                    layer_definition['table'],
                    layer_definition['geometry'],
                    layer_definition['sql'],
                    layer_definition['display_name'],
                    layer_definition['id'],
                    layer_definition['epsg'],
                )

                if layer_definition['legend']:
                    group_comptages.addLayer(layer)
                elif settings.value("extra_layers"):
                    group_extra.addLayer(layer)

                self.layers[key] = layer

        self.apply_qml_styles()
        self.add_layer_actions()
        self.create_virtual_fields()
        self.create_joins()
        self.create_relations()
        iface.setActiveLayer(self.layers['section'])

        self.populate_list_of_highlighted_sections()

        self.layers['count'].featureAdded.connect(self.on_count_added)

        from qgis.core import QgsExpressionContextUtils
        QgsExpressionContextUtils.setProjectVariable(
            QgsProject.instance(), 'highlighted_installation', '')
    def processAlgorithm(self, parameters, context, feedback):
        msg = ""
        output_layers = []
        layers_name = ["commune", "voie", "point_adresse", "parcelle"]
        layers_name_none = dict()
        layers_name_none["document"] = ""
        layers_name_none["v_commune"] = "insee_code"

        # override = self.parameterAsBool(parameters, self.OVERRIDE, context)
        connection = self.parameterAsString(parameters, self.DATABASE, context)

        feedback.pushInfo("## CONNEXION A LA BASE DE DONNEES ##")
        uri = uri_from_name(connection)

        is_host = uri.host() != ""
        if is_host:
            feedback.pushInfo("Connexion établie via l'hote")
        else:
            feedback.pushInfo("Connexion établie via le service")

        schema = self.parameterAsString(parameters, self.SCHEMA, context)
        feedback.pushInfo("")
        feedback.pushInfo("## CHARGEMENT DES COUCHES ##")
        for x in layers_name:
            if not context.project().mapLayersByName(x):
                result = self.initLayer(context, uri, schema, x, "geom", "")
                if not result:
                    feedback.pushInfo("La couche " + x +
                                      " ne peut pas être chargée")
                else:
                    output_layers.append(result.id())
                    if x == "voie":
                        QgsExpressionContextUtils.setProjectVariable(
                            context.project(), GESTION_ADRESSE_VOIE,
                            result.id())
                    elif x == "point_adresse":
                        QgsExpressionContextUtils.setProjectVariable(
                            context.project(),
                            GESTION_ADRESSE_POINT_ADRESSE,
                            result.id(),
                        )

        for x in layers_name_none:
            if not context.project().mapLayersByName(x):
                result = self.initLayer(context, uri, schema, x, None, "",
                                        layers_name_none[x])
                if not result:
                    feedback.pushInfo("La couche " + x +
                                      " ne peut pas être chargée")

        return {self.OUTPUT_MSG: msg, self.OUTPUT: output_layers}
Exemplo n.º 14
0
    def processAlgorithm(self, parameters, context, feedback):
        connection_name = parameters[self.CONNECTION_NAME]

        # Set project variable
        QgsExpressionContextUtils.setProjectVariable(context.project(), 'gobs_connection_name', connection_name)
        feedback.pushInfo(tr('PostgreSQL connection to G-Obs database') + ' = ' + connection_name)

        msg = tr('Configuration has been saved')
        feedback.pushInfo(msg)
        status = 1

        return {
            self.OUTPUT_STATUS: status,
            self.OUTPUT_STRING: msg
        }
Exemplo n.º 15
0
    def doAction(self, layer, uid, feature):
        if layer.actions().action(uid).name() == 'openFeatureForm':
            self.plugin.iface.openFeatureForm(layer, feature)
        else :
            ctxt = QgsExpressionContext()
            ctxt.appendScope(QgsExpressionContextUtils.globalScope())
            ctxt.appendScope(QgsExpressionContextUtils.projectScope(QgsProject.instance()))
            ctxt.appendScope(QgsExpressionContextUtils.mapSettingsScope(self.canvas.mapSettings()))

            # Add click_x and click_y to context
            p = self.toLayerCoordinates(layer, self.pos())            
            QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(), 'click_x', p.x())
            QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(), 'click_y', p.y())

            layer.actions().doAction(uid, feature, ctxt)
Exemplo n.º 16
0
def set_project_setting(key: str,
                        value: Union[str, int, float, bool],
                        internal: bool = True) -> bool:
    """
    Set a value in the QGIS project settings

    :param key: Key for the setting
    :param value: Value for the setting
    :param internal: Whether to search from only plugin settings or all
    """
    proj = QgsProject.instance()
    if internal:
        return proj.writeEntry(plugin_name(), key, value)
    else:
        QgsExpressionContextUtils.setProjectVariable(proj, key, value)
        return True
Exemplo n.º 17
0
def write_project_variables(project_owner, project_name, project_full_name,
                            version, server):
    QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(),
                                                 "mergin_project_name",
                                                 project_name)
    QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(),
                                                 "mergin_project_owner",
                                                 project_owner)
    QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(),
                                                 "mergin_project_full_name",
                                                 project_full_name)
    QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(),
                                                 "mergin_project_version",
                                                 int_version(version))
    QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(),
                                                 "mergin_project_server",
                                                 server)
Exemplo n.º 18
0
    def ODKSaveLayerStateAction(self):

        backupDict = {
            'fieldsState': self.dlg.treeView.backup(),
            'settings': self.settingsDlg.exportSettings(),
            'targetLayer': self.dlg.treeView.targetLayer
        }

        workDir = QgsProject.instance().readPath("./")
        fileName = QFileDialog().getSaveFileName(
            None, self.tr("Save QGISODK project"), workDir, "*.json")
        if fileName:
            if QFileInfo(fileName).suffix() != "json":
                fileName += ".json"
            with open(fileName, "w") as json_file:
                json.dump(backupDict, json_file)
        QgsExpressionContextUtils.setProjectVariable('QgisODK_current_project',
                                                     fileName)
Exemplo n.º 19
0
    def setCurrentProposal(self, value):
        """
        Set the current proposal
        """
        QgsMessageLog.logMessage(
            'Current proposal changed to {proposal_id}'.format(
                proposal_id=value),
            tag="TOMs panel")
        QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(),
                                                     'CurrentProposal', value)

        self.currProposalObject.setProposal(self.currentProposal())

        self.proposalChanged.emit()
        self.updateMapCanvas()

        box = self.currProposalObject.getProposalBoundingBox()
        if box.isNull() == False:
            self.canvas.setExtent(box)
Exemplo n.º 20
0
 def saveState(self):
     """
     Makes sure all added workflows are stored to active instance of
     QgsProject, making it "loadable" along with saved QGIS projects.
     """
     # workflow objects cannot be serialized, so they must be passed as dict
     workflows = dict()
     for w in self.workflows.values():
         workflows[w.displayName()] = w.asDict()
     
     QgsExpressionContextUtils.setProjectVariable(
         QgsProject.instance(),
         "dsgtools_qatoolbox_state",
         json.dumps({
             "workflows" : workflows,
             "current_workflow" : self.comboBox.currentIndex(),
             "showButtons" : self._showButtons
         })
     )
Exemplo n.º 21
0
    def doAction(self, layer, uid, feature):
        if layer.actions().action(uid).name() == 'openFeatureForm':
            self.plugin.iface.openFeatureForm(layer, feature)
        else:
            ctxt = QgsExpressionContext()
            ctxt.appendScope(QgsExpressionContextUtils.globalScope())
            ctxt.appendScope(
                QgsExpressionContextUtils.projectScope(QgsProject.instance()))
            ctxt.appendScope(
                QgsExpressionContextUtils.mapSettingsScope(
                    self.canvas.mapSettings()))

            # Add click_x and click_y to context
            p = self.toLayerCoordinates(layer, self.pos())
            QgsExpressionContextUtils.setProjectVariable(
                QgsProject.instance(), 'click_x', p.x())
            QgsExpressionContextUtils.setProjectVariable(
                QgsProject.instance(), 'click_y', p.y())

            layer.actions().doAction(uid, feature, ctxt)
    def processAlgorithm(self, parameters, context, feedback):
        """
        Here is where the processing itself takes place.
        """
        connection_name = self.parameterAsString(parameters, self.CONNECTION_NAME, context)

        # Set global variable
        # noinspection PyCallByClass,PyArgumentList
        QgsExpressionContextUtils.setProjectVariable(
            context.project(), 'veloroutes_connection_name', connection_name
        )
        feedback.pushInfo('Connection PostgreSQL à la base vvv "{}"'.format(connection_name))

        msg = 'La configuration a été faite'
        feedback.pushInfo(msg)
        status = 1

        return {
            self.OUTPUT_STATUS: status,
            self.OUTPUT_STRING: msg
        }
Exemplo n.º 23
0
    def run(self):
        """Run method that loads and starts the plugin"""

        if not self.pluginIsActive:
            self.pluginIsActive = True

            #print "** STARTING variablesLiveChanger"

            # dockwidget may not exist if:
            #    first run of plugin
            #    removed on close (see self.onClosePlugin method)
            if self.dockwidget == None:
                # Create the dockwidget (after translation) and keep reference
                self.dockwidget = variablesLiveChangerDockWidget()

                # Default level
                QgsExpressionContextUtils.setProjectVariable(
                    QgsProject.instance(), 'level', '0')
                self.dockwidget.levelComboBox.setCurrentIndex(5)

                def changeCurrentIndex(i):
                    QgsExpressionContextUtils.setProjectVariable(
                        QgsProject.instance(),
                        'level',
                        self.dockwidget.levelComboBox.currentText()
                    )
                    self.iface.mapCanvas().refresh()

                self.dockwidget.levelComboBox.currentIndexChanged.connect(
                    changeCurrentIndex
                )
                self.iface.mapCanvas().refresh()

            # connect to provide cleanup on closing of dockwidget
            self.dockwidget.closingPlugin.connect(self.onClosePlugin)

            # show the dockwidget
            # TODO: fix to allow choice of dock location
            self.iface.addDockWidget(Qt.RightDockWidgetArea, self.dockwidget)
            self.dockwidget.show()
Exemplo n.º 24
0
def write_project_variables(project_owner, project_name, project_full_name,
                            version):
    QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(),
                                                 'mergin_project_name',
                                                 project_name)
    QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(),
                                                 'mergin_project_owner',
                                                 project_owner)
    QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(),
                                                 'mergin_project_full_name',
                                                 project_full_name)
    QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(),
                                                 'mergin_project_version',
                                                 int_version(version))
Exemplo n.º 25
0
    def canvasReleaseEvent(self, event):
        """On click, do action"""
        if not self.plugin.active:
            return

        # left click only
        if event.button() not in (Qt.LeftButton, Qt.RightButton):
            return

        self.__pos = event.pos()

        # Add click_x and click_y to context
        if self.pos():
            QgsExpressionContextUtils.setProjectVariable(
                QgsProject.instance(), "click_x",
                self.pos().x())
            QgsExpressionContextUtils.setProjectVariable(
                QgsProject.instance(), "click_y",
                self.pos().y())

        self.findUnderlyingObjects(event, True)

        # if a single action (2 lines in the list)
        if len(self.featuresFound) == 1:
            layer = self.featuresFound[0]["layer"]
            id = self.featuresFound[0]["idxAction"]
            feature = self.featuresFound[0]["feature"]

            self.doAction(layer, id, feature)

        else:
            # to choose the action to trigger
            canvasPos = self.canvas.mapToGlobal(QPoint(0, 0))
            self.chooserDlg = ChooserDlg(
                self,
                self.featuresFound,
                canvasPos.x() + self.__pos.x(),
                canvasPos.y() + self.__pos.y(),
            )
            self.chooserDlg.go()
Exemplo n.º 26
0
    def fit_curve(self):
        try:
            import numpy as np
            import scipy.optimize
        except ImportError:
            self.iface.messageBar().pushMessage(
                "Atitude correction",
                "Cannot import numpy and/or scipy - cannot run fit",
                level=Qgis.Warning,
                duration=3)
            return ()
        self.iface.messageBar().pushMessage("Atitude correction",
                                            "Running ...",
                                            level=Qgis.Success,
                                            duration=3)

        # https://swharden.com/blog/2020-09-24-python-exponential-fit/
        # NTB - calc from waterdata
        #
        NTBact = self.waterdata[1]
        ntb = sum(NTBact) / len(NTBact)
        QgsExpressionContextUtils.setProjectVariable(QgsProject.instance(),
                                                     'altitudecorrection_ntb',
                                                     ntb)
        print(ntb)
        self.dlg.leNTB.setText(str(round(ntb, 6)))
        #waterfit=self.fit(self.waterdata)
        #print(waterfit)
        #print(waterfit[1])
        # "Canned" parameters
        # ntb=4.284670
        # ntbfactor=0.001743
        # ntb0=ntb+ntbfactor
        # expfactor=-0.006383
        # gmmdown=(value1-ntb)*math.exp(expfactor)/math.exp(expfactor*value2)+ ntb0
        calibdata = []
        # Subtracting ntb to get only terrestrial background
        calibdata = [x - ntb for x in self.landdata[1]]
        p0 = (50, 0.006, ntb)
        params, cv = scipy.optimize.curve_fit(self.monoExp, self.landdata[0],
                                              calibdata, p0)
        dose0, alpha, offset = params
        self.dlg.leDose0.setText(str(round(dose0, 6)))
        QgsExpressionContextUtils.setProjectVariable(
            QgsProject.instance(), 'altitudecorrection_dose0',
            float(dose0))  # params[0])
        self.dlg.leAlpha.setText(str(round(params[1], 6)))
        QgsExpressionContextUtils.setProjectVariable(
            QgsProject.instance(), 'altitudecorrection_alpha',
            float(alpha))  # params[1])
Exemplo n.º 27
0
        def makeShowZonesPdf():
            self.cursor.execute(Const.ZONES_QUERY, [int(feature[id_index])])
            rows = (row for row in self.cursor.fetchall() if row[Const.ZONES_COLUMNS.index('per_int')] >= 3)

            composition = None
            for item in self.iface.activeComposers():
                if item.composerWindow().windowTitle() == Const.PDF_ZONES:
                    composition = item.composition()
                    break
            if composition is None:
                return

            filename = os.path.join(self.reports_folder, '{}_zones.pdf'.format(info[Const.REFCAT]))
            printer = QPrinter()
            composition.beginPrintAsPDF(printer, filename)
            composition.beginPrint(printer, False)
            painter = QPainter()
            painter.begin(printer)

            first = True
            for data in rows:
                if first:
                    first = False
                else:
                    printer.newPage()
                for i, column in enumerate(Const.ZONES_COLUMNS):
                    QgsExpressionContextUtils.setProjectVariable(column, data[i])
                if info[Const.CODI_SECTOR] is not None:
                    QgsExpressionContextUtils.setProjectVariable('sec_descripcio', u'{} - {}'.format(info[Const.CODI_SECTOR], info[Const.DESCR_SECTOR]))
                else:
                    QgsExpressionContextUtils.setProjectVariable('sec_descripcio', None)
                QgsExpressionContextUtils.setProjectVariable('cla_descripcio', u'{} - {}'.format(info[Const.CODI_CLASSI], info[Const.DESCR_CLASSI]))
                composition.refreshItems()
                composition.doPrint(printer, painter)

            painter.end()
            openFile(filename)
Exemplo n.º 28
0
            def refreshed():
                # Disconnect signal
                self.iface.mapCanvas().mapCanvasRefreshed.disconnect(refreshed)

                # Get composition
                composition = None
                for item in self.iface.activeComposers():
                    if item.composerWindow().windowTitle() == Const.PDF_UBICACIO:
                        composition = item.composition()
                        break

                if composition is None:
                    return

                # Set values
                QgsExpressionContextUtils.setProjectVariable('refcat', info[Const.REFCAT])
                QgsExpressionContextUtils.setProjectVariable('area', '{:.0f}'.format(info[Const.AREA]))
                QgsExpressionContextUtils.setProjectVariable('adreca', info[Const.ADRECA])

                # Set main map to the propper position
                main_map = composition.getComposerItemById('Mapa principal')
                centerMap(main_map, feature)

                # Add temporal layer to composition
                legend = composition.getComposerItemById('Llegenda')
                legend_root = legend.modelV2().rootGroup()
                legend_root.insertLayer(0, vl)

                # Make PDF
                filename = os.path.join(self.reports_folder, '{}_ubicacio.pdf'.format(info[Const.REFCAT]))
                if composition.exportAsPDF(filename):
                    openFile(filename)
                else:
                    self.error(u"No s'ha pogut convertir a PDF.")

                # Delete temporary layer
                legend_root.removeLayer(vl)
                QgsMapLayerRegistry.instance().removeMapLayers([vl.id()])

                # Repaint again
                self.iface.mapCanvas().refresh()
Exemplo n.º 29
0
def setProjectVariable(project, variable, value):
    if (project is not None):
        QgsExpressionContextUtils.setProjectVariable(project, variable, value)
Exemplo n.º 30
0
    def updateVars(self):
        """Set the value of the variables from the user-entered values in the Edit Metadata tab"""

        # Initialise progressbar
        i = 0
        QApplication.setOverrideCursor(Qt.BusyCursor)
        currProject = QgsProject.instance()
        self.dlg.updateBar.setValue(0)
        self.dlg.updateBar.setMaximum(11)

        # self.dlg.layoutSelect.currentIndex():
        title = self.dlg.layoutSelect.currentText()
        self.dlg.printinglabel.setText(
            self.tr(u'Updating {}...').format(title))

        # process input events in order to allow canceling
        QCoreApplication.processEvents()

        # Project: update variables from dialog
        QgsExpressionContextUtils.setProjectVariable(currProject, 'ma_country',
                                                     self.dlg.maCountry.text())
        self.dlg.updateBar.setValue(self.dlg.updateBar.value() + 1)
        QgsExpressionContextUtils.setProjectVariable(currProject,
                                                     'ma_glide_number',
                                                     self.dlg.maGlide.text())
        self.dlg.updateBar.setValue(self.dlg.updateBar.value() + 1)
        QgsExpressionContextUtils.setProjectVariable(currProject, 'ma_crs',
                                                     self.dlg.maCrs.text())
        self.dlg.updateBar.setValue(self.dlg.updateBar.value() + 1)
        QgsExpressionContextUtils.setProjectVariable(
            currProject, 'ma_organisation', self.dlg.maOrganisation.text())
        self.dlg.updateBar.setValue(self.dlg.updateBar.value() + 1)
        QgsExpressionContextUtils.setProjectVariable(currProject, 'ma_country',
                                                     self.dlg.maCountry.text())
        self.dlg.updateBar.setValue(self.dlg.updateBar.value() + 1)
        QgsExpressionContextUtils.setProjectVariable(
            currProject, 'ma_opid', self.dlg.maOperationID.text())
        self.dlg.updateBar.setValue(self.dlg.updateBar.value() + 1)
        QgsExpressionContextUtils.setProjectVariable(
            currProject, 'ma_acknowledgements',
            self.dlg.maAcknowledgements.toPlainText())
        self.dlg.updateBar.setValue(self.dlg.updateBar.value() + 1)
        QgsExpressionContextUtils.setProjectVariable(
            currProject, 'ma_disclaimer', self.dlg.maDisclaimer.toPlainText())
        self.dlg.updateBar.setValue(self.dlg.updateBar.value() + 1)

        # Layout: update variables from dialog
        for layout in QgsProject.instance().layoutManager().printLayouts():
            # Select the current layout
            if layout.name() == self.dlg.layoutSelect.currentText():
                QgsMessageLog.logMessage(
                    'Info: value for ' + self.dlg.maSummary.toPlainText(),
                    'MapExport')
                # Map Number
                QgsExpressionContextUtils.setLayoutVariable(
                    layout, 'ma_map_number', self.dlg.maMapNumber.text())
                self.dlg.updateBar.setValue(self.dlg.updateBar.value() + 1)
                # Map Title
                QgsExpressionContextUtils.setLayoutVariable(
                    layout, 'ma_title', self.dlg.maTitle.text())
                self.dlg.updateBar.setValue(self.dlg.updateBar.value() + 1)
                # Date Created
                QgsExpressionContextUtils.setLayoutVariable(
                    layout, 'ma_created', self.dlg.maCreated.date())
                self.dlg.updateBar.setValue(self.dlg.updateBar.value() + 1)
                # Map Summary
                QgsExpressionContextUtils.setLayoutVariable(
                    layout, 'ma_summary', self.dlg.maSummary.toPlainText())
                self.dlg.updateBar.setValue(self.dlg.updateBar.value() + 1)
                # Data sources
                QgsExpressionContextUtils.setLayoutVariable(
                    layout, 'ma_datasource',
                    self.dlg.maDatasource.toPlainText())
                self.dlg.updateBar.setValue(self.dlg.updateBar.value() + 1)
                # Version
                QgsExpressionContextUtils.setLayoutVariable(
                    layout, 'ma_version', self.dlg.maVersion.value())
                self.dlg.updateBar.setValue(self.dlg.updateBar.value() + 1)
                # Status
                QgsExpressionContextUtils.setLayoutVariable(
                    layout, 'ma_status', self.dlg.maStatus.currentText())
                self.dlg.updateBar.setValue(self.dlg.updateBar.value() + 1)
                # Access
                QgsExpressionContextUtils.setLayoutVariable(
                    layout, 'ma_access', self.dlg.maAccess.currentText())
                self.dlg.updateBar.setValue(self.dlg.updateBar.value() + 1)
                # Language
                QgsExpressionContextUtils.setLayoutVariable(
                    layout, 'ma_language', self.dlg.maLanguage.currentText())
                self.dlg.updateBar.setValue(self.dlg.updateBar.value() + 1)

        i = i + 1
        QApplication.restoreOverrideCursor()

        # show an ending message
        # in case of abortion
        if self.arret:
            self.iface.messageBar().pushMessage(
                self.tr(u'Operation interrupted : '),
                self.tr(u'Maps on {} have been '\
                    'exported to "{}" before cancelling. '\
                    'Some files may be incomplete.'
                    ).format(i,folder),
                level = Qgis.Info, duration = 10
                )
        # or when export ended completely
        else:
            self.iface.messageBar().pushMessage(
                self.tr(u'Operation finished : '),
                self.tr(u'The metadata has been '\
                    'updated.'
                    ).format(title),
                level = Qgis.Info, duration = 50
                )
Exemplo n.º 31
0
    def populateMetadataItems(self, m, layout):
        """Get the current value of metadata items from the project or layout variable, and populate the Edit Metadata dialog
        See *updateVars* to populate variable values from th Edit Metadata UI
        """
        currProject = QgsProject.instance()
        # Check that all the variables exist, and if they don't, create them and give them a default value where appropriate
        with open(os.path.join(self.plugin_dir, "input/metadata_items.csv"),
                  'r') as metadata_file:
            reader = csv.reader(metadata_file, delimiter=',')
            metadata_list = list(reader)
        for x in metadata_list:
            ma_variable = str(x[0])
            elem_name = str(x[1])
            elem_name = elem_name.strip()
            ma_level = str(x[2])
            default_value = str(x[3])
            ma_level = ma_level.strip()
            # If project level variables don't exist, create them and populate with the default value
            if (ma_level == 'project'):
                if str(
                        QgsExpressionContextUtils.projectScope(
                            currProject).variable(ma_variable)) == 'None':
                    QgsExpressionContextUtils.setProjectVariable(
                        currProject, ma_variable, default_value)

        # Populate comboboxes
        # Populate values of Status combobox
        self.dlg.maStatus.addItem('New')
        self.dlg.maStatus.addItem('Correction')
        self.dlg.maStatus.addItem('Update')

        # Populate values of Access combobox
        self.dlg.maAccess.addItem('Public')
        self.dlg.maAccess.addItem('MapAction')
        self.dlg.maAccess.addItem('Selected partners')

        # Populate values of Language combobox
        self.dlg.maLanguage.addItem('English')
        self.dlg.maLanguage.addItem('French')
        self.dlg.maLanguage.addItem('Spanish')

        # Populate the Edit Metadata dialog with current values from variables
        for x in m:
            ma_variable = str(x[0])
            elem_name = str(x[1])
            elem_name = elem_name.strip()
            ma_level = str(x[2])
            ma_level = ma_level.strip()
            default_value = str(x[3])
            proj_crs = QgsProject.instance().crs()
            if (ma_level == 'project'):
                # Project: get current value for each variable from project and populate field
                if ma_variable == 'ma_country':
                    self.dlg.maCountry.setText(
                        str(
                            QgsExpressionContextUtils.projectScope(
                                currProject).variable(ma_variable)))
                elif ma_variable == 'ma_crs':
                    self.dlg.maCrs.setText(
                        str(
                            QgsCoordinateReferenceSystem(
                                proj_crs).description()))
                elif ma_variable == 'ma_glide_number':
                    self.dlg.maGlide.setText(
                        str(
                            QgsExpressionContextUtils.projectScope(
                                currProject).variable(ma_variable)))
                elif ma_variable == 'ma_organisation':
                    self.dlg.maOrganisation.setText(
                        str(
                            QgsExpressionContextUtils.projectScope(
                                currProject).variable(ma_variable)))
                elif ma_variable == 'ma_opid':
                    self.dlg.maOperationID.setText(
                        str(
                            QgsExpressionContextUtils.projectScope(
                                currProject).variable(ma_variable)))
                elif ma_variable == 'ma_sourceorg':
                    self.dlg.maSourceOrg.setText(
                        str(
                            QgsExpressionContextUtils.projectScope(
                                currProject).variable(ma_variable)))
                elif ma_variable == 'ma_acknowledgements':
                    self.dlg.maAcknowledgements.setText(
                        str(
                            QgsExpressionContextUtils.projectScope(
                                currProject).variable(ma_variable)))
                elif ma_variable == 'ma_disclaimer':
                    self.dlg.maDisclaimer.setText(
                        str(
                            QgsExpressionContextUtils.projectScope(
                                currProject).variable(ma_variable)))

            # Layout: Get the current value of the variable if it exists and populate the field
            elif (ma_level == 'layout'):
                for layout in QgsProject.instance().layoutManager(
                ).printLayouts():
                    # If the variable doesn't exist, create it
                    if layout.name() == self.dlg.layoutSelect.currentText():
                        if str(
                                QgsExpressionContextUtils.layoutScope(
                                    layout).variable(ma_variable)) == 'None':
                            QgsExpressionContextUtils.setLayoutVariable(
                                layout, ma_variable, default_value)
                        elif ma_variable == 'ma_map_number':
                            self.dlg.maMapNumber.setText(
                                str(
                                    QgsExpressionContextUtils.layoutScope(
                                        layout).variable(ma_variable)))
                        elif ma_variable == 'ma_summary':
                            self.dlg.maSummary.setText(
                                str(
                                    QgsExpressionContextUtils.layoutScope(
                                        layout).variable(ma_variable)))
                        elif ma_variable == 'ma_datasource':
                            self.dlg.maDatasource.setText(
                                str(
                                    QgsExpressionContextUtils.layoutScope(
                                        layout).variable(ma_variable)))
                        elif ma_variable == 'ma_title':
                            self.dlg.maTitle.setText(
                                str(
                                    QgsExpressionContextUtils.layoutScope(
                                        layout).variable(ma_variable)))
                        elif ma_variable == 'ma_version':
                            self.dlg.maVersion.setValue(
                                int(
                                    QgsExpressionContextUtils.layoutScope(
                                        layout).variable(ma_variable)))
                        elif ma_variable == 'ma_status':
                            self.dlg.maStatus.setCurrentText(
                                str(
                                    QgsExpressionContextUtils.layoutScope(
                                        layout).variable(ma_variable)))
                        elif ma_variable == 'ma_access':
                            self.dlg.maAccess.setCurrentText(
                                str(
                                    QgsExpressionContextUtils.layoutScope(
                                        layout).variable(ma_variable)))
                        elif ma_variable == 'ma_language':
                            self.dlg.maLanguage.setCurrentText(
                                str(
                                    QgsExpressionContextUtils.layoutScope(
                                        layout).variable(ma_variable)))
            else:
                # ACTION: update or remove this message
                QgsMessageLog.logMessage('Warning: level ' + str(ma_level),
                                         'MapExport')