示例#1
0
 def refresh(self):
     layers = dataobjects.getRasterLayers()
     options = {}
     for lyr in layers:
         for n in range(lyr.bandCount()):
             options[lyr.name()] = '{:s}@{:d}'.format(lyr.name(), n + 1)
     self.widget.setList(options)
示例#2
0
 def createWidget(self):
     if self.dialogType == DIALOG_STANDARD:
         if self.param.datatype == dataobjects.TYPE_FILE:
             return MultipleInputPanel(datatype=dataobjects.TYPE_FILE)
         else:
             if self.param.datatype == dataobjects.TYPE_RASTER:
                 options = dataobjects.getRasterLayers(sorting=False)
             elif self.param.datatype == dataobjects.TYPE_VECTOR_ANY:
                 options = dataobjects.getVectorLayers(sorting=False)
             else:
                 options = dataobjects.getVectorLayers(
                     [self.param.datatype], sorting=False)
             opts = [getExtendedLayerName(opt) for opt in options]
             return MultipleInputPanel(opts)
     elif self.dialogType == DIALOG_BATCH:
         widget = BatchInputSelectionPanel(self.param, self.row, self.col,
                                           self.dialog)
         widget.valueChanged.connect(
             lambda: self.widgetValueHasChanged.emit(self))
         return widget
     else:
         options = [
             self.dialog.resolveValueDescription(opt)
             for opt in self._getOptions()
         ]
         return MultipleInputPanel(options)
    def getWidgetFromParameter(self, param):
        """
        Overload for custom Qwidget(Panel) from Parameter
        return item : Qwidget(Panel)
        """

        if param.name in ["CHANGES"]:
            item = TableReplaceInputDialog(self, param)

        elif param.name in ["MAP_CSV"]:
            item = FileSelectionCSVTXTPanel(param.isFolder, param.ext)

        elif isinstance(param, ParameterRaster):
            # === Overload of Panel for Raster in order to add signal for updating param
            layers = dataobjects.getRasterLayers()
            items = []
            if param.optional:
                items.append((self.NOT_SELECTED, None))

            self.NONE_SELECTED = self.tr('Chose a layer')
            items.append((self.NONE_SELECTED, ""))  # Not use None
            for layer in layers:
                items.append((self.getExtendedLayerName(layer), layer))
            item = InputLayerSelectorPanel(items, param)

        else:
            # == default Wigdet from Parameter, i.e. use parent method
            item = ParametersPanel.getWidgetFromParameter(self, param)

        return item
示例#4
0
 def refresh(self):
     layers = dataobjects.getRasterLayers()
     options = {}
     for lyr in layers:
         for n in range(lyr.bandCount()):
             options[lyr.name()] = '{:s}@{:d}'.format(lyr.name(), n + 1)
     self.widget.setList(options)
    def getWidgetFromParameter(self, param):
        """
        Overload for custom Qwidget(Panel) from Parameter
        return item : Qwidget(Panel)
        """

        if param.name in ["DOMAINS"]:
            # === Overload ParameterString for special parameter name like DOMAINS,..
            item = ClassificationTablePanel(self.parent, self.alg,
                                            param.default)
            if param.default:
                item.setText(unicode(param.default))

        elif isinstance(param, ParameterRaster):
            # === Overload of Panel for Raster in order to add signal for updating param

            layers = dataobjects.getRasterLayers()
            items = []
            if param.optional:
                items.append((self.NOT_SELECTED, None))

            self.NONE_SELECTED = self.tr('Chose a layer')
            items.append((self.NONE_SELECTED, ""))  # Not use None
            for layer in layers:
                items.append((self.getExtendedLayerName(layer), layer))
            item = CustomInputLayerSelectorPanel(items, param)

        else:
            # == default Wigdet from Parameter, i.e. use parent method
            item = ChloeParametersPanel.getWidgetFromParameter(self, param)
            #item = ParametersPanel.getWidgetFromParameter(self,param)

        return item
示例#6
0
    def showLayerSelectionDialog(self):
        if (isinstance(self.param, ParameterRaster) or
                (isinstance(self.param, ParameterMultipleInput) and
                 self.param.datatype == dataobjects.TYPE_RASTER)):
            layers = dataobjects.getRasterLayers()
        elif isinstance(self.param, ParameterTable):
            layers = dataobjects.getTables()
        else:
            if isinstance(self.param, ParameterVector):
                datatype = self.param.datatype
            else:
                datatype = [self.param.datatype]
            layers = dataobjects.getVectorLayers(datatype)

        dlg = MultipleInputDialog([layer.name() for layer in layers])
        dlg.exec_()
        if dlg.selectedoptions is not None:
            selected = dlg.selectedoptions
            if len(selected) == 1:
                self.setValue(layers[selected[0]])
            else:
                if isinstance(self.param, ParameterMultipleInput):
                    self.text.setText(';'.join(layers[idx].name() for idx in selected))
                else:
                    rowdif = len(selected) - (self._table().rowCount() - self.row)
                    for i in range(rowdif):
                        self._panel().addRow()
                    for i, layeridx in enumerate(selected):
                        self._table().cellWidget(i + self.row,
                                                 self.col).setValue(layers[layeridx])
示例#7
0
    def showLayerSelectionDialog(self):
        if (isinstance(self.param, ParameterRaster)
                or (isinstance(self.param, ParameterMultipleInput)
                    and self.param.datatype == dataobjects.TYPE_RASTER)):
            layers = dataobjects.getRasterLayers()
        elif isinstance(self.param, ParameterTable):
            layers = dataobjects.getTables()
        else:
            if isinstance(self.param, ParameterVector):
                datatype = self.param.datatype
            else:
                datatype = [self.param.datatype]
            layers = dataobjects.getVectorLayers(datatype)

        dlg = MultipleInputDialog([layer.name() for layer in layers])
        dlg.exec_()
        if dlg.selectedoptions is not None:
            selected = dlg.selectedoptions
            if len(selected) == 1:
                self.setValue(layers[selected[0]])
            else:
                if isinstance(self.param, ParameterMultipleInput):
                    self.text.setText(';'.join(layers[idx].name()
                                               for idx in selected))
                else:
                    rowdif = len(selected) - (self._table().rowCount() -
                                              self.row)
                    for i in range(rowdif):
                        self._panel().addRow()
                    for i, layeridx in enumerate(selected):
                        self._table().cellWidget(
                            i + self.row, self.col).setValue(layers[layeridx])
示例#8
0
    def getWidgetFromParameter(self, param):
        """
        Overload for custom Qwidget(Panel) from Parameter
        return item : Qwidget(Panel)
        """

        if param.name in ["METRICS"]:
            # === Overload ParameterString for special parameter name like FIELDS,..s
            item = DoubleCmbBoxSelectionPanel(self.parent, self.alg,
                                              param.default)
        elif param.name in ["FILTER", "UNFILTER"]:
            # === Overload ParameterString for special parameter name like FIELDS,..s
            item = ValuesSelectionPanel(self.parent, self.alg, param.default,
                                        'INPUT_LAYER_ASC')
            if param.default:
                item.setText(unicode(param.default))

        elif isinstance(param, ParameterRaster):
            # === Overload of Panel for Raster in order to add signal for updating param
            layers = dataobjects.getRasterLayers()
            items = []
            if param.optional:
                items.append((self.NOT_SELECTED, None))

            self.NONE_SELECTED = self.tr('Chose a layer')
            items.append((self.NONE_SELECTED, ""))  # Not use None
            for layer in layers:
                items.append((self.getExtendedLayerName(layer), layer))
            item = InputLayerSelectorPanel(items, param)

        else:
            # == default Wigdet from Parameter, i.e. use parent method
            item = ParametersPanel.getWidgetFromParameter(self, param)

        return item
示例#9
0
    def processAlgorithm(self, feedback):
        expression = self.getParameterValue(self.EXPRESSION)
        layersValue = self.getParameterValue(self.LAYERS)
        layersDict = {}
        if layersValue:
            layers = [
                dataobjects.getObjectFromUri(f) for f in layersValue.split(";")
            ]
            layersDict = {
                os.path.basename(lyr.source().split(".")[0]): lyr
                for lyr in layers
            }

        for lyr in dataobjects.getRasterLayers():
            name = lyr.name()
            if (name + "@") in expression:
                layersDict[name] = lyr

        entries = []
        for name, lyr in layersDict.items():
            for n in range(lyr.bandCount()):
                entry = QgsRasterCalculatorEntry()
                entry.ref = '{:s}@{:d}'.format(name, n + 1)
                entry.raster = lyr
                entry.bandNumber = n + 1
                entries.append(entry)

        output = self.getOutputValue(self.OUTPUT)
        extentValue = self.getParameterValue(self.EXTENT)

        if extentValue:
            extent = extentValue.split(',')
            bbox = QgsRectangle(float(extent[0]), float(extent[2]),
                                float(extent[1]), float(extent[3]))
        else:
            if layersDict:
                bbox = list(layersDict.values())[0].extent()
                for lyr in layersDict.values():
                    bbox.combineExtentWith(lyr.extent())
            else:
                raise GeoAlgorithmExecutionException(
                    self.tr("No layers selected"))

        def _cellsize(layer):
            return (layer.extent().xMaximum() -
                    layer.extent().xMinimum()) / layer.width()

        cellsize = self.getParameterValue(self.CELLSIZE) or min(
            [_cellsize(lyr) for lyr in layersDict.values()])
        width = math.floor((bbox.xMaximum() - bbox.xMinimum()) / cellsize)
        height = math.floor((bbox.yMaximum() - bbox.yMinimum()) / cellsize)
        driverName = GdalUtils.getFormatShortNameFromFilename(output)
        calc = QgsRasterCalculator(expression, output, driverName, bbox, width,
                                   height, entries)

        res = calc.processCalculation()
        if res == QgsRasterCalculator.ParserError:
            raise GeoAlgorithmExecutionException(
                self.tr("Error parsing formula"))
示例#10
0
 def refresh(self):
     items = []
     layers = dataobjects.getRasterLayers()
     if self.param.optional:
         items.append((self.NOT_SELECTED, None))
     for layer in layers:
         items.append((getExtendedLayerName(layer), layer))
     self.widget.update(items)
示例#11
0
    def setParamValue(self, param, widget, alg=None):
        if isinstance(param, ParameterRaster):
            return param.setValue(widget.getValue())
        elif isinstance(param, (ParameterVector, ParameterTable)):
            try:
                return param.setValue(widget.itemData(widget.currentIndex()))
            except:
                return param.setValue(widget.getValue())
        elif isinstance(param, ParameterBoolean):
            return param.setValue(widget.isChecked())
        elif isinstance(param, ParameterSelection):
            return param.setValue(widget.currentIndex())
        elif isinstance(param, ParameterFixedTable):
            return param.setValue(widget.table)
        elif isinstance(param, ParameterRange):
            return param.setValue(widget.getValue())
        elif isinstance(param, ParameterTableField):
            if param.optional and widget.currentIndex() == 0:
                return param.setValue(None)
            return param.setValue(widget.currentText())
        elif isinstance(param, ParameterTableMultipleField):
            if param.optional and len(list(widget.get_selected_items())) == 0:
                return param.setValue(None)
            return param.setValue(list(widget.get_selected_items()))
        elif isinstance(param, ParameterMultipleInput):
            if param.datatype == ParameterMultipleInput.TYPE_FILE:
                return param.setValue(widget.selectedoptions)
            else:
                if param.datatype == ParameterMultipleInput.TYPE_RASTER:
                    options = dataobjects.getRasterLayers(sorting=False)
                elif param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                    options = dataobjects.getVectorLayers(sorting=False)
                else:
                    options = dataobjects.getVectorLayers([param.datatype],
                                                          sorting=False)
                return param.setValue(
                    [options[i] for i in widget.selectedoptions])
        elif isinstance(param, (ParameterNumber, ParameterFile, ParameterCrs,
                                ParameterExtent, ParameterPoint)):
            return param.setValue(widget.getValue())
        elif isinstance(param, ParameterString):
            if param.multiline:
                text = unicode(widget.toPlainText())
            else:
                text = widget.text()

            if param.evaluateExpressions:
                try:
                    text = self.evaluateExpression(text)
                except:
                    pass
            return param.setValue(text)
        elif isinstance(param, ParameterGeometryPredicate):
            return param.setValue(widget.value())
        else:
            return param.setValue(unicode(widget.text()))
示例#12
0
 def refresh(self):
     if self.param.datatype != dataobjects.TYPE_FILE:
         if self.param.datatype == dataobjects.TYPE_RASTER:
             options = dataobjects.getRasterLayers(sorting=False)
         elif self.param.datatype == dataobjects.TYPE_VECTOR_ANY:
             options = dataobjects.getVectorLayers(sorting=False)
         else:
             options = dataobjects.getVectorLayers([self.param.datatype], sorting=False)
         opts = [self.getExtendedLayerName(opt) for opt in options]
         self.widget.updateForOptions(opts)
示例#13
0
    def setParamValue(self, param, widget, alg=None):
        if isinstance(param, ParameterRaster):
            return param.setValue(widget.getValue())
        elif isinstance(param, (ParameterVector, ParameterTable)):
            try:
                return param.setValue(widget.itemData(widget.currentIndex()))
            except:
                return param.setValue(widget.getValue())
        elif isinstance(param, ParameterBoolean):
            return param.setValue(widget.isChecked())
        elif isinstance(param, ParameterSelection):
            return param.setValue(widget.currentIndex())
        elif isinstance(param, ParameterFixedTable):
            return param.setValue(widget.table)
        elif isinstance(param, ParameterRange):
            return param.setValue(widget.getValue())
        elif isinstance(param, ParameterTableField):
            if param.optional and widget.currentIndex() == 0:
                return param.setValue(None)
            return param.setValue(widget.currentText())
        elif isinstance(param, ParameterTableMultipleField):
            if param.optional and len(list(widget.get_selected_items())) == 0:
                return param.setValue(None)
            return param.setValue(list(widget.get_selected_items()))
        elif isinstance(param, ParameterMultipleInput):
            if param.datatype == dataobjects.TYPE_FILE:
                return param.setValue(widget.selectedoptions)
            else:
                if param.datatype == dataobjects.TYPE_RASTER:
                    options = dataobjects.getRasterLayers(sorting=False)
                elif param.datatype == dataobjects.TYPE_VECTOR_ANY:
                    options = dataobjects.getVectorLayers(sorting=False)
                else:
                    options = dataobjects.getVectorLayers([param.datatype], sorting=False)
                return param.setValue([options[i] for i in widget.selectedoptions])
        elif isinstance(param, (ParameterNumber, ParameterFile, ParameterCrs,
                                ParameterExtent, ParameterPoint)):
            return param.setValue(widget.getValue())
        elif isinstance(param, ParameterString):
            if param.multiline:
                text = str(widget.toPlainText())
            else:
                text = widget.text()

            if param.evaluateExpressions:
                try:
                    text = self.evaluateExpression(text)
                except:
                    pass
            return param.setValue(text)
        elif isinstance(param, ParameterGeometryPredicate):
            return param.setValue(widget.value())
        else:
            return param.setValue(str(widget.text()))
示例#14
0
    def processAlgorithm(self, progress):
        expression = self.getParameterValue(self.EXPRESSION)
        layersValue = self.getParameterValue(self.LAYERS)
        layersDict = {}
        if layersValue:
            layers = [dataobjects.getObjectFromUri(f) for f in layersValue.split(";")]
            layersDict = {os.path.basename(lyr.source().split(".")[0]): lyr for lyr in layers}

        for lyr in dataobjects.getRasterLayers():
            name = lyr.name()
            if (name + "@") in expression:
                layersDict[name] = lyr

        entries = []
        for name, lyr in layersDict.items():
            for n in range(lyr.bandCount()):
                entry = QgsRasterCalculatorEntry()
                entry.ref = '{:s}@{:d}'.format(name, n + 1)
                entry.raster = lyr
                entry.bandNumber = n + 1
                entries.append(entry)

        output = self.getOutputValue(self.OUTPUT)
        extentValue = self.getParameterValue(self.EXTENT)

        if extentValue:
            extent = extentValue.split(',')
            bbox = QgsRectangle(float(extent[0]), float(extent[2]),
                                float(extent[1]), float(extent[3]))
        else:
            if layersDict:
                bbox = list(layersDict.values())[0].extent()
                for lyr in layersDict.values():
                    bbox.combineExtentWith(lyr.extent())
            else:
                raise GeoAlgorithmExecutionException(self.tr("No layers selected"))

        def _cellsize(layer):
            return (layer.extent().xMaximum() - layer.extent().xMinimum()) / layer.width()
        cellsize = self.getParameterValue(self.CELLSIZE) or min([_cellsize(lyr) for lyr in layersDict.values()])
        width = math.floor((bbox.xMaximum() - bbox.xMinimum()) / cellsize)
        height = math.floor((bbox.yMaximum() - bbox.yMinimum()) / cellsize)
        driverName = GdalUtils.getFormatShortNameFromFilename(output)
        calc = QgsRasterCalculator(expression,
                                   output,
                                   driverName,
                                   bbox,
                                   width,
                                   height,
                                   entries)

        res = calc.processCalculation()
        if res == QgsRasterCalculator.ParserError:
            raise GeoAlgorithmExecutionException(self.tr("Error parsing formula"))
示例#15
0
 def updateMultipleInputs(self):
     for param in self.alg.parameters:
         if isinstance(param, ParameterMultipleInput) and param.datatype != dataobjects.TYPE_FILE:
             if param.datatype == dataobjects.TYPE_RASTER:
                 options = dataobjects.getRasterLayers(sorting=False)
             elif param.datatype == dataobjects.TYPE_VECTOR_ANY:
                 options = dataobjects.getVectorLayers(sorting=False)
             else:
                 options = dataobjects.getVectorLayers([param.datatype], sorting=False)
             opts = [self.getExtendedLayerName(opt) for opt in options]
             widget = self.valueItems[param.name]
             widget.updateForOptions(opts)
示例#16
0
 def updateMultipleInputs(self):
     for param in self.alg.parameters:
         if isinstance(param, ParameterMultipleInput) and param.datatype != ParameterMultipleInput.TYPE_FILE:
             if param.datatype == ParameterMultipleInput.TYPE_RASTER:
                 options = dataobjects.getRasterLayers(sorting=False)
             elif param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                 options = dataobjects.getVectorLayers(sorting=False)
             else:
                 options = dataobjects.getVectorLayers([param.datatype], sorting=False)
             opts = [self.getExtendedLayerName(opt) for opt in options]
             widget = self.valueItems[param.name]
             widget.updateForOptions(opts)
示例#17
0
    def fillTree(self):
        layersItem = QtGui.QTreeWidgetItem()
        layersItem.setText(0, "Values from data layers extents")
        self.tree.addTopLevelItem(layersItem)
        layers = dataobjects.getAllLayers()
        for layer in layers:
            layerItem = QtGui.QTreeWidgetItem()
            layerItem.setText(0, unicode(layer.name()))
            layerItem.addChild(TreeValueItem("Min X", layer.extent().xMinimum()))
            layerItem.addChild(TreeValueItem("Max X", layer.extent().xMaximum()))
            layerItem.addChild(TreeValueItem("Min Y", layer.extent().yMinimum()))
            layerItem.addChild(TreeValueItem("Max y", layer.extent().yMaximum()))
            if isinstance(layer, QgsRasterLayer):
                cellsize = (layer.extent().xMaximum() - layer.extent().xMinimum())/layer.width()
                layerItem.addChild(TreeValueItem("Cellsize", cellsize))
            layersItem.addChild(layerItem)
        layersItem = QtGui.QTreeWidgetItem()
        layersItem.setText(0, "Values from raster layers statistics")
        self.tree.addTopLevelItem(layersItem)
        layers = dataobjects.getRasterLayers()
        for layer in layers:
            for i in range(layer.bandCount()):
                if QGis.QGIS_VERSION_INT >= 10900:
                    stats = layer.dataProvider().bandStatistics(i+1)
                else:
                    stats = layer.bandStatistics(i)
                layerItem = QtGui.QTreeWidgetItem()
                layerItem.setText(0, unicode(layer.name()))
                layerItem.addChild(TreeValueItem("Mean", stats.mean))
                layerItem.addChild(TreeValueItem("Std. deviation", stats.stdDev))
                layerItem.addChild(TreeValueItem("Max value", stats.maximumValue))
                layerItem.addChild(TreeValueItem("Min value", stats.minimumValue))
                layersItem.addChild(layerItem)

        canvasItem = QtGui.QTreeWidgetItem()
        canvasItem.setText(0, "Values from QGIS map canvas")
        self.tree.addTopLevelItem(canvasItem)
        extent = interface.iface.mapCanvas().extent()
        extentItem  = QtGui.QTreeWidgetItem()
        extentItem.setText(0, "Current extent")
        extentItem.addChild(TreeValueItem("Min X", extent.xMinimum()))
        extentItem.addChild(TreeValueItem("Max X", extent.xMaximum()))
        extentItem.addChild(TreeValueItem("Min Y", extent.yMinimum()))
        extentItem.addChild(TreeValueItem("Max y", extent.yMaximum()))
        canvasItem.addChild(extentItem)
        extent = interface.iface.mapCanvas().fullExtent()
        extentItem  = QtGui.QTreeWidgetItem()
        extentItem.setText(0, "Full extent of all layers in map canvas")
        extentItem.addChild(TreeValueItem("Min X", extent.xMinimum()))
        extentItem.addChild(TreeValueItem("Max X", extent.xMaximum()))
        extentItem.addChild(TreeValueItem("Min Y", extent.yMinimum()))
        extentItem.addChild(TreeValueItem("Max y", extent.yMaximum()))
        canvasItem.addChild(extentItem)
    def setParamValue(self, param, widget):
        """
        set the .value of the parameter according to the given widget
        the way to get the value is different for each value,
        so there is a code for each kind of parameter

        param : -il <ParameterMultipleInput> or -method <ParameterSelection> ...
        """
        if isinstance(param, ParameterRaster):
            return param.setValue(widget.getValue())
        elif isinstance(param, (ParameterVector, ParameterTable)):
            try:
                return param.setValue(widget.itemData(widget.currentIndex()))
            except:
                return param.setValue(widget.getValue())
        elif isinstance(param, ParameterBoolean):
            return param.setValue(widget.currentIndex() == 0)
        elif isinstance(param, ParameterSelection):
            return param.setValue(widget.currentIndex())
        elif isinstance(param, ParameterFixedTable):
            return param.setValue(widget.table)
        elif isinstance(param, ParameterRange):
            return param.setValue(widget.getValue())
        if isinstance(param, ParameterTableField):
            if param.optional and widget.currentIndex() == 0:
                return param.setValue(None)
            return param.setValue(widget.currentText())
        elif isinstance(param, ParameterMultipleInput):
            if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                options = dataobjects.getVectorLayers()
            else:
                options = dataobjects.getRasterLayers()
            value = []
            for index in widget.selectedoptions:
                value.append(options[index])
            return param.setValue(value)
        elif isinstance(param, ParameterMultipleExternalInput):
            value = widget.selectedoptions
            return param.setValue(value)
        elif isinstance(param, (ParameterNumber, ParameterFile, ParameterCrs,
                        ParameterExtent)):
            return param.setValue(widget.getValue())
        elif isinstance(param, ParameterString):
            if param.multiline:
                return param.setValue(unicode(widget.toPlainText()))
            else:
                return param.setValue(unicode(widget.text()))
        else:
            return param.setValue(unicode(widget.text()))
示例#19
0
 def createWidget(self):
     if self.dialogType == DIALOG_STANDARD:
         layers = dataobjects.getRasterLayers(sorting=False)
         options = {}
         for lyr in layers:
             for n in range(lyr.bandCount()):
                 name = '{:s}@{:d}'.format(lyr.name(), n + 1)
                 options[name] = name
         return self._panel(options)
     elif self.dialogType == DIALOG_BATCH:
         return QLineEdit()
     else:
         layers = self.dialog.getAvailableValuesOfType(ParameterRaster, OutputRaster)
         options = {self.dialog.resolveValueDescription(lyr): "{}@1".format(lyr) for lyr in layers}
         return self._panel(options)
示例#20
0
    def setParamValue(self, param, widget):
        """
        set the .value of the parameter according to the given widget
        the way to get the value is different for each value,
        so there is a code for each kind of parameter

        param : -il <ParameterMultipleInput> or -method <ParameterSelection> ...
        """
        if isinstance(param, ParameterRaster):
            return param.setValue(widget.getValue())
        elif isinstance(param, (ParameterVector, ParameterTable)):
            try:
                return param.setValue(widget.itemData(widget.currentIndex()))
            except:
                return param.setValue(widget.getValue())
        elif isinstance(param, ParameterBoolean):
            return param.setValue(widget.currentIndex() == 0)
        elif isinstance(param, ParameterSelection):
            return param.setValue(widget.currentIndex())
        elif isinstance(param, ParameterFixedTable):
            return param.setValue(widget.table)
        elif isinstance(param, ParameterRange):
            return param.setValue(widget.getValue())
        if isinstance(param, ParameterTableField):
            if param.optional and widget.currentIndex() == 0:
                return param.setValue(None)
            return param.setValue(widget.currentText())
        elif isinstance(param, ParameterMultipleInput):
            if param.datatype == ParameterMultipleInput.TYPE_FILE:
                return param.setValue(widget.selectedoptions)
            else:
                if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                    options = dataobjects.getVectorLayers()
                else:
                    options = dataobjects.getRasterLayers()
                return param.setValue(
                    [options[i] for i in widget.selectedoptions])
        elif isinstance(
                param,
            (ParameterNumber, ParameterFile, ParameterCrs, ParameterExtent)):
            return param.setValue(widget.getValue())
        elif isinstance(param, ParameterString):
            if param.multiline:
                return param.setValue(unicode(widget.toPlainText()))
            else:
                return param.setValue(unicode(widget.text()))
        else:
            return param.setValue(unicode(widget.text()))
示例#21
0
    def expressionContext(self):
        context = QgsExpressionContext()
        context.appendScope(QgsExpressionContextUtils.globalScope())
        context.appendScope(QgsExpressionContextUtils.projectScope())
        processingScope = QgsExpressionContextScope()
        layers = dataobjects.getAllLayers()
        for layer in layers:
            name = layer.name()
            processingScope.setVariable('%s_minx' % name,
                                        layer.extent().xMinimum())
            processingScope.setVariable('%s_miny' % name,
                                        layer.extent().yMinimum())
            processingScope.setVariable('%s_maxx' % name,
                                        layer.extent().xMaximum())
            processingScope.setVariable('%s_maxy' % name,
                                        layer.extent().yMaximum())
            if isinstance(layer, QgsRasterLayer):
                cellsize = (layer.extent().xMaximum() -
                            layer.extent().xMinimum()) / layer.width()
                processingScope.setVariable('%s_cellsize' % name, cellsize)

        layers = dataobjects.getRasterLayers()
        for layer in layers:
            for i in range(layer.bandCount()):
                stats = layer.dataProvider().bandStatistics(i + 1)
                processingScope.setVariable('%s_band%i_avg' % (name, i + 1),
                                            stats.mean)
                processingScope.setVariable('%s_band%i_stddev' % (name, i + 1),
                                            stats.stdDev)
                processingScope.setVariable('%s_band%i_min' % (name, i + 1),
                                            stats.minimumValue)
                processingScope.setVariable('%s_band%i_max' % (name, i + 1),
                                            stats.maximumValue)

        extent = iface.mapCanvas().extent()
        processingScope.setVariable('canvasextent_minx', extent.xMinimum())
        processingScope.setVariable('canvasextent_miny', extent.yMinimum())
        processingScope.setVariable('canvasextent_maxx', extent.xMaximum())
        processingScope.setVariable('canvasextent_maxy', extent.yMaximum())

        extent = iface.mapCanvas().fullExtent()
        processingScope.setVariable('fullextent_minx', extent.xMinimum())
        processingScope.setVariable('fullextent_miny', extent.yMinimum())
        processingScope.setVariable('fullextent_maxx', extent.xMaximum())
        processingScope.setVariable('fullextent_maxy', extent.yMaximum())
        context.appendScope(processingScope)
        return context
示例#22
0
    def getWidgetFromParameter(self, param):
        """
        Overload for custom Qwidget(Panel) from Parameter
        return item : Qwidget(Panel)
        """

        if param.name in ["INPUTS_MATRIX"]:
            
            options = dataobjects.getRasterLayers(sorting=False)
            opts = [self.getExtendedLayerName(opt) for opt in options]
            item = OrderedMultipleInputPanel(opts)

        else:
            # == default Wigdet from Parameter, i.e. use parent method
            item = ParametersPanel.getWidgetFromParameter(self,param)

        return item
示例#23
0
 def setValue(self, obj):
     self.exported = None
     if obj is None:
         if self.optional:
             self.value = None
             return True
         else:
             return False
     if isinstance(obj, QgsRasterLayer):
         self.value = unicode(obj.dataProvider().dataSourceUri())
         return True
     else:
         self.value = unicode(obj)
         layers = dataobjects.getRasterLayers()
         for layer in layers:
             if layer.name() == self.value:
                 self.value = unicode(layer.dataProvider().dataSourceUri())
                 return True
         return os.path.exists(self.value)
示例#24
0
 def createWidget(self):
     if self.dialogType == DIALOG_STANDARD:
         layers = dataobjects.getRasterLayers(sorting=False)
         options = {}
         for lyr in layers:
             for n in range(lyr.bandCount()):
                 name = '{:s}@{:d}'.format(lyr.name(), n + 1)
                 options[name] = name
         return self._panel(options)
     elif self.dialogType == DIALOG_BATCH:
         return QLineEdit()
     else:
         layers = self.dialog.getAvailableValuesOfType(
             ParameterRaster, OutputRaster)
         options = {
             self.dialog.resolveValueDescription(lyr): "{}@1".format(lyr)
             for lyr in layers
         }
         return self._panel(options)
示例#25
0
文件: wrappers.py 项目: mterente/QGIS
 def createWidget(self):
     if self.dialogType == DIALOG_STANDARD:
         if self.param.datatype == dataobjects.TYPE_FILE:
             return MultipleInputPanel(datatype=dataobjects.TYPE_FILE)
         else:
             if self.param.datatype == dataobjects.TYPE_RASTER:
                 options = dataobjects.getRasterLayers(sorting=False)
             elif self.param.datatype == dataobjects.TYPE_VECTOR_ANY:
                 options = dataobjects.getVectorLayers(sorting=False)
             else:
                 options = dataobjects.getVectorLayers([self.param.datatype], sorting=False)
             opts = [getExtendedLayerName(opt) for opt in options]
             return MultipleInputPanel(opts)
     elif self.dialogType == DIALOG_BATCH:
         widget = BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog)
         widget.valueChanged.connect(lambda: self.widgetValueHasChanged.emit(self))
         return widget
     else:
         options = [self.dialog.resolveValueDescription(opt) for opt in self._getOptions()]
         return MultipleInputPanel(options)
示例#26
0
 def value(self):
     if self.dialogType == DIALOG_STANDARD:
         if self.param.datatype == dataobjects.TYPE_FILE:
             return self.param.setValue(self.widget.selectedoptions)
         else:
             if self.param.datatype == dataobjects.TYPE_RASTER:
                 options = dataobjects.getRasterLayers(sorting=False)
             elif self.param.datatype == dataobjects.TYPE_VECTOR_ANY:
                 options = dataobjects.getVectorLayers(sorting=False)
             else:
                 options = dataobjects.getVectorLayers([self.param.datatype], sorting=False)
             return [options[i] for i in self.widget.selectedoptions]
     elif self.dialogType == DIALOG_BATCH:
         return self.widget.getText()
     else:
         options = self._getOptions()
         values = [options[i] for i in self.widget.selectedoptions]
         if len(values) == 0 and not self.param.optional:
             raise InvalidParameterValue()
         return values
示例#27
0
 def createWidget(self):
     if self.dialogType == DIALOG_STANDARD:
         layers = dataobjects.getRasterLayers()
         items = []
         if self.param.optional:
             items.append((self.NOT_SELECTED, None))
         for layer in layers:
             items.append((getExtendedLayerName(layer), layer))
         return InputLayerSelectorPanel(items, self.param)
     elif self.dialogType == DIALOG_BATCH:
         return BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog)
     else:
         widget = QComboBox()
         widget.setEditable(True)
         files = self.dialog.getAvailableValuesOfType(ParameterRaster, OutputRaster)
         for f in files:
             widget.addItem(self.dialog.resolveValueDescription(f), f)
         if self.param.optional:
             widget.setEditText("")
         return widget
示例#28
0
 def setParamValue(self, param, widget, alg=None):
     if isinstance(param, ParameterRaster):
         return param.setValue(widget.getValue())
     elif isinstance(param, (ParameterVector, ParameterTable)):
         try:
             return param.setValue(widget.itemData(widget.currentIndex()))
         except:
             return param.setValue(widget.getValue())
     elif isinstance(param, ParameterBoolean):
         return param.setValue(widget.isChecked())
     elif isinstance(param, ParameterSelection):
         return param.setValue(widget.currentIndex())
     elif isinstance(param, ParameterFixedTable):
         return param.setValue(widget.table)
     elif isinstance(param, ParameterRange):
         return param.setValue(widget.getValue())
     if isinstance(param, ParameterTableField):
         if param.optional and widget.currentIndex() == 0:
             return param.setValue(None)
         return param.setValue(widget.currentText())
     elif isinstance(param, ParameterMultipleInput):
         if param.datatype == ParameterMultipleInput.TYPE_FILE:
             return param.setValue(widget.selectedoptions)
         else:
             if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                 options = dataobjects.getVectorLayers(sorting=False)
             else:
                 options = dataobjects.getRasterLayers(sorting=False)
             return param.setValue([options[i] for i in widget.selectedoptions])
     elif isinstance(param, (ParameterNumber, ParameterFile, ParameterCrs,
                     ParameterExtent)):
         return param.setValue(widget.getValue())
     elif isinstance(param, ParameterString):
         if param.multiline:
             return param.setValue(unicode(widget.toPlainText()))
         else:
             return param.setValue(unicode(widget.text()))
     elif isinstance(param, ParameterGeometryPredicate):
         return param.setValue(widget.value())
     else:
         return param.setValue(unicode(widget.text()))
示例#29
0
 def setParamValue(self, param, widget, alg=None):
     if isinstance(param, ParameterRaster):
         return param.setValue(widget.getValue())
     elif isinstance(param, (ParameterVector, ParameterTable)):
         try:
             return param.setValue(widget.itemData(widget.currentIndex()))
         except:
             return param.setValue(widget.getValue())
     elif isinstance(param, ParameterBoolean):
         return param.setValue(widget.isChecked())
     elif isinstance(param, ParameterSelection):
         return param.setValue(widget.currentIndex())
     elif isinstance(param, ParameterFixedTable):
         return param.setValue(widget.table)
     elif isinstance(param, ParameterRange):
         return param.setValue(widget.getValue())
     if isinstance(param, ParameterTableField):
         if param.optional and widget.currentIndex() == 0:
             return param.setValue(None)
         return param.setValue(widget.currentText())
     elif isinstance(param, ParameterMultipleInput):
         if param.datatype == ParameterMultipleInput.TYPE_FILE:
             return param.setValue(widget.selectedoptions)
         else:
             if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                 options = dataobjects.getVectorLayers(sorting=False)
             else:
                 options = dataobjects.getRasterLayers(sorting=False)
             return param.setValue(
                 [options[i] for i in widget.selectedoptions])
     elif isinstance(
             param,
         (ParameterNumber, ParameterFile, ParameterCrs, ParameterExtent)):
         return param.setValue(widget.getValue())
     elif isinstance(param, ParameterString):
         if param.multiline:
             return param.setValue(unicode(widget.toPlainText()))
         else:
             return param.setValue(unicode(widget.text()))
     else:
         return param.setValue(unicode(widget.text()))
示例#30
0
 def getAsString(self, value):
     if self.datatype == ParameterMultipleInput.TYPE_RASTER:
         if isinstance(value, QgsRasterLayer):
             return unicode(value.dataProvider().dataSourceUri())
         else:
             s = unicode(value)
             layers = dataobjects.getRasterLayers()
             for layer in layers:
                 if layer.name() == s:
                     return unicode(layer.dataProvider().dataSourceUri())
             return s
     else:
         if isinstance(value, QgsVectorLayer):
             return unicode(value.source())
         else:
             s = unicode(value)
             layers = dataobjects.getVectorLayers(self.datatype)
             for layer in layers:
                 if layer.name() == s:
                     return unicode(layer.source())
             return s
 def getAsString(self, value):
     if self.datatype == ParameterMultipleInput.TYPE_RASTER:
         if isinstance(value, QgsRasterLayer):
             return unicode(value.dataProvider().dataSourceUri())
         else:
             s = unicode(value)
             layers = dataobjects.getRasterLayers()
             for layer in layers:
                 if layer.name() == s:
                     return unicode(layer.dataProvider().dataSourceUri())
             return s
     else:
         if isinstance(value, QgsVectorLayer):
             return unicode(value.source())
         else:
             s = unicode(value)
             layers = dataobjects.getVectorLayers(self.datatype)
             for layer in layers:
                 if layer.name() == s:
                     return unicode(layer.source())
             return s
示例#32
0
    def expressionContext(self):
        context = QgsExpressionContext()
        context.appendScope(QgsExpressionContextUtils.globalScope())
        context.appendScope(QgsExpressionContextUtils.projectScope())
        processingScope = QgsExpressionContextScope()
        layers = dataobjects.getAllLayers()
        for layer in layers:
            name = layer.name()
            processingScope.setVariable('%s_minx' % name, layer.extent().xMinimum())
            processingScope.setVariable('%s_miny' % name, layer.extent().yMinimum())
            processingScope.setVariable('%s_maxx' % name, layer.extent().xMaximum())
            processingScope.setVariable('%s_maxy' % name, layer.extent().yMaximum())
            if isinstance(layer, QgsRasterLayer):
                cellsize = (layer.extent().xMaximum()
                            - layer.extent().xMinimum()) / layer.width()
                processingScope.setVariable('%s_cellsize' % name, cellsize)

        layers = dataobjects.getRasterLayers()
        for layer in layers:
            for i in range(layer.bandCount()):
                stats = layer.dataProvider().bandStatistics(i + 1)
                processingScope.setVariable('%s_band%i_avg' % (name, i + 1), stats.mean)
                processingScope.setVariable('%s_band%i_stddev' % (name, i + 1), stats.stdDev)
                processingScope.setVariable('%s_band%i_min' % (name, i + 1), stats.minimumValue)
                processingScope.setVariable('%s_band%i_max' % (name, i + 1), stats.maximumValue)

        extent = iface.mapCanvas().extent()
        processingScope.setVariable('canvasextent_minx', extent.xMinimum())
        processingScope.setVariable('canvasextent_miny', extent.yMinimum())
        processingScope.setVariable('canvasextent_maxx', extent.xMaximum())
        processingScope.setVariable('canvasextent_maxy', extent.yMaximum())

        extent = iface.mapCanvas().fullExtent()
        processingScope.setVariable('fullextent_minx', extent.xMinimum())
        processingScope.setVariable('fullextent_miny', extent.yMinimum())
        processingScope.setVariable('fullextent_maxx', extent.xMaximum())
        processingScope.setVariable('fullextent_maxy', extent.yMaximum())
        context.appendScope(processingScope)
        return context
示例#33
0
 def setParamValue(self, param, widget):
     if isinstance(param, ParameterRaster):
         return param.setValue(widget.getValue())
     elif isinstance(param, (ParameterVector, ParameterTable)):
         try:
             return param.setValue(widget.itemData(widget.currentIndex()))
         except:
             return param.setValue(widget.getValue())
     elif isinstance(param, ParameterBoolean):
         return param.setValue(widget.currentIndex() == 0)
     elif isinstance(param, ParameterSelection):
         return param.setValue(widget.currentIndex())
     elif isinstance(param, ParameterFixedTable):
         return param.setValue(widget.table)
     elif isinstance(param, ParameterRange):
         return param.setValue(widget.getValue())
     if isinstance(param, ParameterTableField):
         return param.setValue(widget.currentText())
     elif isinstance(param, ParameterMultipleInput):
         if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
             options = dataobjects.getVectorLayers()
         else:
             options = dataobjects.getRasterLayers()
         value = []
         for index in widget.selectedoptions:
             value.append(options[index])
         return param.setValue(value)
     elif isinstance(
             param,
         (ParameterNumber, ParameterFile, ParameterCrs, ParameterExtent)):
         return param.setValue(widget.getValue())
     elif isinstance(param, ParameterString):
         if param.multiline:
             return param.setValue(unicode(widget.toPlainText()))
         else:
             return param.setValue(unicode(widget.text()))
     else:
         return param.setValue(unicode(widget.text()))
示例#34
0
 def setParamValue(self, param, widget):
     if isinstance(param, ParameterRaster):
         return param.setValue(widget.getValue())
     elif isinstance(param, (ParameterVector, ParameterTable)):
         try:
             return param.setValue(widget.itemData(widget.currentIndex()))
         except:
             return param.setValue(widget.getValue())
     elif isinstance(param, ParameterBoolean):
         return param.setValue(widget.currentIndex() == 0)
     elif isinstance(param, ParameterSelection):
         return param.setValue(widget.currentIndex())
     elif isinstance(param, ParameterFixedTable):
         return param.setValue(widget.table)
     elif isinstance(param, ParameterRange):
         return param.setValue(widget.getValue())
     if isinstance(param, ParameterTableField):
         return param.setValue(widget.currentText())
     elif isinstance(param, ParameterMultipleInput):
         if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
             options = dataobjects.getVectorLayers()
         else:
             options = dataobjects.getRasterLayers()
         value = []
         for index in widget.selectedoptions:
             value.append(options[index])
         return param.setValue(value)
     elif isinstance(param, (ParameterNumber, ParameterFile, ParameterCrs,
                     ParameterExtent)):
         return param.setValue(widget.getValue())
     elif isinstance(param, ParameterString):
         if param.multiline:
             return param.setValue(unicode(widget.toPlainText()))
         else:
             return param.setValue(unicode(widget.text()))
     else:
         return param.setValue(unicode(widget.text()))
示例#35
0
    def getAsString(self, value):
        if self.datatype == dataobjects.TYPE_RASTER:
            if isinstance(value, QgsRasterLayer):
                return str(value.dataProvider().dataSourceUri())
            else:
                s = str(value)
                layers = dataobjects.getRasterLayers()
                for layer in layers:
                    if layer.name() == s:
                        return str(layer.dataProvider().dataSourceUri())
                return s

        if self.datatype == dataobjects.TYPE_FILE:
            return str(value)
        else:
            if isinstance(value, QgsVectorLayer):
                return str(value.source())
            else:
                s = str(value)
                layers = dataobjects.getVectorLayers([self.datatype])
                for layer in layers:
                    if layer.name() == s:
                        return str(layer.source())
                return s
示例#36
0
    def getWidgetFromParameter(self, param):
        if isinstance(param, ParameterRaster):
            layers = dataobjects.getRasterLayers()
            items = []
            if param.optional:
                items.append((self.NOT_SELECTED, None))
            for layer in layers:
                items.append((self.getExtendedLayerName(layer), layer))
            item = InputLayerSelectorPanel(items)
        elif isinstance(param, ParameterVector):
            if self.somethingDependsOnThisParameter(param) \
                or self.alg.allowOnlyOpenedLayers:
                item = QtGui.QComboBox()
                layers = dataobjects.getVectorLayers(param.shapetype)
                if param.optional:
                    item.addItem(self.NOT_SELECTED, None)
                for layer in layers:
                    item.addItem(self.getExtendedLayerName(layer), layer)
                item.currentIndexChanged.connect(self.updateDependentFields)
                item.name = param.name
            else:
                layers = dataobjects.getVectorLayers(param.shapetype)
                items = []
                if param.optional:
                    items.append((self.NOT_SELECTED, None))
                for layer in layers:
                    items.append((self.getExtendedLayerName(layer), layer))
                item = InputLayerSelectorPanel(items)
        elif isinstance(param, ParameterTable):
            if self.somethingDependsOnThisParameter(param):
                item = QtGui.QComboBox()
                layers = dataobjects.getTables()
                if param.optional:
                    item.addItem(self.NOT_SELECTED, None)
                for layer in layers:
                    item.addItem(layer.name(), layer)
                item.currentIndexChanged.connect(self.updateDependentFields)
                item.name = param.name
            else:
                layers = dataobjects.getTables()
                items = []
                if param.optional:
                    items.append((self.NOT_SELECTED, None))
                for layer in layers:
                    items.append((layer.name(), layer))
                item = InputLayerSelectorPanel(items)
        elif isinstance(param, ParameterBoolean):
            item = QtGui.QComboBox()
            item.addItem('Yes')
            item.addItem('No')
            if param.default:
                item.setCurrentIndex(0)
            else:
                item.setCurrentIndex(1)
        elif isinstance(param, ParameterTableField):
            item = QtGui.QComboBox()
            if param.parent in self.dependentItems:
                items = self.dependentItems[param.parent]
            else:
                items = []
                self.dependentItems[param.parent] = items
            items.append(param.name)
            parent = self.alg.getParameterFromName(param.parent)
            if isinstance(parent, ParameterVector):
                layers = dataobjects.getVectorLayers(parent.shapetype)
            else:
                layers = dataobjects.getTables()
            if len(layers) > 0:
                item.addItems(self.getFields(layers[0], param.datatype))
        elif isinstance(param, ParameterSelection):
            item = QtGui.QComboBox()
            item.addItems(param.options)
            item.setCurrentIndex(param.default)
        elif isinstance(param, ParameterFixedTable):
            item = FixedTablePanel(param)
        elif isinstance(param, ParameterRange):
            item = RangePanel(param)
        elif isinstance(param, ParameterFile):
            item = FileSelectionPanel(param.isFolder)
        elif isinstance(param, ParameterMultipleInput):
            if param.datatype == ParameterMultipleInput.TYPE_RASTER:
                options = dataobjects.getRasterLayers()
            elif param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                options = dataobjects.getVectorLayers()
            else:
                options = dataobjects.getVectorLayers([param.datatype])
            opts = []
            for opt in options:
                opts.append(self.getExtendedLayerName(opt))
            item = MultipleInputPanel(opts)
        elif isinstance(param, ParameterNumber):
            item = NumberInputPanel(param.default, param.min, param.max,
                                    param.isInteger)
        elif isinstance(param, ParameterExtent):
            item = ExtentSelectionPanel(self.parent, self.alg, param.default)
        elif isinstance(param, ParameterCrs):
            item = CrsSelectionPanel(param.default)
        elif isinstance(param, ParameterString):
            if param.multiline:
                verticalLayout = QtGui.QVBoxLayout()
                verticalLayout.setSizeConstraint(
                    QtGui.QLayout.SetDefaultConstraint)
                textEdit = QtGui.QPlainTextEdit()
                textEdit.setPlainText(param.default)
                verticalLayout.addWidget(textEdit)
                item = textEdit
            else:
                item = QtGui.QLineEdit()
                item.setText(str(param.default))
        else:
            item = QtGui.QLineEdit()
            item.setText(str(param.default))

        return item
示例#37
0
    def getWidgetFromParameter(self, param):
        # TODO Create Parameter widget class that holds the logic
        # for creating a widget that belongs to the parameter.
        if isinstance(param, ParameterRaster):
            layers = dataobjects.getRasterLayers()
            items = []
            if param.optional:
                items.append((self.NOT_SELECTED, None))
            for layer in layers:
                items.append((self.getExtendedLayerName(layer), layer))
            item = InputLayerSelectorPanel(items, param)
        elif isinstance(param, ParameterVector):
            if self.somethingDependsOnThisParameter(
                    param) or self.alg.allowOnlyOpenedLayers:
                item = QComboBox()
                layers = dataobjects.getVectorLayers(param.shapetype)
                if param.optional:
                    item.addItem(self.NOT_SELECTED, None)
                for layer in layers:
                    item.addItem(self.getExtendedLayerName(layer), layer)
                item.currentIndexChanged.connect(self.updateDependentFields)
                item.name = param.name
            else:
                layers = dataobjects.getVectorLayers(param.shapetype)
                items = []
                if param.optional:
                    items.append((self.NOT_SELECTED, None))
                for layer in layers:
                    items.append((self.getExtendedLayerName(layer), layer))
                # if already set, put first in list
                for i, (name, layer) in enumerate(items):
                    if layer and layer.source() == param.value:
                        items.insert(0, items.pop(i))
                item = InputLayerSelectorPanel(items, param)
        elif isinstance(param, ParameterTable):
            if self.somethingDependsOnThisParameter(param):
                item = QComboBox()
                layers = dataobjects.getTables()
                if param.optional:
                    item.addItem(self.NOT_SELECTED, None)
                for layer in layers:
                    item.addItem(layer.name(), layer)
                item.currentIndexChanged.connect(self.updateDependentFields)
                item.name = param.name
            else:
                layers = dataobjects.getTables()
                items = []
                if param.optional:
                    items.append((self.NOT_SELECTED, None))
                for layer in layers:
                    items.append((layer.name(), layer))
                # if already set, put first in list
                for i, (name, layer) in enumerate(items):
                    if layer and layer.source() == param.value:
                        items.insert(0, items.pop(i))
                item = InputLayerSelectorPanel(items, param)
        elif isinstance(param, ParameterBoolean):
            item = QCheckBox()
            if param.default:
                item.setChecked(True)
            else:
                item.setChecked(False)
        elif isinstance(param, ParameterTableField):
            item = QComboBox()
            if param.parent in self.dependentItems:
                items = self.dependentItems[param.parent]
            else:
                items = []
                self.dependentItems[param.parent] = items
            items.append(param.name)
            parent = self.alg.getParameterFromName(param.parent)
            if isinstance(parent, ParameterVector):
                layers = dataobjects.getVectorLayers(parent.shapetype)
            else:
                layers = dataobjects.getTables()
            if len(layers) > 0:
                if param.optional:
                    item.addItem(self.tr("[not set]"))
                item.addItems(self.getFields(layers[0], param.datatype))
        elif isinstance(param, ParameterSelection):
            item = QComboBox()
            item.addItems(param.options)
            item.setCurrentIndex(param.default)
        elif isinstance(param, ParameterFixedTable):
            item = FixedTablePanel(param)
        elif isinstance(param, ParameterRange):
            item = RangePanel(param)
        elif isinstance(param, ParameterFile):
            item = FileSelectionPanel(param.isFolder, param.ext)
        elif isinstance(param, ParameterMultipleInput):
            if param.datatype == ParameterMultipleInput.TYPE_FILE:
                item = MultipleFileInputPanel()
            else:
                if param.datatype == ParameterMultipleInput.TYPE_RASTER:
                    options = dataobjects.getRasterLayers(sorting=False)
                elif param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                    options = dataobjects.getVectorLayers(sorting=False)
                else:
                    options = dataobjects.getVectorLayers([param.datatype],
                                                          sorting=False)
                opts = []
                for opt in options:
                    opts.append(self.getExtendedLayerName(opt))
                item = MultipleInputPanel(opts)
        elif isinstance(param, ParameterNumber):
            item = NumberInputPanel(param.default, param.min, param.max,
                                    param.isInteger)
        elif isinstance(param, ParameterExtent):
            item = ExtentSelectionPanel(self.parent, self.alg, param.default)
        elif isinstance(param, ParameterCrs):
            item = CrsSelectionPanel(param.default)
        elif isinstance(param, ParameterString):
            if param.multiline:
                verticalLayout = QVBoxLayout()
                verticalLayout.setSizeConstraint(QLayout.SetDefaultConstraint)
                textEdit = QPlainTextEdit()
                textEdit.setPlainText(param.default)
                verticalLayout.addWidget(textEdit)
                item = textEdit
            else:
                item = QLineEdit()
                item.setText(str(param.default))
        else:
            item = QLineEdit()
            item.setText(str(param.default))

        return item
示例#38
0
    def getWidgetFromParameter(self, param):
        # TODO Create Parameter widget class that holds the logic 
        # for creating a widget that belongs to the parameter.
        if isinstance(param, ParameterRaster):
            layers = dataobjects.getRasterLayers()
            items = []
            if param.optional:
                items.append((self.NOT_SELECTED, None))
            for layer in layers:
                items.append((self.getExtendedLayerName(layer), layer))
            item = InputLayerSelectorPanel(items)
        elif isinstance(param, ParameterVector):
            if self.somethingDependsOnThisParameter(param) \
                or self.alg.allowOnlyOpenedLayers:
                item = QtGui.QComboBox()
                layers = dataobjects.getVectorLayers(param.shapetype)
                if param.optional:
                    item.addItem(self.NOT_SELECTED, None)
                for layer in layers:
                    item.addItem(self.getExtendedLayerName(layer), layer)
                item.currentIndexChanged.connect(self.updateDependentFields)
                item.name = param.name
            else:
                layers = dataobjects.getVectorLayers(param.shapetype)
                items = []
                if param.optional:
                    items.append((self.NOT_SELECTED, None))
                for layer in layers:
                    items.append((self.getExtendedLayerName(layer), layer))
                item = InputLayerSelectorPanel(items)
        elif isinstance(param, ParameterTable):
            if self.somethingDependsOnThisParameter(param):
                item = QtGui.QComboBox()
                layers = dataobjects.getTables()
                if param.optional:
                    item.addItem(self.NOT_SELECTED, None)
                for layer in layers:
                    item.addItem(layer.name(), layer)
                item.currentIndexChanged.connect(self.updateDependentFields)
                item.name = param.name
            else:
                layers = dataobjects.getTables()
                items = []
                if param.optional:
                    items.append((self.NOT_SELECTED, None))
                for layer in layers:
                    items.append((layer.name(), layer))
                item = InputLayerSelectorPanel(items)
        elif isinstance(param, ParameterBoolean):
            item = QtGui.QComboBox()
            item.addItem('Yes')
            item.addItem('No')
            if param.default:
                item.setCurrentIndex(0)
            else:
                item.setCurrentIndex(1)
        elif isinstance(param, ParameterTableField):
            item = QtGui.QComboBox()
            if param.parent in self.dependentItems:
                items = self.dependentItems[param.parent]
            else:
                items = []
                self.dependentItems[param.parent] = items
            items.append(param.name)
            parent = self.alg.getParameterFromName(param.parent)
            if isinstance(parent, ParameterVector):
                layers = dataobjects.getVectorLayers(parent.shapetype)
            else:
                layers = dataobjects.getTables()
            if len(layers) > 0:
                item.addItems(self.getFields(layers[0], param.datatype))
        elif isinstance(param, ParameterSelection):
            item = QtGui.QComboBox()
            item.addItems(param.options)
            item.setCurrentIndex(param.default)
        elif isinstance(param, ParameterFixedTable):
            item = FixedTablePanel(param)
        elif isinstance(param, ParameterRange):
            item = RangePanel(param)
        elif isinstance(param, ParameterFile):
            item = FileSelectionPanel(param.isFolder)
        elif isinstance(param, ParameterMultipleInput):
            if param.datatype == ParameterMultipleInput.TYPE_RASTER:
                options = dataobjects.getRasterLayers()
            elif param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                options = dataobjects.getVectorLayers()
            else:
                options = dataobjects.getVectorLayers([param.datatype])
            opts = []
            for opt in options:
                opts.append(self.getExtendedLayerName(opt))
            item = MultipleInputPanel(opts)
        elif isinstance(param, ParameterNumber):
            item = NumberInputPanel(param.default, param.min, param.max,
                                    param.isInteger)
        elif isinstance(param, ParameterExtent):
            item = ExtentSelectionPanel(self.parent, self.alg, param.default)
        elif isinstance(param, ParameterCrs):
            item = CrsSelectionPanel(param.default)
        elif isinstance(param, ParameterString):
            if param.multiline:
                verticalLayout = QtGui.QVBoxLayout()
                verticalLayout.setSizeConstraint(
                        QtGui.QLayout.SetDefaultConstraint)
                textEdit = QtGui.QPlainTextEdit()
                textEdit.setPlainText(param.default)
                verticalLayout.addWidget(textEdit)
                item = textEdit
            else:
                item = QtGui.QLineEdit()
                item.setText(str(param.default))
        else:
            item = QtGui.QLineEdit()
            item.setText(str(param.default))

        return item
示例#39
0
    def getWidgetFromParameter(self, param):
        # TODO Create Parameter widget class that holds the logic
        # for creating a widget that belongs to the parameter.
        if isinstance(param, ParameterRaster):
            layers = dataobjects.getRasterLayers()
            items = []
            if param.optional:
                items.append((self.NOT_SELECTED, None))
            for layer in layers:
                items.append((self.getExtendedLayerName(layer), layer))
            item = InputLayerSelectorPanel(items, param)
        elif isinstance(param, ParameterVector):
            if self.somethingDependsOnThisParameter(param) or self.alg.allowOnlyOpenedLayers:
                item = QComboBox()
                layers = dataobjects.getVectorLayers(param.shapetype)
                layers.sort(key=lambda lay: lay.name())
                if param.optional:
                    item.addItem(self.NOT_SELECTED, None)
                for layer in layers:
                    item.addItem(self.getExtendedLayerName(layer), layer)
                item.currentIndexChanged.connect(self.updateDependentFields)
                item.name = param.name
            else:
                layers = dataobjects.getVectorLayers(param.shapetype)
                items = []
                if param.optional:
                    items.append((self.NOT_SELECTED, None))
                for layer in layers:
                    items.append((self.getExtendedLayerName(layer), layer))
                # if already set, put first in list
                for i,(name,layer) in enumerate(items):
                    if layer and layer.source() == param.value:
                        items.insert(0, items.pop(i))
                item = InputLayerSelectorPanel(items, param)
        elif isinstance(param, ParameterTable):
            if self.somethingDependsOnThisParameter(param):
                item = QComboBox()
                layers = dataobjects.getTables()
                if param.optional:
                    item.addItem(self.NOT_SELECTED, None)
                for layer in layers:
                    item.addItem(layer.name(), layer)
                item.currentIndexChanged.connect(self.updateDependentFields)
                item.name = param.name
            else:
                layers = dataobjects.getTables()
                items = []
                if param.optional:
                    items.append((self.NOT_SELECTED, None))
                for layer in layers:
                    items.append((layer.name(), layer))
                # if already set, put first in list
                for i,(name,layer) in enumerate(items):
                    if layer and layer.source() == param.value:
                        items.insert(0, items.pop(i))
                item = InputLayerSelectorPanel(items, param)
        elif isinstance(param, ParameterBoolean):
            item = QCheckBox()
            if param.default:
                item.setChecked(True)
            else:
                item.setChecked(False)
        elif isinstance(param, ParameterTableField):
            item = QComboBox()
            if param.parent in self.dependentItems:
                items = self.dependentItems[param.parent]
            else:
                items = []
                self.dependentItems[param.parent] = items
            items.append(param.name)
            parent = self.alg.getParameterFromName(param.parent)
            if isinstance(parent, ParameterVector):
                layers = dataobjects.getVectorLayers(parent.shapetype)
            else:
                layers = dataobjects.getTables()
            if len(layers) > 0:
                if param.optional:
                    item.addItem(self.tr('[not set]'))
                item.addItems(self.getFields(layers[0], param.datatype))
        elif isinstance(param, ParameterSelection):
            item = QComboBox()
            item.addItems(param.options)
            item.setCurrentIndex(param.default)
        elif isinstance(param, ParameterFixedTable):
            item = FixedTablePanel(param)
        elif isinstance(param, ParameterRange):
            item = RangePanel(param)
        elif isinstance(param, ParameterFile):
            item = FileSelectionPanel(param.isFolder, param.ext)
        elif isinstance(param, ParameterMultipleInput):
            if param.datatype == ParameterMultipleInput.TYPE_FILE:
                item = MultipleInputPanel(datatype=ParameterMultipleInput.TYPE_FILE)
            else:
                if param.datatype == ParameterMultipleInput.TYPE_RASTER:
                    options = dataobjects.getRasterLayers(sorting=False)
                elif param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                    options = dataobjects.getVectorLayers(sorting=False)
                else:
                    options = dataobjects.getVectorLayers([param.datatype], sorting=False)
                opts = []
                for opt in options:
                    opts.append(self.getExtendedLayerName(opt))
                item = MultipleInputPanel(opts)
        elif isinstance(param, ParameterNumber):
            item = NumberInputPanel(param.default, param.min, param.max,
                                    param.isInteger)
        elif isinstance(param, ParameterExtent):
            item = ExtentSelectionPanel(self.parent, self.alg, param.default)
        elif isinstance(param, ParameterCrs):
            item = CrsSelectionPanel(param.default)
        elif isinstance(param, ParameterString):
            if param.multiline:
                verticalLayout = QVBoxLayout()
                verticalLayout.setSizeConstraint(
                    QLayout.SetDefaultConstraint)
                textEdit = QPlainTextEdit()
                textEdit.setPlainText(param.default)
                verticalLayout.addWidget(textEdit)
                item = textEdit
            else:
                item = QLineEdit()
                item.setText(str(param.default))
        elif isinstance(param, ParameterGeometryPredicate):
            item = GeometryPredicateSelectionPanel(param.enabledPredicates)
            if param.left:
                widget = self.valueItems[param.left]
                if isinstance(widget, InputLayerSelectorPanel):
                    widget = widget.cmbText
                widget.currentIndexChanged.connect(item.onLeftLayerChange)
                item.leftLayer = widget.itemData(widget.currentIndex())
            if param.right:
                widget = self.valueItems[param.right]
                if isinstance(widget, InputLayerSelectorPanel):
                    widget = widget.cmbText
                widget.currentIndexChanged.connect(item.onRightLayerChange)
                item.rightLayer = widget.itemData(widget.currentIndex())
            item.updatePredicates()
            item.setValue(param.default)
        else:
            item = QLineEdit()
            item.setText(str(param.default))

        return item
示例#40
0
    def fillTree(self):
        layersItem = QTreeWidgetItem()
        layersItem.setText(0, self.tr('Values from data layers extents'))
        self.treeValues.addTopLevelItem(layersItem)
        layers = dataobjects.getAllLayers()
        for layer in layers:
            layerItem = QTreeWidgetItem()
            layerItem.setText(0, unicode(layer.name()))
            layerItem.addChild(TreeValueItem(self.tr('Min X'),
                               layer.extent().xMinimum()))
            layerItem.addChild(TreeValueItem(self.tr('Max X'),
                               layer.extent().xMaximum()))
            layerItem.addChild(TreeValueItem(self.tr('Min Y'),
                               layer.extent().yMinimum()))
            layerItem.addChild(TreeValueItem(self.tr('Max Y'),
                               layer.extent().yMaximum()))
            if isinstance(layer, QgsRasterLayer):
                cellsize = (layer.extent().xMaximum()
                            - layer.extent().xMinimum()) / layer.width()
                layerItem.addChild(TreeValueItem(self.tr('Cellsize'),
                                                 cellsize))
            layersItem.addChild(layerItem)

        layersItem = QTreeWidgetItem()
        layersItem.setText(0, self.tr('Values from raster layers statistics'))
        self.treeValues.addTopLevelItem(layersItem)
        layers = dataobjects.getRasterLayers()
        for layer in layers:
            for i in range(layer.bandCount()):
                stats = layer.dataProvider().bandStatistics(i + 1)
                layerItem = QTreeWidgetItem()
                layerItem.setText(0, unicode(layer.name()))
                layerItem.addChild(TreeValueItem(self.tr('Mean'), stats.mean))
                layerItem.addChild(TreeValueItem(self.tr('Std. deviation'),
                                   stats.stdDev))
                layerItem.addChild(TreeValueItem(self.tr('Max value'),
                                   stats.maximumValue))
                layerItem.addChild(TreeValueItem(self.tr('Min value'),
                                   stats.minimumValue))
                layersItem.addChild(layerItem)

        canvasItem = QTreeWidgetItem()
        canvasItem.setText(0, self.tr('Values from QGIS map canvas'))
        self.treeValues.addTopLevelItem(canvasItem)
        extent = iface.mapCanvas().extent()
        extentItem = QTreeWidgetItem()
        extentItem.setText(0, self.tr('Current extent'))
        extentItem.addChild(TreeValueItem(self.tr('Min X'), extent.xMinimum()))
        extentItem.addChild(TreeValueItem(self.tr('Max X'), extent.xMaximum()))
        extentItem.addChild(TreeValueItem(self.tr('Min Y'), extent.yMinimum()))
        extentItem.addChild(TreeValueItem(self.tr('Max Y'), extent.yMaximum()))
        canvasItem.addChild(extentItem)

        extent = iface.mapCanvas().fullExtent()
        extentItem = QTreeWidgetItem()
        extentItem.setText(0,
                self.tr('Full extent of all layers in map canvas'))
        extentItem.addChild(TreeValueItem(self.tr('Min X'), extent.xMinimum()))
        extentItem.addChild(TreeValueItem(self.tr('Max X'), extent.xMaximum()))
        extentItem.addChild(TreeValueItem(self.tr('Min Y'), extent.yMinimum()))
        extentItem.addChild(TreeValueItem(self.tr('Max Y'), extent.yMaximum()))
        canvasItem.addChild(extentItem)
示例#41
0
    def fillTree(self):
        layersItem = QTreeWidgetItem()
        layersItem.setText(0, self.tr('Values from data layers extents'))
        self.treeValues.addTopLevelItem(layersItem)
        layers = dataobjects.getAllLayers()
        for layer in layers:
            layerItem = QTreeWidgetItem()
            layerItem.setText(0, unicode(layer.name()))
            layerItem.addChild(
                TreeValueItem(self.tr('Min X'),
                              layer.extent().xMinimum()))
            layerItem.addChild(
                TreeValueItem(self.tr('Max X'),
                              layer.extent().xMaximum()))
            layerItem.addChild(
                TreeValueItem(self.tr('Min Y'),
                              layer.extent().yMinimum()))
            layerItem.addChild(
                TreeValueItem(self.tr('Max Y'),
                              layer.extent().yMaximum()))
            if isinstance(layer, QgsRasterLayer):
                cellsize = (layer.extent().xMaximum() -
                            layer.extent().xMinimum()) / layer.width()
                layerItem.addChild(TreeValueItem(self.tr('Cellsize'),
                                                 cellsize))
            layersItem.addChild(layerItem)

        layersItem = QTreeWidgetItem()
        layersItem.setText(0, self.tr('Values from raster layers statistics'))
        self.treeValues.addTopLevelItem(layersItem)
        layers = dataobjects.getRasterLayers()
        for layer in layers:
            for i in range(layer.bandCount()):
                stats = layer.dataProvider().bandStatistics(i + 1)
                layerItem = QTreeWidgetItem()
                layerItem.setText(0, unicode(layer.name()))
                layerItem.addChild(TreeValueItem(self.tr('Mean'), stats.mean))
                layerItem.addChild(
                    TreeValueItem(self.tr('Std. deviation'), stats.stdDev))
                layerItem.addChild(
                    TreeValueItem(self.tr('Max value'), stats.maximumValue))
                layerItem.addChild(
                    TreeValueItem(self.tr('Min value'), stats.minimumValue))
                layersItem.addChild(layerItem)

        canvasItem = QTreeWidgetItem()
        canvasItem.setText(0, self.tr('Values from QGIS map canvas'))
        self.treeValues.addTopLevelItem(canvasItem)
        extent = interface.iface.mapCanvas().extent()
        extentItem = QTreeWidgetItem()
        extentItem.setText(0, self.tr('Current extent'))
        extentItem.addChild(TreeValueItem(self.tr('Min X'), extent.xMinimum()))
        extentItem.addChild(TreeValueItem(self.tr('Max X'), extent.xMaximum()))
        extentItem.addChild(TreeValueItem(self.tr('Min Y'), extent.yMinimum()))
        extentItem.addChild(TreeValueItem(self.tr('Max Y'), extent.yMaximum()))
        canvasItem.addChild(extentItem)

        extent = interface.iface.mapCanvas().fullExtent()
        extentItem = QTreeWidgetItem()
        extentItem.setText(0,
                           self.tr('Full extent of all layers in map canvas'))
        extentItem.addChild(TreeValueItem(self.tr('Min X'), extent.xMinimum()))
        extentItem.addChild(TreeValueItem(self.tr('Max X'), extent.xMaximum()))
        extentItem.addChild(TreeValueItem(self.tr('Min Y'), extent.yMinimum()))
        extentItem.addChild(TreeValueItem(self.tr('Max Y'), extent.yMaximum()))
        canvasItem.addChild(extentItem)