コード例 #1
0
    def selectExtent(self):
        popupmenu = QMenu()
        useCanvasExtentAction = QAction(
            QCoreApplication.translate("ExtentSelectionPanel", 'Use Canvas Extent'),
            self.btnSelect)
        useLayerExtentAction = QAction(
            QCoreApplication.translate("ExtentSelectionPanel", 'Use Layer Extent…'),
            self.btnSelect)
        selectOnCanvasAction = QAction(
            self.tr('Select Extent on Canvas'), self.btnSelect)

        popupmenu.addAction(useCanvasExtentAction)
        popupmenu.addAction(selectOnCanvasAction)
        popupmenu.addSeparator()
        popupmenu.addAction(useLayerExtentAction)

        selectOnCanvasAction.triggered.connect(self.selectOnCanvas)
        useLayerExtentAction.triggered.connect(self.useLayerExtent)
        useCanvasExtentAction.triggered.connect(self.useCanvasExtent)

        if self.param.flags() & QgsProcessingParameterDefinition.FlagOptional:
            useMincoveringExtentAction = QAction(
                self.tr('Use Min Covering Extent from Input Layers'),
                self.btnSelect)
            useMincoveringExtentAction.triggered.connect(
                self.useMinCoveringExtent)
            popupmenu.addAction(useMincoveringExtentAction)

        popupmenu.exec_(QCursor.pos())
コード例 #2
0
 def showSnippets(self, evt):
     popupmenu = QMenu()
     for name, snippet in list(self.snippets.items()):
         action = QAction(self.tr(name), self.btnSnippets)
         action.triggered[()].connect(lambda snippet=snippet: self.editor.insert(snippet))
         popupmenu.addAction(action)
     popupmenu.exec_(QCursor.pos())
コード例 #3
0
 def showPopupMenu(self):
     popup_menu = QMenu()
     select_all_action = QAction(self.tr('Select All'), popup_menu)
     select_all_action.triggered.connect(self.selectAll)
     clear_all_action = QAction(self.tr('Clear Selection'), popup_menu)
     clear_all_action.triggered.connect(self.deselectAll)
     popup_menu.addAction(select_all_action)
     popup_menu.addAction(clear_all_action)
     popup_menu.exec_(QCursor.pos())
コード例 #4
0
ファイル: maps_printer.py プロジェクト: DelazJ/MapsPrinter
    def context_menu(self):
        """Add context menu fonctions."""

        menu = QMenu(self.dlg.layoutList)
        menu.addAction(self.tr(u'Check...'), self.actionCheckLayout)
        menu.addAction(self.tr(u'Uncheck...'), self.actionUncheckLayout)
        menu.addSeparator()
        menu.addAction(self.tr(u'Show...'), self.actionShowLayout)
        menu.addAction(self.tr(u'Close...'), self.actionHideLayout)
        menu.exec_(QCursor.pos())
コード例 #5
0
    def showPopupMenu(self):
        popupmenu = QMenu()

        if not (isinstance(self.param, ParameterMultipleInput) and self.param.datatype == dataobjects.TYPE_FILE):
            selectLayerAction = QAction(self.tr("Select from open layers"), self.pushButton)
            selectLayerAction.triggered.connect(self.showLayerSelectionDialog)
            popupmenu.addAction(selectLayerAction)

        selectFileAction = QAction(self.tr("Select from filesystem"), self.pushButton)
        selectFileAction.triggered.connect(self.showFileSelectionDialog)
        popupmenu.addAction(selectFileAction)

        popupmenu.exec_(QCursor.pos())
コード例 #6
0
    def selectOutput(self):
        if isinstance(self.parameter, QgsProcessingParameterFolderDestination):
            self.selectDirectory()
        else:
            popupMenu = QMenu()

            if not self.default_selection:
                if self.parameter.flags() & QgsProcessingParameterDefinition.FlagOptional:
                    actionSkipOutput = QAction(
                        self.tr('Skip Output'), self.btnSelect)
                    actionSkipOutput.triggered.connect(self.skipOutput)
                    popupMenu.addAction(actionSkipOutput)

                if isinstance(self.parameter, QgsProcessingParameterFeatureSink) \
                        and self.parameter.supportsNonFileBasedOutput():
                    # use memory layers for temporary layers if supported
                    actionSaveToTemp = QAction(
                        self.tr('Create Temporary Layer'), self.btnSelect)
                else:
                    actionSaveToTemp = QAction(
                        self.tr('Save to a Temporary File'), self.btnSelect)
                actionSaveToTemp.triggered.connect(self.saveToTemporary)
                popupMenu.addAction(actionSaveToTemp)

            actionSaveToFile = QAction(
                QCoreApplication.translate('DestinationSelectionPanel', 'Save to File…'), self.btnSelect)
            actionSaveToFile.triggered.connect(self.selectFile)
            popupMenu.addAction(actionSaveToFile)

            if isinstance(self.parameter, QgsProcessingParameterFeatureSink) \
                    and self.parameter.supportsNonFileBasedOutput():
                actionSaveToGpkg = QAction(
                    QCoreApplication.translate('DestinationSelectionPanel', 'Save to GeoPackage…'), self.btnSelect)
                actionSaveToGpkg.triggered.connect(self.saveToGeopackage)
                popupMenu.addAction(actionSaveToGpkg)
                actionSaveToPostGIS = QAction(
                    QCoreApplication.translate('DestinationSelectionPanel', 'Save to PostGIS Table…'), self.btnSelect)
                actionSaveToPostGIS.triggered.connect(self.saveToPostGIS)
                settings = QgsSettings()
                settings.beginGroup('/PostgreSQL/connections/')
                names = settings.childGroups()
                settings.endGroup()
                actionSaveToPostGIS.setEnabled(bool(names))
                popupMenu.addAction(actionSaveToPostGIS)

            actionSetEncoding = QAction(
                QCoreApplication.translate('DestinationSelectionPanel', 'Change File Encoding ({})…').format(self.encoding), self.btnSelect)
            actionSetEncoding.triggered.connect(self.selectEncoding)
            popupMenu.addAction(actionSetEncoding)

            popupMenu.exec_(QCursor.pos())
コード例 #7
0
    def selectOutput(self):
        if isinstance(self.parameter, QgsProcessingParameterFolderDestination):
            self.selectDirectory()
        else:
            popupMenu = QMenu()

            if self.parameter.flags() & QgsProcessingParameterDefinition.FlagOptional:
                actionSkipOutput = QAction(
                    self.tr('Skip output'), self.btnSelect)
                actionSkipOutput.triggered.connect(self.skipOutput)
                popupMenu.addAction(actionSkipOutput)

            if isinstance(self.parameter, QgsProcessingParameterFeatureSink) \
                    and self.alg.provider().supportsNonFileBasedOutput():
                # use memory layers for temporary layers if supported
                actionSaveToTemp = QAction(
                    self.tr('Create temporary layer'), self.btnSelect)
            else:
                actionSaveToTemp = QAction(
                    self.tr('Save to a temporary file'), self.btnSelect)
            actionSaveToTemp.triggered.connect(self.saveToTemporary)
            popupMenu.addAction(actionSaveToTemp)

            actionSaveToFile = QAction(
                self.tr('Save to file...'), self.btnSelect)
            actionSaveToFile.triggered.connect(self.selectFile)
            popupMenu.addAction(actionSaveToFile)

            actionShowExpressionsBuilder = QAction(
                self.tr('Use expression...'), self.btnSelect)
            actionShowExpressionsBuilder.triggered.connect(self.showExpressionsBuilder)
            popupMenu.addAction(actionShowExpressionsBuilder)

            if isinstance(self.parameter, QgsProcessingParameterFeatureSink) \
                    and self.alg.provider().supportsNonFileBasedOutput():
                actionSaveToSpatialite = QAction(
                    self.tr('Save to SpatiaLite table...'), self.btnSelect)
                actionSaveToSpatialite.triggered.connect(self.saveToSpatialite)
                popupMenu.addAction(actionSaveToSpatialite)
                actionSaveToPostGIS = QAction(
                    self.tr('Save to PostGIS table...'), self.btnSelect)
                actionSaveToPostGIS.triggered.connect(self.saveToPostGIS)
                settings = QgsSettings()
                settings.beginGroup('/PostgreSQL/connections/')
                names = settings.childGroups()
                settings.endGroup()
                actionSaveToPostGIS.setEnabled(bool(names))
                popupMenu.addAction(actionSaveToPostGIS)

            popupMenu.exec_(QCursor.pos())
コード例 #8
0
    def selectExtent(self):
        popupmenu = QMenu()
        useLayerExtentAction = QAction(
            self.tr('Use layer/canvas extent'), self.btnSelect)
        selectOnCanvasAction = QAction(
            self.tr('Select extent on canvas'), self.btnSelect)

        popupmenu.addAction(useLayerExtentAction)
        popupmenu.addAction(selectOnCanvasAction)

        selectOnCanvasAction.triggered.connect(self.selectOnCanvas)
        useLayerExtentAction.triggered.connect(self.useLayerExtent)

        popupmenu.exec_(QCursor.pos())
コード例 #9
0
ファイル: BatchInputSelectionPanel.py プロジェクト: qgis/QGIS
    def showPopupMenu(self):
        popupmenu = QMenu()

        if (isinstance(self.param, QgsProcessingParameterMultipleLayers) and
                self.param.layerType() != QgsProcessing.TypeFile):
            selectLayerAction = QAction(self.tr('Select from Open Layers…'), self.pushButton)
            selectLayerAction.triggered.connect(self.showLayerSelectionDialog)
            popupmenu.addAction(selectLayerAction)

        selectFileAction = QAction(self.tr('Select from File System…'), self.pushButton)
        selectFileAction.triggered.connect(self.showFileSelectionDialog)
        popupmenu.addAction(selectFileAction)

        popupmenu.exec_(QCursor.pos())
コード例 #10
0
    def showPopupMenu(self):
        popupmenu = QMenu()

        if not (isinstance(self.param, QgsProcessingParameterMultipleLayers) and
                self.param.layerType == dataobjects.TYPE_FILE):
            selectLayerAction = QAction(
                QCoreApplication.translate('BatchInputSelectionPanel', 'Select from Open Layers…'), self.pushButton)
            selectLayerAction.triggered.connect(self.showLayerSelectionDialog)
            popupmenu.addAction(selectLayerAction)

        selectFileAction = QAction(
            QCoreApplication.translate('BatchInputSelectionPanel', 'Select from File System…'), self.pushButton)
        selectFileAction.triggered.connect(self.showFileSelectionDialog)
        popupmenu.addAction(selectFileAction)

        popupmenu.exec_(QCursor.pos())
コード例 #11
0
ファイル: ExtentSelectionPanel.py プロジェクト: Zakui/QGIS
    def selectExtent(self):
        popupmenu = QMenu()
        useLayerExtentAction = QAction(self.tr("Use layer/canvas extent"), self.btnSelect)
        selectOnCanvasAction = QAction(self.tr("Select extent on canvas"), self.btnSelect)

        popupmenu.addAction(useLayerExtentAction)
        popupmenu.addAction(selectOnCanvasAction)

        selectOnCanvasAction.triggered.connect(self.selectOnCanvas)
        useLayerExtentAction.triggered.connect(self.useLayerExtent)

        if self.canUseAutoExtent():
            useMincoveringExtentAction = QAction(self.tr("Use min covering extent from input layers"), self.btnSelect)
            useMincoveringExtentAction.triggered.connect(self.useMinCoveringExtent)
            popupmenu.addAction(useMincoveringExtentAction)

        popupmenu.exec_(QCursor.pos())
コード例 #12
0
    def selectOutput(self):
        if isinstance(self.output, OutputDirectory):
            self.selectDirectory()
        else:
            popupMenu = QMenu()

            if isinstance(self.output, OutputVector) \
                    and self.alg.provider.supportsNonFileBasedOutput():
                # use memory layers for temporary layers if supported
                actionSaveToTemp = QAction(
                    self.tr('Create temporary layer'), self.btnSelect)
            else:
                actionSaveToTemp = QAction(
                    self.tr('Save to a temporary file'), self.btnSelect)
            actionSaveToTemp.triggered.connect(self.saveToTemporary)
            popupMenu.addAction(actionSaveToTemp)

            actionSaveToFile = QAction(
                self.tr('Save to file...'), self.btnSelect)
            actionSaveToFile.triggered.connect(self.selectFile)
            popupMenu.addAction(actionSaveToFile)

            actionShowExpressionsBuilder = QAction(
                self.tr('Use expression...'), self.btnSelect)
            actionShowExpressionsBuilder.triggered.connect(self.showExpressionsBuilder)
            popupMenu.addAction(actionShowExpressionsBuilder)

            if isinstance(self.output, OutputVector) \
                    and self.alg.provider.supportsNonFileBasedOutput():
                actionSaveToSpatialite = QAction(
                    self.tr('Save to Spatialite table...'), self.btnSelect)
                actionSaveToSpatialite.triggered.connect(self.saveToSpatialite)
                popupMenu.addAction(actionSaveToSpatialite)
                actionSaveToPostGIS = QAction(
                    self.tr('Save to PostGIS table...'), self.btnSelect)
                actionSaveToPostGIS.triggered.connect(self.saveToPostGIS)
                settings = QSettings()
                settings.beginGroup('/PostgreSQL/connections/')
                names = settings.childGroups()
                settings.endGroup()
                actionSaveToPostGIS.setEnabled(bool(names))
                popupMenu.addAction(actionSaveToPostGIS)

            popupMenu.exec_(QCursor.pos())
コード例 #13
0
ファイル: maindialog.py プロジェクト: zgustaf/QGIS
    def _get_csw(self):
        """convenience function to init owslib.csw.CatalogueServiceWeb"""

        # connect to the server
        try:
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            self.catalog = CatalogueServiceWeb(self.catalog_url,
                                               timeout=self.timeout,
                                               username=self.catalog_username,
                                               password=self.catalog_password)
            return True
        except ExceptionReport as err:
            msg = self.tr('Error connecting to service: {0}').format(err)
        except ValueError as err:
            msg = self.tr('Value Error: {0}').format(err)
        except Exception as err:
            msg = self.tr('Unknown Error: {0}').format(err)

        QApplication.restoreOverrideCursor()
        QMessageBox.warning(self, self.tr('CSW Connection error'), msg)
        return False
コード例 #14
0
    def accept(self):
        self.inFiles = None
        if self.batchCheck.isChecked():
            self.inFiles = Utils.getRasterFiles(self.inSelector.filename(), self.recurseCheck.isChecked())
        else:
            self.inFiles = [self.inSelector.filename()]

        self.progressBar.setRange(0, len(self.inFiles))

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        self.okButton.setEnabled(False)

        self.extractor = ExtractThread(self.inFiles, self.prjCheck.isChecked())
        self.extractor.fileProcessed.connect(self.updateProgress)
        self.extractor.processFinished.connect(self.processingFinished)
        self.extractor.processInterrupted.connect(self.processingInterrupted)

        self.buttonBox.rejected.disconnect(self.reject)
        self.buttonBox.rejected.connect(self.stopProcessing)

        self.extractor.start()
コード例 #15
0
 def setServerDb(self, serverAbstractDb):
     self.serverAbstractDb = serverAbstractDb
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     try:
         if self.serverAbstractDb:
             dbList = self.serverAbstractDb.getEDGVDbsFromServer(
                 parentWidget=self.parent, getDatabaseVersions=False)
             dbList.sort()
             self.clear()
             self.connectionSelectorComboBox.addItem(
                 self.tr('Select Database'))
             self.addItems(dbList)
         else:
             self.clear()
             self.abstractDb = None
             QApplication.restoreOverrideCursor()
             return
     except Exception as e:
         QApplication.restoreOverrideCursor()
         QMessageBox.critical(self, self.tr('Critical!'), ':'.join(e.args))
     QApplication.restoreOverrideCursor()
コード例 #16
0
    def show_metadata(self):
        """show record metadata"""

        if not self.treeRecords.selectedItems():
            return

        item = self.treeRecords.currentItem()
        if not item:
            return

        identifier = get_item_data(item, 'identifier')

        try:
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            cat = CatalogueServiceWeb(self.catalog_url, timeout=self.timeout)
            cat.getrecordbyid([self.catalog.records[identifier].identifier])
        except ExceptionReport as err:
            QApplication.restoreOverrideCursor()
            QMessageBox.warning(self, self.tr('GetRecords error'),
                                self.tr('Error getting response: %s') % err)
            return
        except KeyError as err:
            QMessageBox.warning(self, self.tr('Record parsing error'),
                                'Unable to locate record identifier')
            QApplication.restoreOverrideCursor()
            return

        QApplication.restoreOverrideCursor()

        record = cat.records[identifier]
        record.xml_url = cat.request

        crd = RecordDialog()
        metadata = render_template('en', self.context, record,
                                   'record_metadata_dc.html')

        style = QgsApplication.reportStyleSheet()
        crd.textMetadata.document().setDefaultStyleSheet(style)
        crd.textMetadata.setHtml(metadata)
        crd.exec_()
コード例 #17
0
    def draw(self, element: Union[Param, Seperator, Title, QLayoutItem]):
        '''
        add an element (parameter or style element) to the dialog and draw it

        Parameters
        ----------
        element : object
            parameter or style element to draw
        '''
        self.inputs = []
        # put param objects into grid, else added to the base layout
        if isinstance(element, Param):
            if not self._grid:
                self._grid = QGridLayout()
                self.layout.addLayout(self._grid)
            element.draw(self._grid, edit=True)
            if element.help_text:
                help_button = QPushButton('?')
                help_button.setMaximumWidth(20)
                help_button.setToolTip('Hilfe')
                help_button.setCursor(QCursor(Qt.PointingHandCursor))
                help_button.setFlat(True)
                font = help_button.font()
                font.setUnderline(True)
                font.setBold(True)
                help_button.setFont(font)
                help_button.clicked.connect(
                    lambda: self.show_help(element.help_text, expand=True))
                element.row.addWidget(help_button)
            if element.input:
                element.input.focus.connect(
                    lambda: self.show_help(element.help_text))
                self.inputs.append(element.input)
        else:
            self._grid = None
            if isinstance(element, QLayoutItem):
                self.layout.addItem(element)
            else:
                element.draw(self.layout)
        self.adjustSize()
コード例 #18
0
    def selectExtent(self):
        popupmenu = QMenu()
        useLayerExtentAction = QAction(
            self.tr('Use layer/canvas extent'), self.btnSelect)
        selectOnCanvasAction = QAction(
            self.tr('Select extent on canvas'), self.btnSelect)

        popupmenu.addAction(useLayerExtentAction)
        popupmenu.addAction(selectOnCanvasAction)

        selectOnCanvasAction.triggered.connect(self.selectOnCanvas)
        useLayerExtentAction.triggered.connect(self.useLayerExtent)

        if self.param.optional:
            useMincoveringExtentAction = QAction(
                self.tr('Use min covering extent from input layers'),
                self.btnSelect)
            useMincoveringExtentAction.triggered.connect(
                self.useMinCoveringExtent)
            popupmenu.addAction(useMincoveringExtentAction)

        popupmenu.exec_(QCursor.pos())
コード例 #19
0
    def onPointClicked(self, point):
        layer = self.iface.activeLayer()
        if not layer or layer.type(
        ) != QgsMapLayer.VectorLayer or layer.geometryType(
        ) != QgsWkbTypes.PointGeometry:
            QMessageBox.information(self.iface.mainWindow(),
                                    "PS Time Series Viewer",
                                    "Select a vector layer and try again.")
            return

        # set the waiting cursor
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        try:
            dlg = self._onPointClicked(layer, point)
        finally:
            # restore the cursor
            QApplication.restoreOverrideCursor()

        if dlg:
            dlg.exec_()

        self.run()
コード例 #20
0
    def selectExtent(self):
        popupmenu = QMenu()
        useLayerExtentAction = QAction(self.tr('Use layer/canvas extent'),
                                       self.btnSelect)
        selectOnCanvasAction = QAction(self.tr('Select extent on canvas'),
                                       self.btnSelect)

        popupmenu.addAction(useLayerExtentAction)
        popupmenu.addAction(selectOnCanvasAction)

        selectOnCanvasAction.triggered.connect(self.selectOnCanvas)
        useLayerExtentAction.triggered.connect(self.useLayerExtent)

        if self.param.flags() & QgsProcessingParameterDefinition.FlagOptional:
            useMincoveringExtentAction = QAction(
                self.tr('Use min covering extent from input layers'),
                self.btnSelect)
            useMincoveringExtentAction.triggered.connect(
                self.useMinCoveringExtent)
            popupmenu.addAction(useMincoveringExtentAction)

        popupmenu.exec_(QCursor.pos())
コード例 #21
0
 def overlay(self):
     measure = self.dlg.fcbMeasure.layer()
     area = self.dlg.fcbArea.layer()
     params = {
         'INPUT': measure,
         'OVERLAY': area,
         'OUTPUT': "memory:land_water",
         'INTERSECTION': "memory:land_water"
     }
     QgsApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     self.iface.messageBar().pushMessage("Atitude correction",
                                         "Running overlay",
                                         level=Qgis.Info,
                                         duration=3)
     output = processing.runAndLoadResults("qgis:intersection", params)
     QgsApplication.restoreOverrideCursor()
     self.iface.messageBar().pushMessage("Atitude correction",
                                         "Overlay finished",
                                         level=Qgis.Success,
                                         duration=3)
     self.overlaylayer = QgsProject.instance().mapLayer(output['OUTPUT'])
     self.dlg.lcbOverlay.setLayer(self.overlaylayer)
コード例 #22
0
ファイル: dlg_sql_window.py プロジェクト: rui88/QGIS
    def executeSql(self):

        sql = self._getSqlQuery()
        if sql == "":
            return

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        # delete the old model
        old_model = self.viewResult.model()
        self.viewResult.setModel(None)
        if old_model:
            old_model.deleteLater()

        cols = []
        quotedCols = []

        try:
            # set the new model
            model = self.db.sqlResultModel(sql, self)
            self.viewResult.setModel(model)
            self.lblResult.setText(
                self.tr("%d rows, %.1f seconds") %
                (model.affectedRows(), model.secs()))
            cols = self.viewResult.model().columnNames()
            for col in cols:
                quotedCols.append(self.db.connector.quoteId(col))

        except BaseError as e:
            QApplication.restoreOverrideCursor()
            DlgDbError.showError(e, self)
            self.uniqueModel.clear()
            self.geomCombo.clear()
            return

        self.setColumnCombos(cols, quotedCols)

        self.update()
        QApplication.restoreOverrideCursor()
コード例 #23
0
ファイル: dlg_sql_layer_window.py プロジェクト: mbrukman/QGIS
    def updateSqlLayer(self):
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        try:
            layer = self._getSqlLayer(self.filter)
            if layer == None:
                return

            #self.layer.dataProvider().setDataSourceUri(layer.dataProvider().dataSourceUri())
            #self.layer.dataProvider().reloadData()
            XMLDocument = QDomDocument("style")
            XMLMapLayers = XMLDocument.createElement("maplayers")
            XMLMapLayer = XMLDocument.createElement("maplayer")
            self.layer.writeLayerXML(XMLMapLayer, XMLDocument)
            XMLMapLayer.firstChildElement("datasource").firstChild().setNodeValue(layer.source())
            XMLMapLayers.appendChild(XMLMapLayer)
            XMLDocument.appendChild(XMLMapLayers)
            self.layer.readLayerXML(XMLMapLayer)
            self.layer.reload()
            self.iface.actionDraw().trigger()
            self.iface.mapCanvas().refresh()
        finally:
            QApplication.restoreOverrideCursor()
コード例 #24
0
    def on_okButton_clicked(self):
        """
        Creates the actual frame.
        """
        if not self.widget.dbLoaded:
            QMessageBox.warning(self, self.tr("Warning!"),
                                self.tr('Please, select a database first.'))
            return

        if not self.validateMI():
            QMessageBox.warning(self, self.tr("Warning!"),
                                self.tr('Map name index not valid!'))
            return
        try:
            QtWidgets.QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            layer = self.loadFrameLayer()
            self.runCreateFrameAndAddFeaturesToFrame(layer)
            QtWidgets.QApplication.restoreOverrideCursor()
        except Exception as e:
            QtWidgets.QApplication.restoreOverrideCursor()
            raise e
        self.done(1)
コード例 #25
0
ファイル: ConfigDialog.py プロジェクト: wongjimsan/QGIS
 def accept(self):
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     qsettings = QSettings()
     for setting in list(self.items.keys()):
         if setting.group != menusSettingsGroup or self.saveMenus:
             if isinstance(setting.value, bool):
                 setting.setValue(
                     self.items[setting].checkState() == Qt.Checked)
             else:
                 try:
                     setting.setValue(str(self.items[setting].text()))
                 except ValueError as e:
                     QMessageBox.warning(
                         self, self.tr('Wrong value'),
                         self.tr('Wrong value for parameter "%s":\n\n%s' %
                                 (setting.description, str(e))))
                     return
             setting.save(qsettings)
     Processing.updateAlgsList()
     settingsWatcher.settingsChanged.emit()
     QApplication.restoreOverrideCursor()
     QDialog.accept(self)
コード例 #26
0
ファイル: ExtentSelectionPanel.py プロジェクト: kermeat/QGIS
    def selectExtent(self):
        popupmenu = QMenu()
        useLayerExtentAction = QAction(
            self.tr('Use layer/canvas extent'), self.btnSelect)
        selectOnCanvasAction = QAction(
            self.tr('Select extent on canvas'), self.btnSelect)

        popupmenu.addAction(useLayerExtentAction)
        popupmenu.addAction(selectOnCanvasAction)

        selectOnCanvasAction.triggered.connect(self.selectOnCanvas)
        useLayerExtentAction.triggered.connect(self.useLayerExtent)

        if self.canUseAutoExtent():
            useMincoveringExtentAction = QAction(
                self.tr('Use min covering extent from input layers'),
                self.btnSelect)
            useMincoveringExtentAction.triggered.connect(
                self.useMinCoveringExtent)
            popupmenu.addAction(useMincoveringExtentAction)

        popupmenu.exec_(QCursor.pos())
コード例 #27
0
 def on_applyPushButton_clicked(self):
     permissionsToGrant = [i for i in self.profileCustomSelector.toLs if i not in self.grantedProfileList]
     profilesToRevoke = [i for i in self.profileCustomSelector.fromLs if i not in self.notGrantedProfileList]
     #grant operation
     header = self.tr('Grant / Revoke operation complete: ')
     successList = []
     errorDict = dict()
     QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
     for profileName in permissionsToGrant:
         try:
             self.permissionManager.grantPermission(self.dbName, profileName, self.edgvVersion, self.userName) #TODO: add error treatment
             successList.append(profileName)
         except Exception as e:
             errorDict[profileName] = str(e.args[0])
     for profileName in profilesToRevoke:
         try:
             self.permissionManager.revokePermission(self.dbName, profileName, self.userName) #TODO: add error treatment
             successList.append(profileName)
         except Exception as e:
             errorDict[profileName] = ':'.join(e.args)
     QApplication.restoreOverrideCursor()
     self.outputMessage(header, successList, errorDict)
     self.close()
コード例 #28
0
 def canvasMoveEvent(self, e):
     """
     Deals with mouse move event to update the rubber band position in the canvas
     """
     ctrlIsHeld = QApplication.keyboardModifiers() == Qt2.ControlModifier
     if e.button() != None and not ctrlIsHeld:
         if self.rotate:
             # change rotate status
             self.rotate = False
         QApplication.restoreOverrideCursor()
         self.endPoint = self.toMapCoordinates( e.pos() )
     elif e.button() != None and ctrlIsHeld \
         and self.geometryType == self.tr(u"Square"):
         # calculate angle between mouse and last rubberband centroid before holding control
         self.rotAngle = self.rotateRect(self.currentCentroid, e)
         if not self.rotate:
             # only override mouse if it is not overriden already
             QApplication.setOverrideCursor(QCursor(Qt2.BlankCursor))
             self.rotate = True
     if self.geometryType == self.tr(u"Circle"):
             self.showCircle(self.endPoint)
     elif self.geometryType == self.tr(u"Square"):
         self.showRect(self.endPoint, sqrt(self.param)/2, self.rotAngle)
コード例 #29
0
    def showPopupMenu(self):
        popupmenu = QMenu()

        isLayerParam = isinstance(self.param,
                                  (QgsProcessingParameterRasterLayer,
                                   QgsProcessingParameterVectorLayer,
                                   QgsProcessingParameterMeshLayer,
                                   QgsProcessingParameterFeatureSource))

        if isLayerParam or (
                isinstance(self.param, QgsProcessingParameterMultipleLayers)
                and self.param.layerType() != QgsProcessing.TypeFile):
            selectLayerAction = QAction(self.tr('Select from Open Layers…'),
                                        self.pushButton)
            selectLayerAction.triggered.connect(self.showLayerSelectionDialog)
            popupmenu.addAction(selectLayerAction)

        selectFileAction = QAction(self.tr('Select from File System…'),
                                   self.pushButton)
        selectFileAction.triggered.connect(self.showFileSelectionDialog)
        popupmenu.addAction(selectFileAction)

        popupmenu.exec_(QCursor.pos())
コード例 #30
0
 def on_batchImportPushButton_clicked(self):
     """
     Imports all config files from a folder into dsgtools_admindb. It only works for a single type of config per time.
     """
     fd = QFileDialog()
     folder = fd.getExistingDirectory(
         caption=self.tr('Select a folder with json files: '))
     if folder == '':
         # QMessageBox.warning(self, self.tr('Warning!'), self.tr('Warning! Select a input folder!'))
         return
     try:
         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
         self.genericDbManager.batchImportSettings(folder)
         QApplication.restoreOverrideCursor()
         QMessageBox.information(
             self, self.tr('Success!'),
             self.widgetName + self.tr(' successfully imported.'))
     except Exception as e:
         QApplication.restoreOverrideCursor()
         QMessageBox.critical(
             self, self.tr('Error!'),
             self.tr('Error! Problem importing ') + self.widgetName + ': ' +
             ':'.join(e.args))
コード例 #31
0
 def __init__(self,
              ui_element: QWidget,
              canvas: QgsMapCanvas = None,
              tip: str = '',
              target_epsg: int = 25832,
              cursor: int = Qt.CrossCursor):
     '''
     Parameters
     ----------
     ui_element : QWidget
         clickable UI element, clicking it will activate/deactivate this
         tool
     canvas : QgsMapCanvas, optional
         the map canvas the tool will work on, defaults to the map canvas of
         the QGIS UI
     tip : str, optional
         tooltip text shown while hovering the map canvas, defaults to not
         showing a tooltip
     target_epsg : int, optional
         all geometries determined by map interactions will be transformed
         into the crs with given epsg code, defaults to 25832
     cursor : int, optional
         the appearance of the cursor when hovering the map canvas while tool
         is active, defaults to cross hair (Qt.CrossCursor)
     '''
     self.cursor = QCursor(cursor)
     self.ui_element = ui_element
     self.canvas = canvas or utils.iface.mapCanvas()
     # workaround: .clicked.connect(self.toggle) works only occasionally
     # reason unknown
     self.ui_element.clicked.connect(
         lambda checked: self.set_active(checked))
     self.tip = tip
     if tip:
         self.map_timer = QTimer(self.canvas)
         self.map_timer.timeout.connect(self.show_tip)
     self.target_crs = QgsCoordinateReferenceSystem(target_epsg)
コード例 #32
0
 def __init__(self, parent: QObject = None,
              title: str = 'Parameter einstellen',
              help_text: str = None, help_expanded: bool = True):
     '''
     Parameters
     ----------
     parent : QObject, optional
         parent object of dialog
     title : str, optional
         title of the parameter dialog, defaults to 'Parameter einstellen'
     help_text : str, optional
         the general help displayed in the dialog, defaults to no help text
     help_expanded : bool, optional
         whether the help section is expanded or collapsed initially,
         defaults to expanded
     '''
     super().__init__(modal=True, parent=parent,
                      ui_file='parameter_dialog.ui',
                      title=title)
     self.layout = self.base_layout
     self.help_widget.setVisible(help_expanded)
     if help_text is None:
         self.details_button.setVisible(False)
     else:
         self.back_button.clicked.connect(
             lambda: self.show_help(help_text, hide_back=True, expand=True))
         self.show_help(help_text, hide_back=True)
     def toggle(checked):
         if checked:
             self.details_button.setText('Hilfe ausblenden <<')
         if not checked:
             self.adjustSize()
             self.details_button.setText('Hilfe anzeigen >>')
     self.details_button.toggled.connect(toggle)
     self.details_button.setChecked(help_expanded)
     self.back_button.setCursor(QCursor(Qt.PointingHandCursor))
     self._grid = None
コード例 #33
0
 def on_updatePropertyPushButton_clicked(self):
     """
     Updates property.
     1. Get propertyName
     2. Get propertyDict
     3. Instantiate config interface and get new dict
     4. Update property
     """
     propertyName = self.propertyComboBox.currentText()
     propertyDict = self.genericDbManager.getPropertyPerspectiveDict(
         viewType=DsgEnums.Property)
     if propertyName not in list(propertyDict.keys()):
         QMessageBox.critical(
             self, self.tr('Error!'),
             self.tr(
                 'Error! Problem getting {0}: Invalid property {1}').format(
                     self.widgetName, propertyName))
         return
     parameterDict = self.genericDbManager.getSetting(
         propertyName, self.genericDbManager.edgvVersion)
     setupDict = self.populateConfigInterface(self.abstractDb,
                                              jsonDict=parameterDict)
     if setupDict:
         try:
             QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
             self.genericDbManager.updateSetting(propertyName, setupDict)
             QApplication.restoreOverrideCursor()
             QMessageBox.information(
                 self, self.tr('Success!'),
                 self.tr('Success! Property {0} successfully updated.').
                 format(propertyName))
         except Exception as e:
             QApplication.restoreOverrideCursor()
             QMessageBox.critical(
                 self, self.tr('Error!'),
                 self.tr('Error! Problem updating {0}').format(
                     propertyName))
コード例 #34
0
ファイル: inspectiontool.py プロジェクト: transformaps/Roam
    def __init__(self, canvas, layerfrom, layerto, mapping, validation_method):
        """
            mapping - A dict of field - field mapping with values to
                            copy to the new layer
        """
        QgsMapTool.__init__(self, canvas)
        self.layerfrom = layerfrom
        self.layerto = layerto
        self.fields = mapping
        self.validation_method = validation_method
        self.band = QgsRubberBand(canvas, QgsWkbTypes.PolygonGeometry)
        self.band.setColor(QColor.fromRgb(255, 0, 0, 65))
        self.band.setWidth(5)

        self.cursor = QCursor(
            QPixmap([
                "16 16 3 1", "      c None", ".     c #FF0000",
                "+     c #FFFFFF", "                ", "       +.+      ",
                "      ++.++     ", "     +.....+    ", "    +.     .+   ",
                "   +.   .   .+  ", "  +.    .    .+ ", " ++.    .    .++",
                " ... ...+... ...", " ++.    .    .++", "  +.    .    .+ ",
                "   +.   .   .+  ", "   ++.     .+   ", "    ++.....+    ",
                "      ++.++     ", "       +.+      "
            ]))
コード例 #35
0
ファイル: ConfigDialog.py プロジェクト: zgustaf/QGIS
    def accept(self):
        qsettings = QgsSettings()
        for setting in list(self.items.keys()):
            if setting.group != menusSettingsGroup or self.saveMenus:
                if isinstance(setting.value, bool):
                    setting.setValue(
                        self.items[setting].checkState() == Qt.Checked)
                else:
                    try:
                        setting.setValue(str(self.items[setting].text()))
                    except ValueError as e:
                        QMessageBox.warning(
                            self, self.tr('Wrong value'),
                            self.tr('Wrong value for parameter "{0}":\n\n{1}').
                            format(setting.description, str(e)))
                        return
                setting.save(qsettings)

        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        for p in QgsApplication.processingRegistry().providers():
            p.refreshAlgorithms()
        QApplication.restoreOverrideCursor()

        settingsWatcher.settingsChanged.emit()
コード例 #36
0
    def getDatabasesFromServer(self):
        """
        Gets databases from server
        """
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
        try:
            if self.serverWidget.abstractDb:
                dbList = self.serverWidget.abstractDb.getEDGVDbsFromServer(
                    parentWidget=self)
                dbList.sort()
                self.comboBoxPostgis.clear()
                self.comboBoxPostgis.addItem(self.tr('Select Database'))
                for db, version in dbList:
                    self.comboBoxPostgis.addItem(db)

            else:
                self.setInitialState()
                QApplication.restoreOverrideCursor()
                return
        except Exception as e:
            QApplication.restoreOverrideCursor()
            QMessageBox.critical(self, self.tr('Critical!'), ':'.join(e.args))
            self.setInitialState()
        QApplication.restoreOverrideCursor()
コード例 #37
0
 def on_batchExportPushButton_clicked(self):
     """
     Exports all configs from dsgtools_admindb.
     """
     fd = QFileDialog()
     folder = fd.getExistingDirectory(
         caption=self.tr('Select a folder to output'))
     folder = folder[0] if isinstance(folder, tuple) else folder
     if folder == '':
         # QMessageBox.warning(self, self.tr('Warning!'), self.tr('Warning! Select a output!'))
         return
     try:
         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
         self.genericDbManager.batchExportSettings(folder)
         QApplication.restoreOverrideCursor()
         QMessageBox.information(
             self, self.tr('Success!'),
             self.widgetName + self.tr(' successfully exported.'))
     except Exception as e:
         QApplication.restoreOverrideCursor()
         QMessageBox.critical(
             self, self.tr('Error!'),
             self.tr('Error! Problem exporting ') + self.widgetName + ': ' +
             ':'.join(e.args))
コード例 #38
0
 def on_exportPushButton_clicked(self):
     """
     Export selected properties.
     """
     exportPropertyList = self.selectConfig()
     if exportPropertyList is None:
         # user cancelled
         return
     if exportPropertyList == []:
         QMessageBox.warning(
             self, self.tr('Warning!'),
             self.tr('Warning! Select a profile to export!'))
         return
     fd = QFileDialog()
     folder = fd.getExistingDirectory(
         caption=self.tr('Select a folder to output'))
     folder = folder[0] if isinstance(folder, tuple) else folder
     if folder == '':
         # QMessageBox.warning(self, self.tr('Warning!'), self.tr('Warning! Select a output!'))
         return
     edgvVersion = self.genericDbManager.edgvVersion
     try:
         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
         for exportProperty in exportPropertyList:
             self.genericDbManager.exportSetting(exportProperty,
                                                 edgvVersion, folder)
         QApplication.restoreOverrideCursor()
         QMessageBox.information(
             self, self.tr('Success!'),
             self.widgetName + self.tr(' successfully exported.'))
     except Exception as e:
         QApplication.restoreOverrideCursor()
         QMessageBox.critical(
             self, self.tr('Error!'),
             self.tr('Error! Problem exporting ') + self.widgetName + ': ' +
             ':'.join(e.args))
コード例 #39
0
ファイル: mapMarker.py プロジェクト: piMoll/SEILAPLAN
    def __init__(self, canvas):
        QgsMapTool.__init__(self, canvas)
        self.canvas = canvas

        # Cross hair when drawing profile line
        self.cursor = QCursor(Qt.CrossCursor)
        # Cross hair when creating new fixed poles in profile window
        self.poleCursor = None

        # Red line for profile drawing
        self.rubberband = QgsRubberBand(self.canvas)
        self.rubberband.setWidth(3)
        self.rubberband.setColor(QColor(PROFILE_COLOR))

        # Place markers only on profile line from survey data
        self.surveyDataMode = False

        # Coordinates of drawn line points
        self.linePoints = []
        # Drawn line geometry
        self.lineFeature = None
        # Point markers for poles
        self.markers = []
        # Transformation function to project map coordinates on to survey
        # profile
        self.transformFunc = None

        # Line for section marking (sections without poles)
        self.linePointsS = []
        self.lineFeatureS = []

        # Temporary save double clicks
        self.dblclktemp = None

        # Backup the last active Tool before the profile tool became active
        self.savedTool = self.canvas.mapTool()
コード例 #40
0
ファイル: ExtentSelectionPanel.py プロジェクト: endeep/QGIS
    def selectExtent(self):
        popupmenu = QMenu()
        useLayerExtentAction = QAction(
            QCoreApplication.translate("ExtentSelectionPanel",
                                       'Use Layer/Canvas Extent…'),
            self.btnSelect)
        selectOnCanvasAction = QAction(self.tr('Select Extent on Canvas'),
                                       self.btnSelect)

        popupmenu.addAction(useLayerExtentAction)
        popupmenu.addAction(selectOnCanvasAction)

        selectOnCanvasAction.triggered.connect(self.selectOnCanvas)
        useLayerExtentAction.triggered.connect(self.useLayerExtent)

        if self.param.flags() & QgsProcessingParameterDefinition.FlagOptional:
            useMincoveringExtentAction = QAction(
                self.tr('Use Min Covering Extent from Input Layers'),
                self.btnSelect)
            useMincoveringExtentAction.triggered.connect(
                self.useMinCoveringExtent)
            popupmenu.addAction(useMincoveringExtentAction)

        popupmenu.exec_(QCursor.pos())
コード例 #41
0
 def zoomToPressed(self):
     try:
         w3wCoord = str(self.coordBox.text()).replace(" ", "")
         QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
         json = self.w3w.forwardGeocode(w3wCoord)
         lat = float(json["geometry"]["lat"])
         lon = float(json["geometry"]["lng"])
         canvasCrs = self.canvas.mapSettings().destinationCrs()
         epsg4326 = QgsCoordinateReferenceSystem("EPSG:4326")
         transform4326 = QgsCoordinateTransform(epsg4326, canvasCrs)
         center = transform4326.transform(lon, lat)
         self.canvas.zoomByFactor(1, center)
         self.canvas.refresh()
         if self.marker is None:
             self.marker = QgsVertexMarker(self.canvas)
         self.marker.setCenter(center)
         self.marker.setIconSize(8)
         self.marker.setPenWidth(4)
         self.removeMarkerButton.setDisabled(False)
         self.coordBox.setStyleSheet("QLineEdit{background: white}")
     except Exception as e:
         self.coordBox.setStyleSheet("QLineEdit{background: yellow}")
     finally:
         QApplication.restoreOverrideCursor()
コード例 #42
0
    def runAlgorithm(algOrName, onFinish, *args, **kwargs):
        if isinstance(algOrName, GeoAlgorithm):
            alg = algOrName
        else:
            alg = Processing.getAlgorithm(algOrName)
        if alg is None:
            # fix_print_with_import
            print('Error: Algorithm not found\n')
            QgsMessageLog.logMessage(
                Processing.tr('Error: Algorithm {0} not found\n').format(
                    algOrName), Processing.tr("Processing"))
            return
        alg = alg.getCopy()

        if len(args) == 1 and isinstance(args[0], dict):
            # Set params by name and try to run the alg even if not all parameter values are provided,
            # by using the default values instead.
            setParams = []
            for (name, value) in args[0].items():
                param = alg.getParameterFromName(name)
                if param and param.setValue(value):
                    setParams.append(name)
                    continue
                output = alg.getOutputFromName(name)
                if output and output.setValue(value):
                    continue
                # fix_print_with_import
                print('Error: Wrong parameter value %s for parameter %s.' %
                      (value, name))
                QgsMessageLog.logMessage(
                    Processing.tr(
                        'Error: Wrong parameter value {0} for parameter {1}.').
                    format(value, name), Processing.tr("Processing"))
                ProcessingLog.addToLog(
                    ProcessingLog.LOG_ERROR,
                    Processing.
                    tr('Error in %s. Wrong parameter value %s for parameter %s.'
                       ) % (alg.name, value, name))
                return
            # fill any missing parameters with default values if allowed
            for param in alg.parameters:
                if param.name not in setParams:
                    if not param.setDefaultValue():
                        # fix_print_with_import
                        print(
                            'Error: Missing parameter value for parameter %s.'
                            % param.name)
                        QgsMessageLog.logMessage(
                            Processing.
                            tr('Error: Missing parameter value for parameter {0}.'
                               ).format(param.name),
                            Processing.tr("Processing"))
                        ProcessingLog.addToLog(
                            ProcessingLog.LOG_ERROR,
                            Processing.
                            tr('Error in %s. Missing parameter value for parameter %s.'
                               ) % (alg.name, param.name))
                        return
        else:
            if len(args) != alg.getVisibleParametersCount(
            ) + alg.getVisibleOutputsCount():
                # fix_print_with_import
                print('Error: Wrong number of parameters')
                QgsMessageLog.logMessage(
                    Processing.tr('Error: Wrong number of parameters'),
                    Processing.tr("Processing"))
                processing.alghelp(algOrName)
                return
            i = 0
            for param in alg.parameters:
                if not param.hidden:
                    if not param.setValue(args[i]):
                        # fix_print_with_import
                        print('Error: Wrong parameter value: ' +
                              unicode(args[i]))
                        QgsMessageLog.logMessage(
                            Processing.tr('Error: Wrong parameter value: ') +
                            unicode(args[i]), Processing.tr("Processing"))
                        return
                    i = i + 1

            for output in alg.outputs:
                if not output.hidden:
                    if not output.setValue(args[i]):
                        # fix_print_with_import
                        print('Error: Wrong output value: ' + unicode(args[i]))
                        QgsMessageLog.logMessage(
                            Processing.tr('Error: Wrong output value: ') +
                            unicode(args[i]), Processing.tr("Processing"))
                        return
                    i = i + 1

        msg = alg._checkParameterValuesBeforeExecuting()
        if msg:
            # fix_print_with_import
            print('Unable to execute algorithm\n' + unicode(msg))
            QgsMessageLog.logMessage(
                Processing.tr('Unable to execute algorithm\n{0}').format(msg),
                Processing.tr("Processing"))
            return

        if not alg.checkInputCRS():
            print('Warning: Not all input layers use the same CRS.\n' +
                  'This can cause unexpected results.')
            QgsMessageLog.logMessage(
                Processing.
                tr('Warning: Not all input layers use the same CRS.\nThis can cause unexpected results.'
                   ), Processing.tr("Processing"))

        # Don't set the wait cursor twice, because then when you
        # restore it, it will still be a wait cursor.
        overrideCursor = False
        if iface is not None:
            cursor = QApplication.overrideCursor()
            if cursor is None or cursor == 0:
                QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                overrideCursor = True
            elif cursor.shape() != Qt.WaitCursor:
                QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                overrideCursor = True

        progress = None
        if kwargs is not None and "progress" in kwargs.keys():
            progress = kwargs["progress"]
        elif iface is not None:
            progress = MessageBarProgress(alg.name)

        ret = runalg(alg, progress)
        if ret:
            if onFinish is not None:
                onFinish(alg, progress)
        else:
            QgsMessageLog.logMessage(
                Processing.tr("There were errors executing the algorithm."),
                Processing.tr("Processing"))

        if overrideCursor:
            QApplication.restoreOverrideCursor()
        if isinstance(progress, MessageBarProgress):
            progress.close()
        return alg
コード例 #43
0
ファイル: Processing.py プロジェクト: limited107/QGIS
    def runAlgorithm(algOrName, onFinish, *args, **kwargs):
        if isinstance(algOrName, GeoAlgorithm):
            alg = algOrName
        else:
            alg = QgsApplication.processingRegistry().algorithmById(algOrName)
        if alg is None:
            # fix_print_with_import
            print('Error: Algorithm not found\n')
            QgsMessageLog.logMessage(Processing.tr('Error: Algorithm {0} not found\n').format(algOrName),
                                     Processing.tr("Processing"))
            return
        # hack - remove when getCopy is removed
        provider = alg.provider()
        alg = alg.getCopy()
        #hack pt2
        alg.setProvider(provider)

        if len(args) == 1 and isinstance(args[0], dict):
            # Set params by name and try to run the alg even if not all parameter values are provided,
            # by using the default values instead.
            setParams = []
            for (name, value) in list(args[0].items()):
                param = alg.getParameterFromName(name)
                if param and param.setValue(value):
                    setParams.append(name)
                    continue
                output = alg.getOutputFromName(name)
                if output and output.setValue(value):
                    continue
                # fix_print_with_import
                print('Error: Wrong parameter value %s for parameter %s.' % (value, name))
                QgsMessageLog.logMessage(
                    Processing.tr('Error: Wrong parameter value {0} for parameter {1}.').format(value, name),
                    Processing.tr("Processing"))
                QgsMessageLog.logMessage(Processing.tr('Error in {0}. Wrong parameter value {1} for parameter {2}.').format(
                    alg.name(), value, name
                ), Processing.tr("Processing"),
                    QgsMessageLog.CRITICAL
                )
                return
            # fill any missing parameters with default values if allowed
            for param in alg.parameters:
                if param.name not in setParams:
                    if not param.setDefaultValue():
                        # fix_print_with_import
                        print('Error: Missing parameter value for parameter %s.' % param.name)
                        QgsMessageLog.logMessage(
                            Processing.tr('Error: Missing parameter value for parameter {0}.').format(param.name),
                            Processing.tr("Processing"))
                        return
        else:
            if len(args) != alg.getVisibleParametersCount() + alg.getVisibleOutputsCount():
                # fix_print_with_import
                print('Error: Wrong number of parameters')
                QgsMessageLog.logMessage(Processing.tr('Error: Wrong number of parameters'),
                                         Processing.tr("Processing"))
                processing.algorithmHelp(algOrName)
                return
            i = 0
            for param in alg.parameters:
                if not param.hidden:
                    if not param.setValue(args[i]):
                        # fix_print_with_import
                        print('Error: Wrong parameter value: ' + str(args[i]))
                        QgsMessageLog.logMessage(Processing.tr('Error: Wrong parameter value: ') + str(args[i]),
                                                 Processing.tr("Processing"))
                        return
                    i = i + 1

            for output in alg.outputs:
                if not output.hidden:
                    if not output.setValue(args[i]):
                        # fix_print_with_import
                        print('Error: Wrong output value: ' + str(args[i]))
                        QgsMessageLog.logMessage(Processing.tr('Error: Wrong output value: ') + str(args[i]),
                                                 Processing.tr("Processing"))
                        return
                    i = i + 1

        context = None
        if kwargs is not None and 'context' in list(kwargs.keys()):
            context = kwargs["context"]
        else:
            context = dataobjects.createContext()

        msg = alg._checkParameterValuesBeforeExecuting(context)
        if msg:
            # fix_print_with_import
            print('Unable to execute algorithm\n' + str(msg))
            QgsMessageLog.logMessage(Processing.tr('Unable to execute algorithm\n{0}').format(msg),
                                     Processing.tr("Processing"))
            return

        if not alg.checkInputCRS(context):
            print('Warning: Not all input layers use the same CRS.\n' +
                  'This can cause unexpected results.')
            QgsMessageLog.logMessage(
                Processing.tr('Warning: Not all input layers use the same CRS.\nThis can cause unexpected results.'),
                Processing.tr("Processing"))

        # Don't set the wait cursor twice, because then when you
        # restore it, it will still be a wait cursor.
        overrideCursor = False
        if iface is not None:
            cursor = QApplication.overrideCursor()
            if cursor is None or cursor == 0:
                QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                overrideCursor = True
            elif cursor.shape() != Qt.WaitCursor:
                QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
                overrideCursor = True

        feedback = None
        if kwargs is not None and "feedback" in list(kwargs.keys()):
            feedback = kwargs["feedback"]
        elif iface is not None:
            feedback = MessageBarProgress(alg.displayName())

        ret = execute(alg, context, feedback)
        if ret:
            if onFinish is not None:
                onFinish(alg, context, feedback)
        else:
            QgsMessageLog.logMessage(Processing.tr("There were errors executing the algorithm."),
                                     Processing.tr("Processing"))

        if overrideCursor:
            QApplication.restoreOverrideCursor()
        if isinstance(feedback, MessageBarProgress):
            feedback.close()
        return alg