Пример #1
0
    def batchFinished(self):
        self.base.stop()

        if len(self.errors) > 0:
            msg = u"Processing of the following files ended with error: <br><br>" + "<br><br>".join(self.errors)
            QErrorMessage(self).showMessage(msg)

        inDir = self.getInputFileName()
        outDir = self.getOutputFileName()
        if outDir is None or inDir == outDir:
            self.outFiles = self.inFiles

        # load layers managing the render flag to avoid waste of time
        canvas = self.iface.mapCanvas()
        previousRenderFlag = canvas.renderFlag()
        canvas.setRenderFlag(False)
        notCreatedList = []
        for item in self.outFiles:
            fileInfo = QFileInfo(item)
            if fileInfo.exists():
                if self.base.loadCheckBox.isChecked():
                    self.addLayerIntoCanvas(fileInfo)
            else:
                notCreatedList.append(item)
        canvas.setRenderFlag(previousRenderFlag)

        if len(notCreatedList) == 0:
            QMessageBox.information(self, self.tr("Finished"), self.tr("Operation completed."))
        else:
            QMessageBox.warning(self, self.tr("Warning"), self.tr("The following files were not created: \n{0}").format(', '.join(notCreatedList)))
Пример #2
0
    def process(self):
        search_name = self.searchName.text()
        layer = self.layerCombo.currentLayer()
        expression = self.fieldExpressionWidget.currentField()[0]
        geometryStorage = self.geometryStorageCombo.currentText()
        priority = self.priorityBox.value()
        srid = layer.crs().authid()
        evaluate_directly = self.evaluateCheckBox.isChecked()

        if self.projectSearch is None:
            self.projectSearch = self.project_search_model.addSearch(
                search_name, layer, expression, geometryStorage, priority)
        else:
            self.projectSearch.edit(search_name, layer.id(), layer.name(),
                                    expression, geometryStorage, priority,
                                    srid)

        if evaluate_directly:
            self.progressBar.setMinimum(0)
            self.progressBar.setMaximum(layer.featureCount())
            self.progressBar.show()
            self.cancelButton.show()

            ok, message = self.project_finder.recordSearch(self.projectSearch)

            self.progressBar.hide()
            self.cancelButton.hide()
            self.okButton.show()

            if not ok:
                QErrorMessage().showMessage(message)
                return

        self.close()
Пример #3
0
    def onError(self, error):
        if error == QProcess.FailedToStart:
            msg = QCoreApplication.translate("GdalTools", "The process failed to start. Either the invoked program is missing, or you may have insufficient permissions to invoke the program.")
        elif error == QProcess.Crashed:
            msg = QCoreApplication.translate("GdalTools", "The process crashed some time after starting successfully.")
        else:
            msg = QCoreApplication.translate("GdalTools", "An unknown error occurred.")

        QErrorMessage(self).showMessage(msg)
        QApplication.processEvents()  # give the user chance to see the message

        self.stop()
Пример #4
0
    def loadFields(self, vectorFile=''):
        self.zfieldCombo.clear()

        if not vectorFile:
            return

        try:
            (fields, names) = Utils.getVectorFields(vectorFile)
        except Utils.UnsupportedOGRFormat as e:
            QErrorMessage(self).showMessage(e.args[0])
            self.inSelector.setLayer(None)
            return

        ncodec = QTextCodec.codecForName(self.lastEncoding)
        for name in names:
            self.zfieldCombo.addItem(ncodec.toUnicode(name))
Пример #5
0
    def loadFields(self, vectorFile):
        self.attributeComboBox.clear()

        if not vectorFile:
            return

        try:
            (fields, names) = Utils.getVectorFields(vectorFile)
        except Utils.UnsupportedOGRFormat as e:
            QErrorMessage(self).showMessage(e.args[0])
            self.inSelector.setLayer(None)
            return

        # GDAL Python3 bindings return fields as str and not bytes
        # so no recoding is needed. But this assumes that the underlying
        # OGR driver always return a Unicode string. hum...
        #ncodec = QTextCodec.codecForName(self.lastEncoding)
        for name in names:
            self.attributeComboBox.addItem(name)
Пример #6
0
    def onFinished(self, exitCode, status):
        if status == QProcess.CrashExit:
            self.stop()
            return

        if self.command.find("gdalinfo") != -1 and exitCode == 0:
            self.finished.emit(self.loadCheckBox.isChecked())
            self.stop()
            return

        # show the error message if there's one, otherwise show the process output message
        msg = unicode(self.process.readAllStandardError())
        if msg == '':
            outMessages = unicode(
                self.process.readAllStandardOutput()).splitlines()

            # make sure to not show the help
            for m in outMessages:
                m = string.strip(m)
                if m == '':
                    continue
                # TODO fix this
                #if m.contains( QRegExp( "^(?:[Uu]sage:\\s)?" + QRegExp.escape(self.command) + "\\s" ) ):
                #  if msg.isEmpty():
                #    msg = self.tr ( "Invalid parameters." )
                #  break
                #if m.contains( QRegExp( "0(?:\\.+[1-9]0{1,2})+" ) ):
                #  continue

                if msg:
                    msg += "\n"
                msg += m

        QErrorMessage(self).showMessage(msg.replace("\n", "<br>"))

        if exitCode == 0:
            self.finished.emit(self.loadCheckBox.isChecked())

        self.stop()
    def run(self):
        """Run method that performs all the real work"""

        # Create the dialog with elements (after translation) and keep reference
        # Only create GUI ONCE in callback, so that it will only load when the plugin is started
        if self.first_start == True:
            self.first_start = False
            self.dlg = ReanalysisVisualizationDialog()

        project = QgsProject.instance()
        if not project.mapLayersByName('back'):
            layer = QgsVectorLayer(
                './background/ne_110m_admin_0_countries.shp', "back", "ogr")
            project.addMapLayer(layer)

        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            params, variables, drawStyle, need_slideshow = self.dlg.prepare_form_data()
            try:
                root = QgsProject.instance().layerTreeRoot()

                group = root.findGroup('contours')
                if group:
                    group.removeAllChildren()
                else:
                    group = root.addGroup("contours")

                root.insertChildNode(-1,
                                     QgsLayerTreeLayer(project.mapLayersByName('back')[0]))
                root.removeLayer(project.mapLayersByName('back')[0])
                data_grid = DataGrid(params, variables)
                geojsons = Isolines(data_grid, drawStyle).get_geojsons()

                for geojson in geojsons:
                    layer = QgsVectorLayer(
                        geojson['geojson'], "leadTime = " + str(geojson['leadTime']), "ogr")
                    layer.setOpacity(0.87)
                    # apply contour style properties
                    symbol_layer = layer.renderer().symbol().symbolLayers()[0]
                    symbol_layer.setDataDefinedProperty(
                        QgsSymbolLayer.PropertyStrokeColor, QgsProperty.fromField("stroke"))
                    symbol_layer.setDataDefinedProperty(
                        QgsSymbolLayer.PropertyFillColor, QgsProperty.fromField("fill"))
                    symbol_layer.setDataDefinedProperty(
                        QgsSymbolLayer.PropertyStrokeWidth, QgsProperty.fromField("stroke-width"))

                    # add labels
                    pal_layer = QgsPalLayerSettings()
                    pal_layer.fieldName = 'title'
                    pal_layer.enabled = True
                    pal_layer.placement = QgsPalLayerSettings.PerimeterCurved
                    pal_layer.placementFlags = QgsPalLayerSettings.OnLine

                    labeler = QgsVectorLayerSimpleLabeling(pal_layer)

                    layer.setLabeling(labeler)
                    layer.setLabelsEnabled(True)

                    # add vector layer with isolines
                    QgsProject.instance().addMapLayer(layer, False)
                    group.insertChildNode(-1, QgsLayerTreeLayer(layer))
                group.setIsMutuallyExclusive(True, 0)
                if need_slideshow:
                    slideshow = threading.Thread(
                        target=self.__change_active_layer, args=(group,))
                    slideshow.start()
            except Exception as e:
                error_text = ''

                if (params['east'] > 180 or params['east'] < -180 or params['west'] > 180 or params['west'] < -180 or params['south'] > 90 or params['south'] < -90 or params['north'] > 90 or params['north'] < -90):
                    error_text += "Ошибка: Некорректно заданы координаты области"
                else:
                    error_text += "Ошибка: \n" + str(e)
                error_dialog = QErrorMessage()
                error_dialog.showMessage(error_text)
                error_dialog.exec_()