def createEditor( self, parent, options, index, ): setting = index.model().data(index, Qt.UserRole) if setting.valuetype == Setting.FOLDER: return FileDirectorySelector(parent) elif setting.valuetype == Setting.FILE: return FileDirectorySelector(parent, True) elif setting.valuetype == Setting.SELECTION: combo = QComboBox(parent) combo.addItems(setting.options) return combo else: value = self.convertValue(index.model().data(index, Qt.EditRole)) if isinstance(value, (int, long)): spnBox = QgsSpinBox(parent) spnBox.setRange(-999999999, 999999999) return spnBox elif isinstance(value, float): spnBox = QgsDoubleSpinBox(parent) spnBox.setRange(-999999999.999999, 999999999.999999) spnBox.setDecimals(6) return spnBox elif isinstance(value, (str, unicode)): return QLineEdit(parent)
def setTableContent(self): params = self._alg.parameters outputs = self._alg.outputs visibleParams = [p for p in params if not p.hidden] visibleOutputs = [p for o in outputs if not o.hidden] self.tableWidget.setRowCount(len(visibleParams) + len(visibleOutputs)) for i, param in visibleParams: item = QTableWidgetItem(param.description) item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setItem(i, 0, item) item = self.getWidgetFromParameter(param) self.valueItems[param.name] = item self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22) for i, output in visibleOutputs: item = QTableWidgetItem(output.description + '<' + output.__module__.split('.')[-1] + '>') item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setItem(i, 0, item) item = QLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.valueItems[output.name] = item self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22)
class FileDirectorySelector(QWidget): def __init__(self, parent=None, selectFile=False): QWidget.__init__(self, parent) # create gui self.btnSelect = QToolButton() self.btnSelect.setText(self.tr('...')) self.lineEdit = QLineEdit() self.hbl = QHBoxLayout() self.hbl.setMargin(0) self.hbl.setSpacing(0) self.hbl.addWidget(self.lineEdit) self.hbl.addWidget(self.btnSelect) self.setLayout(self.hbl) self.canFocusOut = False self.selectFile = selectFile self.setFocusPolicy(Qt.StrongFocus) self.btnSelect.clicked.connect(self.select) def select(self): lastDir = '' if not self.selectFile: selectedPath = QFileDialog.getExistingDirectory(None, self.tr('Select directory'), lastDir, QFileDialog.ShowDirsOnly) else: selectedPath = QFileDialog.getOpenFileName(None, self.tr('Select file'), lastDir, self.tr('All files (*.*)') ) if not selectedPath: return self.lineEdit.setText(selectedPath) self.canFocusOut = True def text(self): return self.lineEdit.text() def setText(self, value): self.lineEdit.setText(value)
def setupUi(self): self.valueItems = {} self.dependentItems = {} self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.infoText = QTextEdit() numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) text = self.tr( 'You can refer to model values in your formula, using ' 'single-letter variables, as follows:\n', 'CalculatorModelerParametersDialog') ichar = 97 if numbers: for number in numbers: text += chr(ichar) + '->' + self.resolveValueDescription( number) + '\n' ichar += 1 else: text += self.tr('\n - No numerical variables are available.', 'CalculatorModelerParametersDialog') self.infoText.setText(text) self.infoText.setEnabled(False) self.formulaText = QLineEdit() if hasattr(self.formulaText, 'setPlaceholderText'): self.formulaText.setPlaceholderText( self.tr('[Enter your formula here]', 'CalculatorModelerParametersDialog')) if self._algName is not None: alg = self.model.algs[self._algName] self.formulaText.setText(alg.params[FORMULA]) self.setWindowTitle( self.tr('Calculator', 'CalculatorModelerParametersDialog')) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(2) self.verticalLayout.setMargin(0) self.verticalLayout.addWidget(self.infoText) self.verticalLayout.addWidget(self.formulaText) self.verticalLayout.addWidget(self.buttonBox) self.setLayout(self.verticalLayout) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) QMetaObject.connectSlotsByName(self)
class FileDirectorySelector(QWidget): def __init__(self, parent=None, selectFile=False): QWidget.__init__(self, parent) # create gui self.btnSelect = QToolButton() self.btnSelect.setText(self.tr('...')) self.lineEdit = QLineEdit() self.hbl = QHBoxLayout() self.hbl.setMargin(0) self.hbl.setSpacing(0) self.hbl.addWidget(self.lineEdit) self.hbl.addWidget(self.btnSelect) self.setLayout(self.hbl) self.canFocusOut = False self.selectFile = selectFile self.setFocusPolicy(Qt.StrongFocus) self.btnSelect.clicked.connect(self.select) def select(self): lastDir = '' if not self.selectFile: selectedPath = QFileDialog.getExistingDirectory( None, self.tr('Select directory'), lastDir, QFileDialog.ShowDirsOnly) else: selectedPath = QFileDialog.getOpenFileName( None, self.tr('Select file'), lastDir, self.tr('All files (*.*)')) if not selectedPath: return self.lineEdit.setText(selectedPath) self.canFocusOut = True def text(self): return self.lineEdit.text() def setText(self, value): self.lineEdit.setText(value)
def __init__(self, param, row, col, panel): super(BatchInputSelectionPanel, self).__init__(None) self.param = param self.panel = panel self.table = self.panel.tblParameters self.row = row self.col = col self.horizontalLayout = QHBoxLayout(self) self.horizontalLayout.setSpacing(0) self.horizontalLayout.setMargin(0) self.text = QLineEdit() self.text.setMinimumWidth(300) self.text.setText('') self.text.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.horizontalLayout.addWidget(self.text) self.pushButton = QPushButton() self.pushButton.setText('...') self.pushButton.clicked.connect(self.showPopupMenu) self.horizontalLayout.addWidget(self.pushButton) self.setLayout(self.horizontalLayout)
def __init__(self, parent=None, selectFile=False): QWidget.__init__(self, parent) # create gui self.btnSelect = QToolButton() self.btnSelect.setText(self.tr('...')) self.lineEdit = QLineEdit() self.hbl = QHBoxLayout() self.hbl.setMargin(0) self.hbl.setSpacing(0) self.hbl.addWidget(self.lineEdit) self.hbl.addWidget(self.btnSelect) self.setLayout(self.hbl) self.canFocusOut = False self.selectFile = selectFile self.setFocusPolicy(Qt.StrongFocus) self.btnSelect.clicked.connect(self.select)
def getWidgetFromParameter(self, param, row, col): if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable, ParameterMultipleInput)): item = BatchInputSelectionPanel(param, row, col, self) elif isinstance(param, ParameterBoolean): item = QComboBox() item.addItem(self.tr('Yes')) item.addItem(self.tr('No')) if param.default: item.setCurrentIndex(0) else: item.setCurrentIndex(1) elif isinstance(param, ParameterSelection): item = QComboBox() item.addItems(param.options) elif isinstance(param, ParameterFixedTable): item = FixedTablePanel(param) elif isinstance(param, ParameterExtent): item = ExtentSelectionPanel(self.parent, self.alg, param.default) elif isinstance(param, ParameterPoint): item = PointSelectionPanel(self.parent, param.default) elif isinstance(param, ParameterCrs): item = CrsSelectionPanel(param.default) elif isinstance(param, ParameterFile): item = FileSelectionPanel(param.isFolder) elif isinstance(param, ParameterGeometryPredicate): item = GeometryPredicateSelectionPanel(param.enabledPredicates, rows=1) width = max(self.tblParameters.columnWidth(col), item.sizeHint().width()) self.tblParameters.setColumnWidth(col, width) else: item = QLineEdit() try: item.setText(unicode(param.default)) except: pass return item
def setupUi(self): self.valueItems = {} self.dependentItems = {} self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.infoText = QTextEdit() numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) text = self.tr('You can refer to model values in your formula, using ' 'single-letter variables, as follows:\n', 'CalculatorModelerParametersDialog') ichar = 97 if numbers: for number in numbers: text += chr(ichar) + '->' + self.resolveValueDescription(number) + '\n' ichar += 1 else: text += self.tr('\n - No numerical variables are available.', 'CalculatorModelerParametersDialog') self.infoText.setText(text) self.infoText.setEnabled(False) self.formulaText = QLineEdit() if hasattr(self.formulaText, 'setPlaceholderText'): self.formulaText.setPlaceholderText(self.tr('[Enter your formula here]', 'CalculatorModelerParametersDialog')) if self._algName is not None: alg = self.model.algs[self._algName] self.formulaText.setText(alg.params[FORMULA]) self.setWindowTitle(self.tr('Calculator', 'CalculatorModelerParametersDialog')) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(2) self.verticalLayout.setMargin(0) self.verticalLayout.addWidget(self.infoText) self.verticalLayout.addWidget(self.formulaText) self.verticalLayout.addWidget(self.buttonBox) self.setLayout(self.verticalLayout) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) QMetaObject.connectSlotsByName(self)
class BatchInputSelectionPanel(QWidget): def __init__(self, param, row, col, panel): super(BatchInputSelectionPanel, self).__init__(None) self.param = param self.panel = panel self.table = self.panel.tblParameters self.row = row self.col = col self.horizontalLayout = QHBoxLayout(self) self.horizontalLayout.setSpacing(0) self.horizontalLayout.setMargin(0) self.text = QLineEdit() self.text.setMinimumWidth(300) self.text.setText('') self.text.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.horizontalLayout.addWidget(self.text) self.pushButton = QPushButton() self.pushButton.setText('...') self.pushButton.clicked.connect(self.showPopupMenu) self.horizontalLayout.addWidget(self.pushButton) self.setLayout(self.horizontalLayout) def showPopupMenu(self): popupmenu = QMenu() if not (isinstance(self.param, ParameterMultipleInput) and self.param.datatype == ParameterMultipleInput.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()) def showLayerSelectionDialog(self): if (isinstance(self.param, ParameterRaster) or (isinstance(self.param, ParameterMultipleInput) and self.param.datatype == ParameterMultipleInput.TYPE_RASTER)): layers = dataobjects.getRasterLayers() elif isinstance(self.param, ParameterTable): layers = dataobjects.getTables() else: if isinstance(self.param, ParameterVector): datatype = self.param.shapetype 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.text.setText(layers[selected[0]].name()) 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).setText(layers[layeridx].name()) def showFileSelectionDialog(self): settings = QSettings() text = unicode(self.text.text()) if os.path.isdir(text): path = text elif os.path.isdir(os.path.dirname(text)): path = os.path.dirname(text) elif settings.contains('/Processing/LastInputPath'): path = unicode(settings.value('/Processing/LastInputPath')) else: path = '' ret = QFileDialog.getOpenFileNames(self, self.tr('Open file'), path, self.tr('All files(*.*);;') + self.param.getFileFilter()) if ret: files = list(ret) settings.setValue('/Processing/LastInputPath', os.path.dirname(unicode(files[0]))) for i, filename in enumerate(files): files[i] = dataobjects.getRasterSublayer(filename, self.param) if len(files) == 1: self.text.setText(files[0]) else: if isinstance(self.param, ParameterMultipleInput): self.text.setText(';'.join(unicode(f) for f in files)) else: rowdif = len(files) - (self.table.rowCount() - self.row) for i in range(rowdif): self.panel.addRow() for i, f in enumerate(files): self.table.cellWidget(i + self.row, self.col).setText(f) def setText(self, text): return self.text.setText(text) def getText(self): return self.text.text()
def setupUi(self): self.setWindowTitle(self.tr('Parameter definition')) self.verticalLayout = QVBoxLayout(self) self.verticalLayout.setSpacing(40) self.verticalLayout.setMargin(20) self.horizontalLayout = QHBoxLayout(self) self.horizontalLayout.setSpacing(2) self.horizontalLayout.setMargin(0) self.label = QLabel(self.tr('Parameter name')) self.horizontalLayout.addWidget(self.label) self.nameTextBox = QLineEdit() self.horizontalLayout.addWidget(self.nameTextBox) self.verticalLayout.addLayout(self.horizontalLayout) self.horizontalLayout2 = QHBoxLayout(self) self.horizontalLayout2.setSpacing(2) self.horizontalLayout2.setMargin(0) self.horizontalLayout3 = QHBoxLayout(self) self.horizontalLayout3.setSpacing(2) self.horizontalLayout3.setMargin(0) self.horizontalLayout4 = QHBoxLayout(self) self.horizontalLayout4.setSpacing(2) self.horizontalLayout4.setMargin(0) if isinstance(self.param, Parameter): self.nameTextBox.setText(self.param.description) if self.paramType == ModelerParameterDefinitionDialog.PARAMETER_BOOLEAN or \ isinstance(self.param, ParameterBoolean): self.state = QCheckBox() self.state.setText(self.tr('Checked')) self.state.setChecked(False) if self.param is not None: self.state.setChecked(True if self.param.value else False) self.horizontalLayout3.addWidget(self.state) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or \ isinstance(self.param, ParameterTableField): self.horizontalLayout3.addWidget(QLabel(self.tr('Parent layer'))) self.parentCombo = QComboBox() idx = 0 for param in self.alg.inputs.values(): if isinstance(param.param, (ParameterVector, ParameterTable)): self.parentCombo.addItem(param.param.description, param.param.name) if self.param is not None: if self.param.parent == param.param.name: self.parentCombo.setCurrentIndex(idx) idx += 1 self.horizontalLayout3.addWidget(self.parentCombo) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or \ isinstance(self.param, ParameterVector): self.horizontalLayout3.addWidget(QLabel(self.tr('Shape type'))) self.shapetypeCombo = QComboBox() self.shapetypeCombo.addItem(self.tr('Any')) self.shapetypeCombo.addItem(self.tr('Point')) self.shapetypeCombo.addItem(self.tr('Line')) self.shapetypeCombo.addItem(self.tr('Polygon')) if self.param is not None: self.shapetypeCombo.setCurrentIndex(self.param.shapetype[0] + 1) self.horizontalLayout3.addWidget(self.shapetypeCombo) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or \ isinstance(self.param, ParameterMultipleInput): self.horizontalLayout3.addWidget(QLabel(self.tr('Data type'))) self.datatypeCombo = QComboBox() self.datatypeCombo.addItem(self.tr('Vector (any)')) self.datatypeCombo.addItem(self.tr('Vector (point)')) self.datatypeCombo.addItem(self.tr('Vector (line)')) self.datatypeCombo.addItem(self.tr('Vector (polygon)')) self.datatypeCombo.addItem(self.tr('Raster')) self.datatypeCombo.addItem(self.tr('Table')) if self.param is not None: self.datatypeCombo.setCurrentIndex(self.param.datatype + 1) self.horizontalLayout3.addWidget(self.datatypeCombo) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or \ isinstance(self.param, ParameterNumber): self.horizontalLayout3.addWidget(QLabel(self.tr('Min/Max values'))) self.minTextBox = QLineEdit() self.maxTextBox = QLineEdit() if self.param is not None: self.minTextBox.setText(unicode(self.param.min)) self.maxTextBox.setText(unicode(self.param.max)) self.horizontalLayout3.addWidget(self.minTextBox) self.horizontalLayout3.addWidget(self.maxTextBox) self.verticalLayout.addLayout(self.horizontalLayout3) self.horizontalLayout4.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() self.defaultTextBox.setText(self.tr('0')) if self.param is not None: default = self.param.default if self.param.isInteger: default = int(math.floor(default)) self.defaultTextBox.setText(unicode(default)) self.horizontalLayout4.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayout4) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or \ isinstance(self.param, ParameterString): self.horizontalLayout3.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() if self.param is not None: self.defaultTextBox.setText(self.param.default) self.horizontalLayout3.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or \ isinstance(self.param, ParameterFile): self.horizontalLayout3.addWidget(QLabel(self.tr('Type'))) self.fileFolderCombo = QComboBox() self.fileFolderCombo.addItem(self.tr('File')) self.fileFolderCombo.addItem(self.tr('Folder')) if self.param is not None: self.fileFolderCombo.setCurrentIndex( 1 if self.param.isFolder else 0) self.horizontalLayout3.addWidget(self.fileFolderCombo) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_POINT or \ isinstance(self.param, ParameterPoint): self.horizontalLayout3.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() if self.param is not None: self.defaultTextBox.setText(self.param.default) self.horizontalLayout3.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayout3) self.horizontalLayout2.addWidget(QLabel(self.tr('Required'))) self.yesNoCombo = QComboBox() self.yesNoCombo.addItem(self.tr('Yes')) self.yesNoCombo.addItem(self.tr('No')) self.horizontalLayout2.addWidget(self.yesNoCombo) if self.param is not None: self.yesNoCombo.setCurrentIndex(1 if self.param.optional else 0) self.verticalLayout.addLayout(self.horizontalLayout2) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.buttonBox.setObjectName('buttonBox') self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) self.verticalLayout.addWidget(self.buttonBox) self.setLayout(self.verticalLayout)
class CalculatorModelerParametersDialog(ModelerParametersDialog): def setupUi(self): self.valueItems = {} self.dependentItems = {} self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.infoText = QTextEdit() numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) text = self.tr('You can refer to model values in your formula, using ' 'single-letter variables, as follows:\n', 'CalculatorModelerParametersDialog') ichar = 97 if numbers: for number in numbers: text += chr(ichar) + '->' + self.resolveValueDescription(number) + '\n' ichar += 1 else: text += self.tr('\n - No numerical variables are available.', 'CalculatorModelerParametersDialog') self.infoText.setText(text) self.infoText.setEnabled(False) self.formulaText = QLineEdit() if hasattr(self.formulaText, 'setPlaceholderText'): self.formulaText.setPlaceholderText(self.tr('[Enter your formula here]', 'CalculatorModelerParametersDialog')) if self._algName is not None: alg = self.model.algs[self._algName] self.formulaText.setText(alg.params[FORMULA]) self.setWindowTitle(self.tr('Calculator', 'CalculatorModelerParametersDialog')) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(2) self.verticalLayout.setMargin(0) self.verticalLayout.addWidget(self.infoText) self.verticalLayout.addWidget(self.formulaText) self.verticalLayout.addWidget(self.buttonBox) self.setLayout(self.verticalLayout) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) QMetaObject.connectSlotsByName(self) def createAlgorithm(self): alg = Algorithm('modelertools:calculator') alg.setName(self.model) alg.description = self.tr('Calculator', 'CalculatorModelerParametersDialog') formula = self.formulaText.text() alg.params[FORMULA] = formula for i in xrange(AVAILABLE_VARIABLES): paramname = NUMBER + unicode(i) alg.params[paramname] = None numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) used = [] for i in range(len(numbers)): if unicode(chr(i + 97)) in formula: used.append(numbers[i]) for i, variable in enumerate(used): paramname = NUMBER + unicode(i) alg.params[paramname] = variable # TODO check formula is correct return alg
def getWidgetFromParameter(self, param): if isinstance(param, ParameterRaster): item = QComboBox() layers = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) if param.optional: item.addItem(self.NOT_SELECTED, None) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterVector): item = QComboBox() layers = self.getAvailableValuesOfType(ParameterVector, OutputVector) if param.optional: item.addItem(self.NOT_SELECTED, None) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterTable): item = QComboBox() tables = self.getAvailableValuesOfType(ParameterTable, OutputTable) layers = self.getAvailableValuesOfType(ParameterVector, OutputVector) if param.optional: item.addItem(self.NOT_SELECTED, None) for table in tables: item.addItem(self.resolveValueDescription(table), table) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterBoolean): item = QComboBox() item.addItem('Yes') item.addItem('No') bools = self.getAvailableValuesOfType(ParameterBoolean, None) for b in bools: item.addItem(self.resolveValueDescription(b), b) if param.default: item.setCurrentIndex(0) else: item.setCurrentIndex(1) elif isinstance(param, ParameterSelection): item = QComboBox() item.addItems(param.options) item.setCurrentIndex(param.default or 1) elif isinstance(param, ParameterFixedTable): item = FixedTablePanel(param) elif isinstance(param, ParameterRange): item = RangePanel(param) elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType( ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType( ParameterRaster, OutputRaster) opts = [] for opt in options: opts.append(self.resolveValueDescription(opt)) item = MultipleInputPanel(opts) elif isinstance(param, ParameterString): strings = self.getAvailableValuesOfType(ParameterString, OutputString) options = [(self.resolveValueDescription(s), s) for s in strings] if param.multiline: item = MultilineTextPanel(options) item.setText(unicode(param.default or "")) else: item = QComboBox() item.setEditable(True) for desc, val in options: item.addItem(desc, val) item.setEditText(unicode(param.default or "")) elif isinstance(param, ParameterTableField): item = QComboBox() item.setEditable(True) fields = self.getAvailableValuesOfType(ParameterTableField, None) for f in fields: item.addItem(self.resolveValueDescription(f), f) elif isinstance(param, ParameterNumber): item = QComboBox() item.setEditable(True) numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) for n in numbers: item.addItem(self.resolveValueDescription(n), n) item.setEditText(unicode(param.default)) elif isinstance(param, ParameterCrs): item = CrsSelectionPanel(param.default) elif isinstance(param, ParameterExtent): item = QComboBox() item.setEditable(True) extents = self.getAvailableValuesOfType(ParameterExtent, OutputExtent) if self.canUseAutoExtent(): item.addItem(self.USE_MIN_COVERING_EXTENT, None) for ex in extents: item.addItem(self.resolveValueDescription(ex), ex) if not self.canUseAutoExtent(): item.setEditText(unicode(param.default)) elif isinstance(param, ParameterPoint): item = QComboBox() item.setEditable(True) points = self.getAvailableValuesOfType(ParameterPoint) for p in points: item.addItem(self.resolveValueDescription(p), p) item.setEditText(unicode(param.default)) elif isinstance(param, ParameterFile): item = QComboBox() item.setEditable(True) files = self.getAvailableValuesOfType(ParameterFile, OutputFile) for f in files: item.addItem(self.resolveValueDescription(f), f) elif isinstance(param, ParameterGeometryPredicate): item = GeometryPredicateSelectionPanel(param.enabledPredicates) else: item = QLineEdit() try: item.setText(unicode(param.default)) except: pass return item
def setupUi(self): self.labels = {} self.widgets = {} self.checkBoxes = {} self.showAdvanced = False self.valueItems = {} self.dependentItems = {} self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) tooltips = self._alg.getParameterDescriptions() self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(5) self.verticalLayout.setMargin(20) hLayout = QHBoxLayout() hLayout.setSpacing(5) hLayout.setMargin(0) descriptionLabel = QLabel(self.tr("Description")) self.descriptionBox = QLineEdit() self.descriptionBox.setText(self._alg.name) hLayout.addWidget(descriptionLabel) hLayout.addWidget(self.descriptionBox) self.verticalLayout.addLayout(hLayout) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.verticalLayout.addWidget(line) for param in self._alg.parameters: if param.isAdvanced: self.advancedButton = QPushButton() self.advancedButton.setText(self.tr('Show advanced parameters')) self.advancedButton.clicked.connect( self.showAdvancedParametersClicked) advancedButtonHLayout = QHBoxLayout() advancedButtonHLayout.addWidget(self.advancedButton) advancedButtonHLayout.addStretch() self.verticalLayout.addLayout(advancedButtonHLayout) break for param in self._alg.parameters: if param.hidden: continue desc = param.description if isinstance(param, ParameterExtent): desc += self.tr('(xmin, xmax, ymin, ymax)') if isinstance(param, ParameterPoint): desc += self.tr('(x, y)') label = QLabel(desc) self.labels[param.name] = label widget = self.getWidgetFromParameter(param) self.valueItems[param.name] = widget if param.name in tooltips.keys(): tooltip = tooltips[param.name] else: tooltip = param.description label.setToolTip(tooltip) widget.setToolTip(tooltip) if param.isAdvanced: label.setVisible(self.showAdvanced) widget.setVisible(self.showAdvanced) self.widgets[param.name] = widget self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(widget) for output in self._alg.outputs: if output.hidden: continue if isinstance(output, (OutputRaster, OutputVector, OutputTable, OutputHTML, OutputFile, OutputDirectory)): label = QLabel(output.description + '<' + output.__class__.__name__ + '>') item = QLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(item) self.valueItems[output.name] = item label = QLabel(' ') self.verticalLayout.addWidget(label) label = QLabel(self.tr('Parent algorithms')) self.dependenciesPanel = self.getDependenciesPanel() self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(self.dependenciesPanel) self.verticalLayout.addStretch(1000) self.setLayout(self.verticalLayout) self.setPreviousValues() self.setWindowTitle(self._alg.name) self.verticalLayout2 = QVBoxLayout() self.verticalLayout2.setSpacing(2) self.verticalLayout2.setMargin(0) self.tabWidget = QTabWidget() self.tabWidget.setMinimumWidth(300) self.paramPanel = QWidget() self.paramPanel.setLayout(self.verticalLayout) self.scrollArea = QScrollArea() self.scrollArea.setWidget(self.paramPanel) self.scrollArea.setWidgetResizable(True) self.tabWidget.addTab(self.scrollArea, self.tr('Parameters')) self.webView = QWebView() html = None url = None isText, help = self._alg.help() if help is not None: if isText: html = help else: url = QUrl(help) else: html = self.tr('<h2>Sorry, no help is available for this ' 'algorithm.</h2>') try: if html: self.webView.setHtml(html) elif url: self.webView.load(url) except: self.webView.setHtml(self.tr('<h2>Could not open help file :-( </h2>')) self.tabWidget.addTab(self.webView, 'Help') self.verticalLayout2.addWidget(self.tabWidget) self.verticalLayout2.addWidget(self.buttonBox) self.setLayout(self.verticalLayout2) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) QMetaObject.connectSlotsByName(self)
class ModelerParametersDialog(QDialog): ENTER_NAME = '[Enter name if this is a final result]' NOT_SELECTED = '[Not selected]' USE_MIN_COVERING_EXTENT = '[Use min covering extent]' def __init__(self, alg, model, algName=None): QDialog.__init__(self) self.setModal(True) #The algorithm to define in this dialog. It is an instance of GeoAlgorithm self._alg = alg #The resulting algorithm after the user clicks on OK. it is an instance of the container Algorithm class self.alg = None #The model this algorithm is going to be added to self.model = model #The name of the algorithm in the model, in case we are editing it and not defining it for the first time self._algName = algName self.setupUi() self.params = None def setupUi(self): self.labels = {} self.widgets = {} self.checkBoxes = {} self.showAdvanced = False self.valueItems = {} self.dependentItems = {} self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) tooltips = self._alg.getParameterDescriptions() self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(5) self.verticalLayout.setMargin(20) hLayout = QHBoxLayout() hLayout.setSpacing(5) hLayout.setMargin(0) descriptionLabel = QLabel(self.tr("Description")) self.descriptionBox = QLineEdit() self.descriptionBox.setText(self._alg.name) hLayout.addWidget(descriptionLabel) hLayout.addWidget(self.descriptionBox) self.verticalLayout.addLayout(hLayout) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.verticalLayout.addWidget(line) for param in self._alg.parameters: if param.isAdvanced: self.advancedButton = QPushButton() self.advancedButton.setText( self.tr('Show advanced parameters')) self.advancedButton.clicked.connect( self.showAdvancedParametersClicked) advancedButtonHLayout = QHBoxLayout() advancedButtonHLayout.addWidget(self.advancedButton) advancedButtonHLayout.addStretch() self.verticalLayout.addLayout(advancedButtonHLayout) break for param in self._alg.parameters: if param.hidden: continue desc = param.description if isinstance(param, ParameterExtent): desc += self.tr('(xmin, xmax, ymin, ymax)') if isinstance(param, ParameterPoint): desc += self.tr('(x, y)') label = QLabel(desc) self.labels[param.name] = label widget = self.getWidgetFromParameter(param) self.valueItems[param.name] = widget if param.name in tooltips.keys(): tooltip = tooltips[param.name] else: tooltip = param.description label.setToolTip(tooltip) widget.setToolTip(tooltip) if param.isAdvanced: label.setVisible(self.showAdvanced) widget.setVisible(self.showAdvanced) self.widgets[param.name] = widget self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(widget) for output in self._alg.outputs: if output.hidden: continue if isinstance(output, (OutputRaster, OutputVector, OutputTable, OutputHTML, OutputFile, OutputDirectory)): label = QLabel(output.description + '<' + output.__class__.__name__ + '>') item = QLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(item) self.valueItems[output.name] = item label = QLabel(' ') self.verticalLayout.addWidget(label) label = QLabel(self.tr('Parent algorithms')) self.dependenciesPanel = self.getDependenciesPanel() self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(self.dependenciesPanel) self.verticalLayout.addStretch(1000) self.setLayout(self.verticalLayout) self.setPreviousValues() self.setWindowTitle(self._alg.name) self.verticalLayout2 = QVBoxLayout() self.verticalLayout2.setSpacing(2) self.verticalLayout2.setMargin(0) self.tabWidget = QTabWidget() self.tabWidget.setMinimumWidth(300) self.paramPanel = QWidget() self.paramPanel.setLayout(self.verticalLayout) self.scrollArea = QScrollArea() self.scrollArea.setWidget(self.paramPanel) self.scrollArea.setWidgetResizable(True) self.tabWidget.addTab(self.scrollArea, self.tr('Parameters')) self.webView = QWebView() html = None url = None isText, help = self._alg.help() if help is not None: if isText: html = help else: url = QUrl(help) else: html = self.tr('<h2>Sorry, no help is available for this ' 'algorithm.</h2>') try: if html: self.webView.setHtml(html) elif url: self.webView.load(url) except: self.webView.setHtml( self.tr('<h2>Could not open help file :-( </h2>')) self.tabWidget.addTab(self.webView, 'Help') self.verticalLayout2.addWidget(self.tabWidget) self.verticalLayout2.addWidget(self.buttonBox) self.setLayout(self.verticalLayout2) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) QMetaObject.connectSlotsByName(self) def getAvailableDependencies(self): if self._algName is None: dependent = [] else: dependent = self.model.getDependentAlgorithms(self._algName) opts = [] for alg in self.model.algs.values(): if alg.name not in dependent: opts.append(alg) return opts def getDependenciesPanel(self): return MultipleInputPanel( [alg.algorithm.name for alg in self.getAvailableDependencies()]) def showAdvancedParametersClicked(self): self.showAdvanced = not self.showAdvanced if self.showAdvanced: self.advancedButton.setText(self.tr('Hide advanced parameters')) else: self.advancedButton.setText(self.tr('Show advanced parameters')) for param in self._alg.parameters: if param.isAdvanced: self.labels[param.name].setVisible(self.showAdvanced) self.widgets[param.name].setVisible(self.showAdvanced) def getAvailableValuesOfType(self, paramType, outType=None): values = [] inputs = self.model.inputs for i in inputs.values(): param = i.param if isinstance(param, paramType): values.append(ValueFromInput(param.name)) if outType is None: return values if self._algName is None: dependent = [] else: dependent = self.model.getDependentAlgorithms(self._algName) for alg in self.model.algs.values(): if alg.name not in dependent: for out in alg.algorithm.outputs: if isinstance(out, outType): values.append(ValueFromOutput(alg.name, out.name)) return values def resolveValueDescription(self, value): if isinstance(value, ValueFromInput): return self.model.inputs[value.name].param.description else: alg = self.model.algs[value.alg] return self.tr("'%s' from algorithm '%s'") % ( alg.algorithm.getOutputFromName( value.output).description, alg.description) def getWidgetFromParameter(self, param): if isinstance(param, ParameterRaster): item = QComboBox() layers = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) if param.optional: item.addItem(self.NOT_SELECTED, None) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterVector): item = QComboBox() layers = self.getAvailableValuesOfType(ParameterVector, OutputVector) if param.optional: item.addItem(self.NOT_SELECTED, None) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterTable): item = QComboBox() tables = self.getAvailableValuesOfType(ParameterTable, OutputTable) layers = self.getAvailableValuesOfType(ParameterVector, OutputVector) if param.optional: item.addItem(self.NOT_SELECTED, None) for table in tables: item.addItem(self.resolveValueDescription(table), table) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterBoolean): item = QComboBox() item.addItem('Yes') item.addItem('No') bools = self.getAvailableValuesOfType(ParameterBoolean, None) for b in bools: item.addItem(self.resolveValueDescription(b), b) if param.default: item.setCurrentIndex(0) else: item.setCurrentIndex(1) elif isinstance(param, ParameterSelection): item = QComboBox() item.addItems(param.options) item.setCurrentIndex(param.default or 1) elif isinstance(param, ParameterFixedTable): item = FixedTablePanel(param) elif isinstance(param, ParameterRange): item = RangePanel(param) elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType( ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType( ParameterRaster, OutputRaster) opts = [] for opt in options: opts.append(self.resolveValueDescription(opt)) item = MultipleInputPanel(opts) elif isinstance(param, ParameterString): strings = self.getAvailableValuesOfType(ParameterString, OutputString) options = [(self.resolveValueDescription(s), s) for s in strings] if param.multiline: item = MultilineTextPanel(options) item.setText(unicode(param.default or "")) else: item = QComboBox() item.setEditable(True) for desc, val in options: item.addItem(desc, val) item.setEditText(unicode(param.default or "")) elif isinstance(param, ParameterTableField): item = QComboBox() item.setEditable(True) fields = self.getAvailableValuesOfType(ParameterTableField, None) for f in fields: item.addItem(self.resolveValueDescription(f), f) elif isinstance(param, ParameterNumber): item = QComboBox() item.setEditable(True) numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) for n in numbers: item.addItem(self.resolveValueDescription(n), n) item.setEditText(unicode(param.default)) elif isinstance(param, ParameterCrs): item = CrsSelectionPanel(param.default) elif isinstance(param, ParameterExtent): item = QComboBox() item.setEditable(True) extents = self.getAvailableValuesOfType(ParameterExtent, OutputExtent) if self.canUseAutoExtent(): item.addItem(self.USE_MIN_COVERING_EXTENT, None) for ex in extents: item.addItem(self.resolveValueDescription(ex), ex) if not self.canUseAutoExtent(): item.setEditText(unicode(param.default)) elif isinstance(param, ParameterPoint): item = QComboBox() item.setEditable(True) points = self.getAvailableValuesOfType(ParameterPoint) for p in points: item.addItem(self.resolveValueDescription(p), p) item.setEditText(unicode(param.default)) elif isinstance(param, ParameterFile): item = QComboBox() item.setEditable(True) files = self.getAvailableValuesOfType(ParameterFile, OutputFile) for f in files: item.addItem(self.resolveValueDescription(f), f) elif isinstance(param, ParameterGeometryPredicate): item = GeometryPredicateSelectionPanel(param.enabledPredicates) else: item = QLineEdit() try: item.setText(unicode(param.default)) except: pass return item def canUseAutoExtent(self): for param in self._alg.parameters: if isinstance( param, (ParameterRaster, ParameterVector, ParameterMultipleInput)): return True return False def setTableContent(self): params = self._alg.parameters outputs = self._alg.outputs visibleParams = [p for p in params if not p.hidden] visibleOutputs = [p for o in outputs if not o.hidden] self.tableWidget.setRowCount(len(visibleParams) + len(visibleOutputs)) for i, param in visibleParams: item = QTableWidgetItem(param.description) item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setItem(i, 0, item) item = self.getWidgetFromParameter(param) self.valueItems[param.name] = item self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22) for i, output in visibleOutputs: item = QTableWidgetItem(output.description + '<' + output.__module__.split('.')[-1] + '>') item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setItem(i, 0, item) item = QLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.valueItems[output.name] = item self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22) def setComboBoxValue(self, combo, value, param): if isinstance(value, list): value = value[0] items = [combo.itemData(i) for i in range(combo.count())] try: idx = items.index(value) combo.setCurrentIndex(idx) return except ValueError: pass if combo.isEditable(): if value is not None: combo.setEditText(unicode(value)) elif isinstance(param, ParameterSelection): combo.setCurrentIndex(int(value)) elif isinstance(param, ParameterBoolean): if value: combo.setCurrentIndex(0) else: combo.setCurrentIndex(1) def setPreviousValues(self): if self._algName is not None: alg = self.model.algs[self._algName] self.descriptionBox.setText(alg.description) for param in alg.algorithm.parameters: if param.hidden: continue widget = self.valueItems[param.name] if param.name in alg.params: value = alg.params[param.name] else: value = None if isinstance( param, (ParameterRaster, ParameterVector, ParameterTable, ParameterTableField, ParameterSelection, ParameterNumber, ParameterBoolean, ParameterExtent, ParameterFile, ParameterPoint)): self.setComboBoxValue(widget, value, param) elif isinstance(param, ParameterString): if param.multiline: widget.setValue(value) else: self.setComboBoxValue(widget, value, param) elif isinstance(param, ParameterCrs): widget.setAuthId(value) elif isinstance(param, ParameterFixedTable): pass # TODO! elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType( ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType( ParameterRaster, OutputRaster) selected = [] for i, opt in enumerate(options): if opt in value: selected.append(i) widget.setSelectedItems(selected) elif isinstance(param, ParameterGeometryPredicate): widget.setValue(value) for name, out in alg.outputs.iteritems(): widget = self.valueItems[name].setText(out.description) selected = [] dependencies = self.getAvailableDependencies() for idx, dependency in enumerate(dependencies): if dependency.name in alg.dependencies: selected.append(idx) self.dependenciesPanel.setSelectedItems(selected) def createAlgorithm(self): alg = Algorithm(self._alg.commandLineName()) alg.setName(self.model) alg.description = self.descriptionBox.text() params = self._alg.parameters outputs = self._alg.outputs for param in params: if param.hidden: continue if not self.setParamValue(alg, param, self.valueItems[param.name]): return None for output in outputs: if not output.hidden: name = unicode(self.valueItems[output.name].text()) if name.strip( ) != '' and name != ModelerParametersDialog.ENTER_NAME: alg.outputs[output.name] = ModelerOutput(name) selectedOptions = self.dependenciesPanel.selectedoptions availableDependencies = self.getAvailableDependencies() for selected in selectedOptions: alg.dependencies.append(availableDependencies[selected].name) return alg def setParamValueLayerOrTable(self, alg, param, widget): idx = widget.currentIndex() if idx < 0: return False else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamTableFieldValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = unicode(widget.currentText()).strip() if s == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = s return True else: alg.params[param.name] = widget.itemData(widget.currentIndex()) return True def setParamStringValue(self, alg, param, widget): if param.multiline: value = widget.getValue() option = widget.getOption() if option == MultilineTextPanel.USE_TEXT: if value == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = value else: alg.params[param.name] = value else: idx = widget.findText(widget.currentText()) if idx < 0: value = widget.currentText().strip() if value == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = value else: alg.params[param.name] = widget.itemData(widget.currentIndex()) return True def setParamFileValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: value = widget.currentText() else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamNumberValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = widget.currentText().strip() if s: try: value = float(s) except: return False elif param.optional: value = None else: return False else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamExtentValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = unicode(widget.currentText()).strip() if s: try: tokens = s.split(',') if len(tokens) != 4: return False for token in tokens: float(token) except: return False elif param.optional: s = None else: return False alg.params[param.name] = [s] else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamPointValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = unicode(widget.currentText()).strip() if s: try: tokens = s.split(',') if len(tokens) != 2: return False for token in tokens: float(token) except: return False elif param.optional: s = None else: return False alg.params[param.name] = [s] else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamValue(self, alg, param, widget): if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable)): return self.setParamValueLayerOrTable(alg, param, widget) elif isinstance(param, ParameterBoolean): if widget.currentIndex() < 2: value = widget.currentIndex() == 0 else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True elif isinstance(param, ParameterString): return self.setParamStringValue(alg, param, widget) elif isinstance(param, ParameterNumber): return self.setParamNumberValue(alg, param, widget) elif isinstance(param, ParameterExtent): return self.setParamExtentValue(alg, param, widget) elif isinstance(param, ParameterPoint): return self.setParamPointValue(alg, param, widget) elif isinstance(param, ParameterFile): return self.setParamFileValue(alg, param, widget) elif isinstance(param, ParameterSelection): alg.params[param.name] = widget.currentIndex() return True elif isinstance(param, ParameterRange): alg.params[param.name] = widget.getValue() return True elif isinstance(param, ParameterCrs): authid = widget.getValue() if authid is None and not param.optional: return False alg.params[param.name] = authid return True elif isinstance(param, ParameterFixedTable): table = widget.table if not bool(table) and not param.optional: return False alg.params[param.name] = ParameterFixedTable.tableToString(table) return True elif isinstance(param, ParameterTableField): return self.setParamTableFieldValue(alg, param, widget) elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType( ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType( ParameterRaster, OutputRaster) values = [options[i] for i in widget.selectedoptions] if len(values) == 0 and not param.optional: return False alg.params[param.name] = values return True elif isinstance(param, ParameterGeometryPredicate): alg.params[param.name] = widget.value() return True else: alg.params[param.name] = unicode(widget.text()) return True def okPressed(self): self.alg = self.createAlgorithm() if self.alg is not None: self.close() else: QMessageBox.warning(self, self.tr('Unable to add algorithm'), self.tr('Wrong or missing parameter values')) def cancelPressed(self): self.alg = None self.close()
class BatchOutputSelectionPanel(QWidget): def __init__(self, output, alg, row, col, panel): super(BatchOutputSelectionPanel, self).__init__(None) self.alg = alg self.row = row self.col = col self.output = output self.panel = panel self.table = self.panel.tblParameters self.horizontalLayout = QHBoxLayout(self) self.horizontalLayout.setSpacing(2) self.horizontalLayout.setMargin(0) self.text = QLineEdit() self.text.setText('') self.text.setMinimumWidth(300) self.text.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.horizontalLayout.addWidget(self.text) self.pushButton = QPushButton() self.pushButton.setText('...') self.pushButton.clicked.connect(self.showSelectionDialog) self.horizontalLayout.addWidget(self.pushButton) self.setLayout(self.horizontalLayout) def showSelectionDialog(self): if isinstance(self.output, OutputDirectory): self.selectDirectory() return filefilter = self.output.getFileFilter(self.alg) settings = QSettings() if settings.contains('/Processing/LastBatchOutputPath'): path = unicode(settings.value('/Processing/LastBatchOutputPath')) else: path = '' filename, selectedFileFilter = QFileDialog.getSaveFileNameAndFilter( self, self.tr('Save file'), path, filefilter) print filename, selectedFileFilter if filename: if not filename.lower().endswith( tuple(re.findall("\*(\.[a-z]{1,10})", filefilter))): ext = re.search("\*(\.[a-z]{1,10})", selectedFileFilter) if ext: filename += ext.group(1) settings.setValue('/Processing/LastBatchOutputPath', os.path.dirname(filename)) dlg = AutofillDialog(self.alg) dlg.exec_() if dlg.mode is not None: try: if dlg.mode == AutofillDialog.DO_NOT_AUTOFILL: self.table.cellWidget(self.row, self.col).setValue(filename) elif dlg.mode == AutofillDialog.FILL_WITH_NUMBERS: n = self.table.rowCount() - self.row for i in range(n): name = filename[:filename.rfind('.')] \ + unicode(i + 1) + filename[filename.rfind('.'):] self.table.cellWidget(i + self.row, self.col).setValue(name) elif dlg.mode == AutofillDialog.FILL_WITH_PARAMETER: n = self.table.rowCount() - self.row for i in range(n): widget = self.table.cellWidget( i + self.row, dlg.param) param = self.alg.parameters[dlg.param] if isinstance( param, (ParameterRaster, ParameterVector, ParameterTable, ParameterMultipleInput)): s = unicode(widget.getText()) s = os.path.basename(s) s = os.path.splitext(s)[0] elif isinstance(param, ParameterBoolean): s = unicode(widget.currentIndex() == 0) elif isinstance(param, ParameterSelection): s = unicode(widget.currentText()) elif isinstance(param, ParameterFixedTable): s = unicode(widget.table) else: s = unicode(widget.text()) name = filename[:filename.rfind('.')] + s \ + filename[filename.rfind('.'):] self.table.cellWidget(i + self.row, self.col).setValue(name) except: pass def selectDirectory(self): settings = QSettings() if settings.contains('/Processing/LastBatchOutputPath'): lastDir = unicode( settings.value('/Processing/LastBatchOutputPath')) else: lastDir = '' dirName = QFileDialog.getExistingDirectory(self, self.tr('Select directory'), lastDir, QFileDialog.ShowDirsOnly) if dirName: self.table.cellWidget(self.row, self.col).setValue(dirName) settings.setValue('/Processing/LastBatchOutputPath', dirName) def setValue(self, text): return self.text.setText(text) def getValue(self): return unicode(self.text.text())
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) if param.default: 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 = [self.getExtendedLayerName(opt) for opt in options] 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, ParameterPoint): item = PointSelectionPanel(self.parent, 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() if param.default: textEdit.setPlainText(param.default) verticalLayout.addWidget(textEdit) item = textEdit else: item = QLineEdit() if param.default: item.setText(unicode(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() if param.default: item.setValue(param.default) else: item = QLineEdit() if param.default: item.setText(unicode(param.default)) return item
def setupUi(self): self.setWindowTitle(self.tr('Parameter definition')) self.verticalLayout = QVBoxLayout(self) self.verticalLayout.setSpacing(40) self.verticalLayout.setMargin(20) self.horizontalLayout = QHBoxLayout(self) self.horizontalLayout.setSpacing(2) self.horizontalLayout.setMargin(0) self.label = QLabel(self.tr('Parameter name')) self.horizontalLayout.addWidget(self.label) self.nameTextBox = QLineEdit() self.horizontalLayout.addWidget(self.nameTextBox) self.verticalLayout.addLayout(self.horizontalLayout) self.horizontalLayout2 = QHBoxLayout(self) self.horizontalLayout2.setSpacing(2) self.horizontalLayout2.setMargin(0) self.horizontalLayout3 = QHBoxLayout(self) self.horizontalLayout3.setSpacing(2) self.horizontalLayout3.setMargin(0) self.horizontalLayout4 = QHBoxLayout(self) self.horizontalLayout4.setSpacing(2) self.horizontalLayout4.setMargin(0) if isinstance(self.param, Parameter): self.nameTextBox.setText(self.param.description) if self.paramType == ModelerParameterDefinitionDialog.PARAMETER_BOOLEAN or \ isinstance(self.param, ParameterBoolean): self.state = QCheckBox() self.state.setText(self.tr('Checked')) self.state.setChecked(False) if self.param is not None: self.state.setChecked(True if self.param.value else False) self.horizontalLayout3.addWidget(self.state) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or \ isinstance(self.param, ParameterTableField): self.horizontalLayout3.addWidget(QLabel(self.tr('Parent layer'))) self.parentCombo = QComboBox() idx = 0 for param in self.alg.inputs.values(): if isinstance(param.param, (ParameterVector, ParameterTable)): self.parentCombo.addItem(param.param.description, param.param.name) if self.param is not None: if self.param.parent == param.param.name: self.parentCombo.setCurrentIndex(idx) idx += 1 self.horizontalLayout3.addWidget(self.parentCombo) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or \ isinstance(self.param, ParameterVector): self.horizontalLayout3.addWidget(QLabel(self.tr('Shape type'))) self.shapetypeCombo = QComboBox() self.shapetypeCombo.addItem(self.tr('Any')) self.shapetypeCombo.addItem(self.tr('Point')) self.shapetypeCombo.addItem(self.tr('Line')) self.shapetypeCombo.addItem(self.tr('Polygon')) if self.param is not None: self.shapetypeCombo.setCurrentIndex(self.param.shapetype[0] + 1) self.horizontalLayout3.addWidget(self.shapetypeCombo) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or \ isinstance(self.param, ParameterMultipleInput): self.horizontalLayout3.addWidget(QLabel(self.tr('Data type'))) self.datatypeCombo = QComboBox() self.datatypeCombo.addItem(self.tr('Vector (any)')) self.datatypeCombo.addItem(self.tr('Vector (point)')) self.datatypeCombo.addItem(self.tr('Vector (line)')) self.datatypeCombo.addItem(self.tr('Vector (polygon)')) self.datatypeCombo.addItem(self.tr('Raster')) self.datatypeCombo.addItem(self.tr('Table')) if self.param is not None: self.datatypeCombo.setCurrentIndex(self.param.datatype + 1) self.horizontalLayout3.addWidget(self.datatypeCombo) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or \ isinstance(self.param, ParameterNumber): self.horizontalLayout3.addWidget(QLabel(self.tr('Min/Max values'))) self.minTextBox = QLineEdit() self.maxTextBox = QLineEdit() if self.param is not None: self.minTextBox.setText(unicode(self.param.min)) self.maxTextBox.setText(unicode(self.param.max)) self.horizontalLayout3.addWidget(self.minTextBox) self.horizontalLayout3.addWidget(self.maxTextBox) self.verticalLayout.addLayout(self.horizontalLayout3) self.horizontalLayout4.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() self.defaultTextBox.setText(self.tr('0')) if self.param is not None: default = self.param.default if self.param.isInteger: default = int(math.floor(default)) self.defaultTextBox.setText(unicode(default)) self.horizontalLayout4.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayout4) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or \ isinstance(self.param, ParameterString): self.horizontalLayout3.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() if self.param is not None: self.defaultTextBox.setText(self.param.default) self.horizontalLayout3.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or \ isinstance(self.param, ParameterFile): self.horizontalLayout3.addWidget(QLabel(self.tr('Type'))) self.fileFolderCombo = QComboBox() self.fileFolderCombo.addItem(self.tr('File')) self.fileFolderCombo.addItem(self.tr('Folder')) if self.param is not None: self.fileFolderCombo.setCurrentIndex( 1 if self.param.isFolder else 0) self.horizontalLayout3.addWidget(self.fileFolderCombo) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_POINT or \ isinstance(self.param, ParameterPoint): self.horizontalLayout3.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() if self.param is not None: self.defaultTextBox.setText(self.param.default) self.horizontalLayout3.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayout3) self.horizontalLayout2.addWidget(QLabel(self.tr('Required'))) self.yesNoCombo = QComboBox() self.yesNoCombo.addItem(self.tr('Yes')) self.yesNoCombo.addItem(self.tr('No')) self.horizontalLayout2.addWidget(self.yesNoCombo) if self.param is not None: self.yesNoCombo.setCurrentIndex( 1 if self.param.optional else 0) self.verticalLayout.addLayout(self.horizontalLayout2) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.buttonBox.setObjectName('buttonBox') self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) self.verticalLayout.addWidget(self.buttonBox) self.setLayout(self.verticalLayout)
class ModelerParameterDefinitionDialog(QDialog): PARAMETER_NUMBER = 'Number' PARAMETER_RASTER = 'Raster layer' PARAMETER_TABLE = 'Table' PARAMETER_VECTOR = 'Vector layer' PARAMETER_STRING = 'String' PARAMETER_BOOLEAN = 'Boolean' PARAMETER_TABLE_FIELD = 'Table field' PARAMETER_EXTENT = 'Extent' PARAMETER_FILE = 'File' PARAMETER_POINT = 'Point' # To add PARAMETER_MULTIPLE = 'Multiple input' PARAMETER_FIXED_TABLE = 'Fixed table' paramTypes = [ PARAMETER_BOOLEAN, PARAMETER_EXTENT, PARAMETER_FILE, PARAMETER_NUMBER, PARAMETER_RASTER, PARAMETER_STRING, PARAMETER_TABLE, PARAMETER_TABLE_FIELD, PARAMETER_VECTOR, PARAMETER_POINT ] def __init__(self, alg, paramType=None, param=None): self.alg = alg self.paramType = paramType self.param = param QDialog.__init__(self) self.setModal(True) self.setupUi() def setupUi(self): self.setWindowTitle(self.tr('Parameter definition')) self.verticalLayout = QVBoxLayout(self) self.verticalLayout.setSpacing(40) self.verticalLayout.setMargin(20) self.horizontalLayout = QHBoxLayout(self) self.horizontalLayout.setSpacing(2) self.horizontalLayout.setMargin(0) self.label = QLabel(self.tr('Parameter name')) self.horizontalLayout.addWidget(self.label) self.nameTextBox = QLineEdit() self.horizontalLayout.addWidget(self.nameTextBox) self.verticalLayout.addLayout(self.horizontalLayout) self.horizontalLayout2 = QHBoxLayout(self) self.horizontalLayout2.setSpacing(2) self.horizontalLayout2.setMargin(0) self.horizontalLayout3 = QHBoxLayout(self) self.horizontalLayout3.setSpacing(2) self.horizontalLayout3.setMargin(0) self.horizontalLayout4 = QHBoxLayout(self) self.horizontalLayout4.setSpacing(2) self.horizontalLayout4.setMargin(0) if isinstance(self.param, Parameter): self.nameTextBox.setText(self.param.description) if self.paramType == ModelerParameterDefinitionDialog.PARAMETER_BOOLEAN or \ isinstance(self.param, ParameterBoolean): self.state = QCheckBox() self.state.setText(self.tr('Checked')) self.state.setChecked(False) if self.param is not None: self.state.setChecked(True if self.param.value else False) self.horizontalLayout3.addWidget(self.state) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or \ isinstance(self.param, ParameterTableField): self.horizontalLayout3.addWidget(QLabel(self.tr('Parent layer'))) self.parentCombo = QComboBox() idx = 0 for param in self.alg.inputs.values(): if isinstance(param.param, (ParameterVector, ParameterTable)): self.parentCombo.addItem(param.param.description, param.param.name) if self.param is not None: if self.param.parent == param.param.name: self.parentCombo.setCurrentIndex(idx) idx += 1 self.horizontalLayout3.addWidget(self.parentCombo) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or \ isinstance(self.param, ParameterVector): self.horizontalLayout3.addWidget(QLabel(self.tr('Shape type'))) self.shapetypeCombo = QComboBox() self.shapetypeCombo.addItem(self.tr('Any')) self.shapetypeCombo.addItem(self.tr('Point')) self.shapetypeCombo.addItem(self.tr('Line')) self.shapetypeCombo.addItem(self.tr('Polygon')) if self.param is not None: self.shapetypeCombo.setCurrentIndex(self.param.shapetype[0] + 1) self.horizontalLayout3.addWidget(self.shapetypeCombo) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or \ isinstance(self.param, ParameterMultipleInput): self.horizontalLayout3.addWidget(QLabel(self.tr('Data type'))) self.datatypeCombo = QComboBox() self.datatypeCombo.addItem(self.tr('Vector (any)')) self.datatypeCombo.addItem(self.tr('Vector (point)')) self.datatypeCombo.addItem(self.tr('Vector (line)')) self.datatypeCombo.addItem(self.tr('Vector (polygon)')) self.datatypeCombo.addItem(self.tr('Raster')) self.datatypeCombo.addItem(self.tr('Table')) if self.param is not None: self.datatypeCombo.setCurrentIndex(self.param.datatype + 1) self.horizontalLayout3.addWidget(self.datatypeCombo) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or \ isinstance(self.param, ParameterNumber): self.horizontalLayout3.addWidget(QLabel(self.tr('Min/Max values'))) self.minTextBox = QLineEdit() self.maxTextBox = QLineEdit() if self.param is not None: self.minTextBox.setText(unicode(self.param.min)) self.maxTextBox.setText(unicode(self.param.max)) self.horizontalLayout3.addWidget(self.minTextBox) self.horizontalLayout3.addWidget(self.maxTextBox) self.verticalLayout.addLayout(self.horizontalLayout3) self.horizontalLayout4.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() self.defaultTextBox.setText(self.tr('0')) if self.param is not None: default = self.param.default if self.param.isInteger: default = int(math.floor(default)) self.defaultTextBox.setText(unicode(default)) self.horizontalLayout4.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayout4) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or \ isinstance(self.param, ParameterString): self.horizontalLayout3.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() if self.param is not None: self.defaultTextBox.setText(self.param.default) self.horizontalLayout3.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or \ isinstance(self.param, ParameterFile): self.horizontalLayout3.addWidget(QLabel(self.tr('Type'))) self.fileFolderCombo = QComboBox() self.fileFolderCombo.addItem(self.tr('File')) self.fileFolderCombo.addItem(self.tr('Folder')) if self.param is not None: self.fileFolderCombo.setCurrentIndex( 1 if self.param.isFolder else 0) self.horizontalLayout3.addWidget(self.fileFolderCombo) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_POINT or \ isinstance(self.param, ParameterPoint): self.horizontalLayout3.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() if self.param is not None: self.defaultTextBox.setText(self.param.default) self.horizontalLayout3.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayout3) self.horizontalLayout2.addWidget(QLabel(self.tr('Required'))) self.yesNoCombo = QComboBox() self.yesNoCombo.addItem(self.tr('Yes')) self.yesNoCombo.addItem(self.tr('No')) self.horizontalLayout2.addWidget(self.yesNoCombo) if self.param is not None: self.yesNoCombo.setCurrentIndex( 1 if self.param.optional else 0) self.verticalLayout.addLayout(self.horizontalLayout2) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.buttonBox.setObjectName('buttonBox') self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) self.verticalLayout.addWidget(self.buttonBox) self.setLayout(self.verticalLayout) def okPressed(self): description = unicode(self.nameTextBox.text()) if description.strip() == '': QMessageBox.warning(self, self.tr('Unable to define parameter'), self.tr('Invalid parameter name')) return if self.param is None: validChars = \ 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' safeName = ''.join(c for c in description if c in validChars) name = safeName.lower() i = 2 while name in self.alg.inputs: name = safeName.lower() + str(i) else: name = self.param.name if self.paramType \ == ModelerParameterDefinitionDialog.PARAMETER_BOOLEAN \ or isinstance(self.param, ParameterBoolean): self.param = ParameterBoolean(name, description, self.state.isChecked()) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or \ isinstance(self.param, ParameterTableField): if self.parentCombo.currentIndex() < 0: QMessageBox.warning(self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return parent = self.parentCombo.itemData(self.parentCombo.currentIndex()) self.param = ParameterTableField(name, description, parent) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_RASTER or \ isinstance(self.param, ParameterRaster): self.param = ParameterRaster( name, description, self.yesNoCombo.currentIndex() == 1) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE or \ isinstance(self.param, ParameterTable): self.param = ParameterTable( name, description, self.yesNoCombo.currentIndex() == 1) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or \ isinstance(self.param, ParameterVector): self.param = ParameterVector( name, description, [self.shapetypeCombo.currentIndex() - 1], self.yesNoCombo.currentIndex() == 1) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or \ isinstance(self.param, ParameterMultipleInput): self.param = ParameterMultipleInput( name, description, self.datatypeCombo.currentIndex() - 1, self.yesNoCombo.currentIndex() == 1) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or \ isinstance(self.param, ParameterNumber): try: vmin = unicode(self.minTextBox.text()).strip() if vmin == '': vmin = None else: vmin = float(vmin) vmax = unicode(self.maxTextBox.text()).strip() if vmax == '': vmax = None else: vmax = float(vmax) self.param = ParameterNumber(name, description, vmin, vmax, unicode(self.defaultTextBox.text())) except: QMessageBox.warning(self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or \ isinstance(self.param, ParameterString): self.param = ParameterString(name, description, unicode(self.defaultTextBox.text())) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_EXTENT or \ isinstance(self.param, ParameterExtent): self.param = ParameterExtent(name, description) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or \ isinstance(self.param, ParameterFile): isFolder = self.fileFolderCombo.currentIndex() == 1 self.param = ParameterFile(name, description, isFolder=isFolder) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_POINT or \ isinstance(self.param, ParameterPoint): self.param = ParameterPoint(name, description, unicode(self.defaultTextBox.text())) self.param.optional = self.yesNoCombo.currentIndex() == 1 self.close() def cancelPressed(self): self.param = None self.close()
class ModelerParameterDefinitionDialog(QDialog): PARAMETER_NUMBER = 'Number' PARAMETER_RASTER = 'Raster layer' PARAMETER_TABLE = 'Table' PARAMETER_VECTOR = 'Vector layer' PARAMETER_STRING = 'String' PARAMETER_BOOLEAN = 'Boolean' PARAMETER_TABLE_FIELD = 'Table field' PARAMETER_EXTENT = 'Extent' PARAMETER_FILE = 'File' PARAMETER_POINT = 'Point' # To add PARAMETER_MULTIPLE = 'Multiple input' PARAMETER_FIXED_TABLE = 'Fixed table' paramTypes = [ PARAMETER_BOOLEAN, PARAMETER_EXTENT, PARAMETER_FILE, PARAMETER_NUMBER, PARAMETER_RASTER, PARAMETER_STRING, PARAMETER_TABLE, PARAMETER_TABLE_FIELD, PARAMETER_VECTOR, PARAMETER_POINT ] def __init__(self, alg, paramType=None, param=None): self.alg = alg self.paramType = paramType self.param = param QDialog.__init__(self) self.setModal(True) self.setupUi() def setupUi(self): self.setWindowTitle(self.tr('Parameter definition')) self.verticalLayout = QVBoxLayout(self) self.verticalLayout.setSpacing(40) self.verticalLayout.setMargin(20) self.horizontalLayout = QHBoxLayout(self) self.horizontalLayout.setSpacing(2) self.horizontalLayout.setMargin(0) self.label = QLabel(self.tr('Parameter name')) self.horizontalLayout.addWidget(self.label) self.nameTextBox = QLineEdit() self.horizontalLayout.addWidget(self.nameTextBox) self.verticalLayout.addLayout(self.horizontalLayout) self.horizontalLayout2 = QHBoxLayout(self) self.horizontalLayout2.setSpacing(2) self.horizontalLayout2.setMargin(0) self.horizontalLayout3 = QHBoxLayout(self) self.horizontalLayout3.setSpacing(2) self.horizontalLayout3.setMargin(0) self.horizontalLayout4 = QHBoxLayout(self) self.horizontalLayout4.setSpacing(2) self.horizontalLayout4.setMargin(0) if isinstance(self.param, Parameter): self.nameTextBox.setText(self.param.description) if self.paramType == ModelerParameterDefinitionDialog.PARAMETER_BOOLEAN or \ isinstance(self.param, ParameterBoolean): self.state = QCheckBox() self.state.setText(self.tr('Checked')) self.state.setChecked(False) if self.param is not None: self.state.setChecked(True if self.param.value else False) self.horizontalLayout3.addWidget(self.state) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or \ isinstance(self.param, ParameterTableField): self.horizontalLayout3.addWidget(QLabel(self.tr('Parent layer'))) self.parentCombo = QComboBox() idx = 0 for param in self.alg.inputs.values(): if isinstance(param.param, (ParameterVector, ParameterTable)): self.parentCombo.addItem(param.param.description, param.param.name) if self.param is not None: if self.param.parent == param.param.name: self.parentCombo.setCurrentIndex(idx) idx += 1 self.horizontalLayout3.addWidget(self.parentCombo) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or \ isinstance(self.param, ParameterVector): self.horizontalLayout3.addWidget(QLabel(self.tr('Shape type'))) self.shapetypeCombo = QComboBox() self.shapetypeCombo.addItem(self.tr('Any')) self.shapetypeCombo.addItem(self.tr('Point')) self.shapetypeCombo.addItem(self.tr('Line')) self.shapetypeCombo.addItem(self.tr('Polygon')) if self.param is not None: self.shapetypeCombo.setCurrentIndex(self.param.shapetype[0] + 1) self.horizontalLayout3.addWidget(self.shapetypeCombo) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or \ isinstance(self.param, ParameterMultipleInput): self.horizontalLayout3.addWidget(QLabel(self.tr('Data type'))) self.datatypeCombo = QComboBox() self.datatypeCombo.addItem(self.tr('Vector (any)')) self.datatypeCombo.addItem(self.tr('Vector (point)')) self.datatypeCombo.addItem(self.tr('Vector (line)')) self.datatypeCombo.addItem(self.tr('Vector (polygon)')) self.datatypeCombo.addItem(self.tr('Raster')) self.datatypeCombo.addItem(self.tr('Table')) if self.param is not None: self.datatypeCombo.setCurrentIndex(self.param.datatype + 1) self.horizontalLayout3.addWidget(self.datatypeCombo) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or \ isinstance(self.param, ParameterNumber): self.horizontalLayout3.addWidget(QLabel(self.tr('Min/Max values'))) self.minTextBox = QLineEdit() self.maxTextBox = QLineEdit() if self.param is not None: self.minTextBox.setText(unicode(self.param.min)) self.maxTextBox.setText(unicode(self.param.max)) self.horizontalLayout3.addWidget(self.minTextBox) self.horizontalLayout3.addWidget(self.maxTextBox) self.verticalLayout.addLayout(self.horizontalLayout3) self.horizontalLayout4.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() self.defaultTextBox.setText(self.tr('0')) if self.param is not None: default = self.param.default if self.param.isInteger: default = int(math.floor(default)) self.defaultTextBox.setText(unicode(default)) self.horizontalLayout4.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayout4) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or \ isinstance(self.param, ParameterString): self.horizontalLayout3.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() if self.param is not None: self.defaultTextBox.setText(self.param.default) self.horizontalLayout3.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or \ isinstance(self.param, ParameterFile): self.horizontalLayout3.addWidget(QLabel(self.tr('Type'))) self.fileFolderCombo = QComboBox() self.fileFolderCombo.addItem(self.tr('File')) self.fileFolderCombo.addItem(self.tr('Folder')) if self.param is not None: self.fileFolderCombo.setCurrentIndex( 1 if self.param.isFolder else 0) self.horizontalLayout3.addWidget(self.fileFolderCombo) self.verticalLayout.addLayout(self.horizontalLayout3) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_POINT or \ isinstance(self.param, ParameterPoint): self.horizontalLayout3.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() if self.param is not None: self.defaultTextBox.setText(self.param.default) self.horizontalLayout3.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayout3) self.horizontalLayout2.addWidget(QLabel(self.tr('Required'))) self.yesNoCombo = QComboBox() self.yesNoCombo.addItem(self.tr('Yes')) self.yesNoCombo.addItem(self.tr('No')) self.horizontalLayout2.addWidget(self.yesNoCombo) if self.param is not None: self.yesNoCombo.setCurrentIndex(1 if self.param.optional else 0) self.verticalLayout.addLayout(self.horizontalLayout2) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.buttonBox.setObjectName('buttonBox') self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) self.verticalLayout.addWidget(self.buttonBox) self.setLayout(self.verticalLayout) def okPressed(self): description = unicode(self.nameTextBox.text()) if description.strip() == '': QMessageBox.warning(self, self.tr('Unable to define parameter'), self.tr('Invalid parameter name')) return if self.param is None: validChars = \ 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' safeName = ''.join(c for c in description if c in validChars) name = safeName.lower() i = 2 while name in self.alg.inputs: name = safeName.lower() + str(i) else: name = self.param.name if self.paramType \ == ModelerParameterDefinitionDialog.PARAMETER_BOOLEAN \ or isinstance(self.param, ParameterBoolean): self.param = ParameterBoolean(name, description, self.state.isChecked()) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or \ isinstance(self.param, ParameterTableField): if self.parentCombo.currentIndex() < 0: QMessageBox.warning( self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return parent = self.parentCombo.itemData(self.parentCombo.currentIndex()) self.param = ParameterTableField(name, description, parent) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_RASTER or \ isinstance(self.param, ParameterRaster): self.param = ParameterRaster(name, description, self.yesNoCombo.currentIndex() == 1) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE or \ isinstance(self.param, ParameterTable): self.param = ParameterTable(name, description, self.yesNoCombo.currentIndex() == 1) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or \ isinstance(self.param, ParameterVector): self.param = ParameterVector( name, description, [self.shapetypeCombo.currentIndex() - 1], self.yesNoCombo.currentIndex() == 1) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or \ isinstance(self.param, ParameterMultipleInput): self.param = ParameterMultipleInput( name, description, self.datatypeCombo.currentIndex() - 1, self.yesNoCombo.currentIndex() == 1) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or \ isinstance(self.param, ParameterNumber): try: vmin = unicode(self.minTextBox.text()).strip() if vmin == '': vmin = None else: vmin = float(vmin) vmax = unicode(self.maxTextBox.text()).strip() if vmax == '': vmax = None else: vmax = float(vmax) self.param = ParameterNumber( name, description, vmin, vmax, unicode(self.defaultTextBox.text())) except: QMessageBox.warning( self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or \ isinstance(self.param, ParameterString): self.param = ParameterString(name, description, unicode(self.defaultTextBox.text())) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_EXTENT or \ isinstance(self.param, ParameterExtent): self.param = ParameterExtent(name, description) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or \ isinstance(self.param, ParameterFile): isFolder = self.fileFolderCombo.currentIndex() == 1 self.param = ParameterFile(name, description, isFolder=isFolder) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_POINT or \ isinstance(self.param, ParameterPoint): self.param = ParameterPoint(name, description, unicode(self.defaultTextBox.text())) self.param.optional = self.yesNoCombo.currentIndex() == 1 self.close() def cancelPressed(self): self.param = None self.close()
class BatchOutputSelectionPanel(QWidget): def __init__(self, output, alg, row, col, panel): super(BatchOutputSelectionPanel, self).__init__(None) self.alg = alg self.row = row self.col = col self.output = output self.panel = panel self.table = self.panel.tblParameters self.horizontalLayout = QHBoxLayout(self) self.horizontalLayout.setSpacing(2) self.horizontalLayout.setMargin(0) self.text = QLineEdit() self.text.setText('') self.text.setMinimumWidth(300) self.text.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.horizontalLayout.addWidget(self.text) self.pushButton = QPushButton() self.pushButton.setText('...') self.pushButton.clicked.connect(self.showSelectionDialog) self.horizontalLayout.addWidget(self.pushButton) self.setLayout(self.horizontalLayout) def showSelectionDialog(self): if isinstance(self.output, OutputDirectory): self.selectDirectory() return filefilter = self.output.getFileFilter(self.alg) settings = QSettings() if settings.contains('/Processing/LastBatchOutputPath'): path = unicode(settings.value('/Processing/LastBatchOutputPath')) else: path = '' filename, selectedFileFilter = QFileDialog.getSaveFileNameAndFilter(self, self.tr('Save file'), path, filefilter) print filename, selectedFileFilter if filename: if not filename.lower().endswith( tuple(re.findall("\*(\.[a-z]{1,10})", filefilter))): ext = re.search("\*(\.[a-z]{1,10})", selectedFileFilter) if ext: filename += ext.group(1) settings.setValue('/Processing/LastBatchOutputPath', os.path.dirname(filename)) dlg = AutofillDialog(self.alg) dlg.exec_() if dlg.mode is not None: try: if dlg.mode == AutofillDialog.DO_NOT_AUTOFILL: self.table.cellWidget(self.row, self.col).setValue(filename) elif dlg.mode == AutofillDialog.FILL_WITH_NUMBERS: n = self.table.rowCount() - self.row for i in range(n): name = filename[:filename.rfind('.')] \ + unicode(i + 1) + filename[filename.rfind('.'):] self.table.cellWidget(i + self.row, self.col).setValue(name) elif dlg.mode == AutofillDialog.FILL_WITH_PARAMETER: n = self.table.rowCount() - self.row for i in range(n): widget = self.table.cellWidget(i + self.row, dlg.param) param = self.alg.parameters[dlg.param] if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable, ParameterMultipleInput)): s = unicode(widget.getText()) s = os.path.basename(s) s = os.path.splitext(s)[0] elif isinstance(param, ParameterBoolean): s = unicode(widget.currentIndex() == 0) elif isinstance(param, ParameterSelection): s = unicode(widget.currentText()) elif isinstance(param, ParameterFixedTable): s = unicode(widget.table) else: s = unicode(widget.text()) name = filename[:filename.rfind('.')] + s \ + filename[filename.rfind('.'):] self.table.cellWidget(i + self.row, self.col).setValue(name) except: pass def selectDirectory(self): settings = QSettings() if settings.contains('/Processing/LastBatchOutputPath'): lastDir = unicode(settings.value('/Processing/LastBatchOutputPath')) else: lastDir = '' dirName = QFileDialog.getExistingDirectory(self, self.tr('Select directory'), lastDir, QFileDialog.ShowDirsOnly) if dirName: self.table.cellWidget(self.row, self.col).setValue(dirName) settings.setValue('/Processing/LastBatchOutputPath', dirName) def setValue(self, text): return self.text.setText(text) def getValue(self): return unicode(self.text.text())
class CalculatorModelerParametersDialog(ModelerParametersDialog): def setupUi(self): self.valueItems = {} self.dependentItems = {} self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.infoText = QTextEdit() numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) text = self.tr( 'You can refer to model values in your formula, using ' 'single-letter variables, as follows:\n', 'CalculatorModelerParametersDialog') ichar = 97 if numbers: for number in numbers: text += chr(ichar) + '->' + self.resolveValueDescription( number) + '\n' ichar += 1 else: text += self.tr('\n - No numerical variables are available.', 'CalculatorModelerParametersDialog') self.infoText.setText(text) self.infoText.setEnabled(False) self.formulaText = QLineEdit() if hasattr(self.formulaText, 'setPlaceholderText'): self.formulaText.setPlaceholderText( self.tr('[Enter your formula here]', 'CalculatorModelerParametersDialog')) if self._algName is not None: alg = self.model.algs[self._algName] self.formulaText.setText(alg.params[FORMULA]) self.setWindowTitle( self.tr('Calculator', 'CalculatorModelerParametersDialog')) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(2) self.verticalLayout.setMargin(0) self.verticalLayout.addWidget(self.infoText) self.verticalLayout.addWidget(self.formulaText) self.verticalLayout.addWidget(self.buttonBox) self.setLayout(self.verticalLayout) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) QMetaObject.connectSlotsByName(self) def createAlgorithm(self): alg = Algorithm('modelertools:calculator') alg.setName(self.model) alg.description = self.tr('Calculator', 'CalculatorModelerParametersDialog') formula = self.formulaText.text() alg.params[FORMULA] = formula for i in xrange(AVAILABLE_VARIABLES): paramname = NUMBER + unicode(i) alg.params[paramname] = None numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) used = [] for i in range(len(numbers)): if unicode(chr(i + 97)) in formula: used.append(numbers[i]) for i, variable in enumerate(used): paramname = NUMBER + unicode(i) alg.params[paramname] = variable # TODO check formula is correct return alg
class BatchInputSelectionPanel(QWidget): def __init__(self, param, row, col, panel): super(BatchInputSelectionPanel, self).__init__(None) self.param = param self.panel = panel self.table = self.panel.tblParameters self.row = row self.col = col self.horizontalLayout = QHBoxLayout(self) self.horizontalLayout.setSpacing(0) self.horizontalLayout.setMargin(0) self.text = QLineEdit() self.text.setMinimumWidth(300) self.text.setText('') self.text.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.horizontalLayout.addWidget(self.text) self.pushButton = QPushButton() self.pushButton.setText('...') self.pushButton.clicked.connect(self.showPopupMenu) self.horizontalLayout.addWidget(self.pushButton) self.setLayout(self.horizontalLayout) def showPopupMenu(self): popupmenu = QMenu() if not (isinstance(self.param, ParameterMultipleInput) and self.param.datatype == ParameterMultipleInput.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()) def showLayerSelectionDialog(self): if (isinstance(self.param, ParameterRaster) or (isinstance(self.param, ParameterMultipleInput) and self.param.datatype == ParameterMultipleInput.TYPE_RASTER)): layers = dataobjects.getRasterLayers() elif isinstance(self.param, ParameterTable): layers = dataobjects.getTables() else: if isinstance(self.param, ParameterVector): datatype = self.param.shapetype 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.text.setText(layers[selected[0]].name()) 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).setText( layers[layeridx].name()) def showFileSelectionDialog(self): settings = QSettings() text = unicode(self.text.text()) if os.path.isdir(text): path = text elif os.path.isdir(os.path.dirname(text)): path = os.path.dirname(text) elif settings.contains('/Processing/LastInputPath'): path = unicode(settings.value('/Processing/LastInputPath')) else: path = '' ret = QFileDialog.getOpenFileNames( self, self.tr('Open file'), path, self.tr('All files(*.*);;') + self.param.getFileFilter()) if ret: files = list(ret) settings.setValue('/Processing/LastInputPath', os.path.dirname(unicode(files[0]))) for i, filename in enumerate(files): files[i] = dataobjects.getRasterSublayer(filename, self.param) if len(files) == 1: self.text.setText(files[0]) else: if isinstance(self.param, ParameterMultipleInput): self.text.setText(';'.join(unicode(f) for f in files)) else: rowdif = len(files) - (self.table.rowCount() - self.row) for i in range(rowdif): self.panel.addRow() for i, f in enumerate(files): self.table.cellWidget(i + self.row, self.col).setText(f) def setText(self, text): return self.text.setText(text) def getText(self): return self.text.text()
def setupUi(self): self.resize(250, 250) self.move(300, 300) self.setWindowsTitle('Kalkulator') self.lineEdit = QLineEdit() self.lineEdit.setAlignment(Qt.AlignRight) self.lineEdit.setFont(QFont('SansSerif', 14)) self.lineEdit.setDisabled(true) self._7Button = QPushButton('7') self._8Button = QPushButton('8') self._9Button = QPushButton('9') self.divButton = QPushButton('/') self.clearButton = QPushButton("CLR") self._4Button = QPushButton('4') self._5Button = QPushButton('5') self._6Button = QPushButton('6') self.mulButton = QPushButton('x') self._1Button = QPushButton('1') self._2Button = QPushButton('2') self._3Button = QPushButton('3') self.minusButton = QPushButton('-') self._0Button = QPushButton('0') self.dotButton = QPushButton('.') self.percentageButton = QPushButton('%') self.plusButton = QPushButton('+') self.calculateButton = QPushButton('=') layout = QGridLayout() layout.addWidget(self.lineEdit, 0, 0, 1, 4) layout.addWidget(self._7Button, 1, 0) layout.addWidget(self._8Button, 1, 1) layout.addWidget(self._9Button, 1, 2) layout.addWidget(self.clearButton, 1, 3) layout.addWidget(self._4Button, 2, 0) layout.addWidget(self._5Button, 2, 1) layout.addWidget(self._6Button, 2, 2) layout.addWidget(self.mulButton, 2, 3) layout.addWidget(self._1Button, 3, 0) layout.addWidget(self._2Button, 3, 1) layout.addWidget(self._3Button, 3, 2) layout.addWidget(self.divButton, 3, 3) layout.addWidget(self._0Button, 4, 0) layout.addWidget(self.dotButton, 4, 1) layout.addWidget(self.minusButton, 4, 2) layout.addWidget(self.plusButton, 4, 3) layout.addWidget(self.percentageButton, 5, 0) layout.addWidget(self.calculateButton, 5, 1, 1, 3) self.setLayout(layout) self._0Button.clicked.connect(lambda: self.writeDigit(0)) self._1Button.clicked.connect(lambda: self.writeDigit(1)) self._2Button.clicked.connect(lambda: self.writeDigit(2)) self._3Button.clicked.connect(lambda: self.writeDigit(3)) self._4Button.clicked.connect(lambda: self.writeDigit(4)) self._5Button.clicked.connect(lambda: self.writeDigit(5)) self._6Button.clicked.connect(lambda: self.writeDigit(6)) self._7Button.clicked.connect(lambda: self.writeDigit(7)) self._8Button.clicked.connect(lambda: self.writeDigit(8)) self._9Button.clicked.connect(lambda: self.writeDigit(9)) self.mulButton.clicked.connect(lambda: self.writeOperator('*')) self.divButton.clicked.connect(lambda: self.writeOperator('/')) self.plusButton.clicked.connect(lambda: self.writeOperator('+')) self.minusButton.clicked.connect(lambda: self.writeOperator('-')) self.dotButton.clicked.connect(self.writePoint) self.clearButton.clicked.connect(self.lineEdit.clear) self.calculateButton.clicked.connect(self.calculateButtonClick) self.percentageButton.clicked.connect(self.percentageButtonClick) def writeDigit(self, digit): if digit in range(0, 10): self.lineEdit.setText(self.lineEdit.text() + str(digit)) def writeOperator(self, operator): if len(self.lineEdit.text()) == 0: return if operator in ['*', '/', '+', '-']: if self.lineEdit.text()[-1] in ['*', '/', '+', '-']: self.lineEdit.setText(self.lineEdit.text()[:-1] + operator) else: self.lineEdit.setText(self.lineEdit.text() + operator) def writePoint(self): if len(self.lineEdit.text()) == 0 or \ self.lineEdit.text() [-1] in ['*', '/', '+', '-']: return self.lineEdit.setText(self.lineEdit.text() + '.') def calculateButtonClick(self): expression = self.lineEdit.text() if len(expression) == 0: return try: result = eval(expression) self.lineEdit.setText(str(result)) except: self.lineEdit.setText('ERROR') def percentageButtonClick(self): expression = self.lineEdit.text() if len(expression) == 0: return try: result = eval(expression) / 100 self.lineEdit.setText(str(result)) except: self.lineEdit.setText('ERROR')
def setupUi(self): self.labels = {} self.widgets = {} self.checkBoxes = {} self.showAdvanced = False self.valueItems = {} self.dependentItems = {} self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) tooltips = self._alg.getParameterDescriptions() self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(5) self.verticalLayout.setMargin(20) hLayout = QHBoxLayout() hLayout.setSpacing(5) hLayout.setMargin(0) descriptionLabel = QLabel(self.tr("Description")) self.descriptionBox = QLineEdit() self.descriptionBox.setText(self._alg.name) hLayout.addWidget(descriptionLabel) hLayout.addWidget(self.descriptionBox) self.verticalLayout.addLayout(hLayout) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.verticalLayout.addWidget(line) for param in self._alg.parameters: if param.isAdvanced: self.advancedButton = QPushButton() self.advancedButton.setText( self.tr('Show advanced parameters')) self.advancedButton.clicked.connect( self.showAdvancedParametersClicked) advancedButtonHLayout = QHBoxLayout() advancedButtonHLayout.addWidget(self.advancedButton) advancedButtonHLayout.addStretch() self.verticalLayout.addLayout(advancedButtonHLayout) break for param in self._alg.parameters: if param.hidden: continue desc = param.description if isinstance(param, ParameterExtent): desc += self.tr('(xmin, xmax, ymin, ymax)') if isinstance(param, ParameterPoint): desc += self.tr('(x, y)') label = QLabel(desc) self.labels[param.name] = label widget = self.getWidgetFromParameter(param) self.valueItems[param.name] = widget if param.name in tooltips.keys(): tooltip = tooltips[param.name] else: tooltip = param.description label.setToolTip(tooltip) widget.setToolTip(tooltip) if param.isAdvanced: label.setVisible(self.showAdvanced) widget.setVisible(self.showAdvanced) self.widgets[param.name] = widget self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(widget) for output in self._alg.outputs: if output.hidden: continue if isinstance(output, (OutputRaster, OutputVector, OutputTable, OutputHTML, OutputFile, OutputDirectory)): label = QLabel(output.description + '<' + output.__class__.__name__ + '>') item = QLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(item) self.valueItems[output.name] = item label = QLabel(' ') self.verticalLayout.addWidget(label) label = QLabel(self.tr('Parent algorithms')) self.dependenciesPanel = self.getDependenciesPanel() self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(self.dependenciesPanel) self.verticalLayout.addStretch(1000) self.setLayout(self.verticalLayout) self.setPreviousValues() self.setWindowTitle(self._alg.name) self.verticalLayout2 = QVBoxLayout() self.verticalLayout2.setSpacing(2) self.verticalLayout2.setMargin(0) self.tabWidget = QTabWidget() self.tabWidget.setMinimumWidth(300) self.paramPanel = QWidget() self.paramPanel.setLayout(self.verticalLayout) self.scrollArea = QScrollArea() self.scrollArea.setWidget(self.paramPanel) self.scrollArea.setWidgetResizable(True) self.tabWidget.addTab(self.scrollArea, self.tr('Parameters')) self.webView = QWebView() html = None url = None isText, help = self._alg.help() if help is not None: if isText: html = help else: url = QUrl(help) else: html = self.tr('<h2>Sorry, no help is available for this ' 'algorithm.</h2>') try: if html: self.webView.setHtml(html) elif url: self.webView.load(url) except: self.webView.setHtml( self.tr('<h2>Could not open help file :-( </h2>')) self.tabWidget.addTab(self.webView, 'Help') self.verticalLayout2.addWidget(self.tabWidget) self.verticalLayout2.addWidget(self.buttonBox) self.setLayout(self.verticalLayout2) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) QMetaObject.connectSlotsByName(self)
class ModelerParametersDialog(QDialog): ENTER_NAME = '[Enter name if this is a final result]' NOT_SELECTED = '[Not selected]' USE_MIN_COVERING_EXTENT = '[Use min covering extent]' def __init__(self, alg, model, algName=None): QDialog.__init__(self) self.setModal(True) #The algorithm to define in this dialog. It is an instance of GeoAlgorithm self._alg = alg #The resulting algorithm after the user clicks on OK. it is an instance of the container Algorithm class self.alg = None #The model this algorithm is going to be added to self.model = model #The name of the algorithm in the model, in case we are editing it and not defining it for the first time self._algName = algName self.setupUi() self.params = None def setupUi(self): self.labels = {} self.widgets = {} self.checkBoxes = {} self.showAdvanced = False self.valueItems = {} self.dependentItems = {} self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) tooltips = self._alg.getParameterDescriptions() self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(5) self.verticalLayout.setMargin(20) hLayout = QHBoxLayout() hLayout.setSpacing(5) hLayout.setMargin(0) descriptionLabel = QLabel(self.tr("Description")) self.descriptionBox = QLineEdit() self.descriptionBox.setText(self._alg.name) hLayout.addWidget(descriptionLabel) hLayout.addWidget(self.descriptionBox) self.verticalLayout.addLayout(hLayout) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.verticalLayout.addWidget(line) for param in self._alg.parameters: if param.isAdvanced: self.advancedButton = QPushButton() self.advancedButton.setText(self.tr('Show advanced parameters')) self.advancedButton.clicked.connect( self.showAdvancedParametersClicked) advancedButtonHLayout = QHBoxLayout() advancedButtonHLayout.addWidget(self.advancedButton) advancedButtonHLayout.addStretch() self.verticalLayout.addLayout(advancedButtonHLayout) break for param in self._alg.parameters: if param.hidden: continue desc = param.description if isinstance(param, ParameterExtent): desc += self.tr('(xmin, xmax, ymin, ymax)') if isinstance(param, ParameterPoint): desc += self.tr('(x, y)') label = QLabel(desc) self.labels[param.name] = label widget = self.getWidgetFromParameter(param) self.valueItems[param.name] = widget if param.name in tooltips.keys(): tooltip = tooltips[param.name] else: tooltip = param.description label.setToolTip(tooltip) widget.setToolTip(tooltip) if param.isAdvanced: label.setVisible(self.showAdvanced) widget.setVisible(self.showAdvanced) self.widgets[param.name] = widget self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(widget) for output in self._alg.outputs: if output.hidden: continue if isinstance(output, (OutputRaster, OutputVector, OutputTable, OutputHTML, OutputFile, OutputDirectory)): label = QLabel(output.description + '<' + output.__class__.__name__ + '>') item = QLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(item) self.valueItems[output.name] = item label = QLabel(' ') self.verticalLayout.addWidget(label) label = QLabel(self.tr('Parent algorithms')) self.dependenciesPanel = self.getDependenciesPanel() self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(self.dependenciesPanel) self.verticalLayout.addStretch(1000) self.setLayout(self.verticalLayout) self.setPreviousValues() self.setWindowTitle(self._alg.name) self.verticalLayout2 = QVBoxLayout() self.verticalLayout2.setSpacing(2) self.verticalLayout2.setMargin(0) self.tabWidget = QTabWidget() self.tabWidget.setMinimumWidth(300) self.paramPanel = QWidget() self.paramPanel.setLayout(self.verticalLayout) self.scrollArea = QScrollArea() self.scrollArea.setWidget(self.paramPanel) self.scrollArea.setWidgetResizable(True) self.tabWidget.addTab(self.scrollArea, self.tr('Parameters')) self.webView = QWebView() html = None url = None isText, help = self._alg.help() if help is not None: if isText: html = help else: url = QUrl(help) else: html = self.tr('<h2>Sorry, no help is available for this ' 'algorithm.</h2>') try: if html: self.webView.setHtml(html) elif url: self.webView.load(url) except: self.webView.setHtml(self.tr('<h2>Could not open help file :-( </h2>')) self.tabWidget.addTab(self.webView, 'Help') self.verticalLayout2.addWidget(self.tabWidget) self.verticalLayout2.addWidget(self.buttonBox) self.setLayout(self.verticalLayout2) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) QMetaObject.connectSlotsByName(self) def getAvailableDependencies(self): if self._algName is None: dependent = [] else: dependent = self.model.getDependentAlgorithms(self._algName) opts = [] for alg in self.model.algs.values(): if alg.name not in dependent: opts.append(alg) return opts def getDependenciesPanel(self): return MultipleInputPanel([alg.algorithm.name for alg in self.getAvailableDependencies()]) def showAdvancedParametersClicked(self): self.showAdvanced = not self.showAdvanced if self.showAdvanced: self.advancedButton.setText(self.tr('Hide advanced parameters')) else: self.advancedButton.setText(self.tr('Show advanced parameters')) for param in self._alg.parameters: if param.isAdvanced: self.labels[param.name].setVisible(self.showAdvanced) self.widgets[param.name].setVisible(self.showAdvanced) def getAvailableValuesOfType(self, paramType, outType=None): values = [] inputs = self.model.inputs for i in inputs.values(): param = i.param if isinstance(param, paramType): values.append(ValueFromInput(param.name)) if outType is None: return values if self._algName is None: dependent = [] else: dependent = self.model.getDependentAlgorithms(self._algName) for alg in self.model.algs.values(): if alg.name not in dependent: for out in alg.algorithm.outputs: if isinstance(out, outType): values.append(ValueFromOutput(alg.name, out.name)) return values def resolveValueDescription(self, value): if isinstance(value, ValueFromInput): return self.model.inputs[value.name].param.description else: alg = self.model.algs[value.alg] return self.tr("'%s' from algorithm '%s'") % (alg.algorithm.getOutputFromName(value.output).description, alg.description) def getWidgetFromParameter(self, param): if isinstance(param, ParameterRaster): item = QComboBox() layers = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) if param.optional: item.addItem(self.NOT_SELECTED, None) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterVector): item = QComboBox() layers = self.getAvailableValuesOfType(ParameterVector, OutputVector) if param.optional: item.addItem(self.NOT_SELECTED, None) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterTable): item = QComboBox() tables = self.getAvailableValuesOfType(ParameterTable, OutputTable) layers = self.getAvailableValuesOfType(ParameterVector, OutputVector) if param.optional: item.addItem(self.NOT_SELECTED, None) for table in tables: item.addItem(self.resolveValueDescription(table), table) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterBoolean): item = QComboBox() item.addItem('Yes') item.addItem('No') bools = self.getAvailableValuesOfType(ParameterBoolean, None) for b in bools: item.addItem(self.resolveValueDescription(b), b) if param.default: item.setCurrentIndex(0) else: item.setCurrentIndex(1) elif isinstance(param, ParameterSelection): item = QComboBox() item.addItems(param.options) item.setCurrentIndex(param.default or 1) elif isinstance(param, ParameterFixedTable): item = FixedTablePanel(param) elif isinstance(param, ParameterRange): item = RangePanel(param) elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType(ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) opts = [] for opt in options: opts.append(self.resolveValueDescription(opt)) item = MultipleInputPanel(opts) elif isinstance(param, ParameterString): strings = self.getAvailableValuesOfType(ParameterString, OutputString) options = [(self.resolveValueDescription(s), s) for s in strings] if param.multiline: item = MultilineTextPanel(options) item.setText(unicode(param.default or "")) else: item = QComboBox() item.setEditable(True) for desc, val in options: item.addItem(desc, val) item.setEditText(unicode(param.default or "")) elif isinstance(param, ParameterTableField): item = QComboBox() item.setEditable(True) fields = self.getAvailableValuesOfType(ParameterTableField, None) for f in fields: item.addItem(self.resolveValueDescription(f), f) elif isinstance(param, ParameterNumber): item = QComboBox() item.setEditable(True) numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) for n in numbers: item.addItem(self.resolveValueDescription(n), n) item.setEditText(unicode(param.default)) elif isinstance(param, ParameterCrs): item = CrsSelectionPanel(param.default) elif isinstance(param, ParameterExtent): item = QComboBox() item.setEditable(True) extents = self.getAvailableValuesOfType(ParameterExtent, OutputExtent) if self.canUseAutoExtent(): item.addItem(self.USE_MIN_COVERING_EXTENT, None) for ex in extents: item.addItem(self.resolveValueDescription(ex), ex) if not self.canUseAutoExtent(): item.setEditText(unicode(param.default)) elif isinstance(param, ParameterPoint): item = QComboBox() item.setEditable(True) points = self.getAvailableValuesOfType(ParameterPoint) for p in points: item.addItem(self.resolveValueDescription(p), p) item.setEditText(unicode(param.default)) elif isinstance(param, ParameterFile): item = QComboBox() item.setEditable(True) files = self.getAvailableValuesOfType(ParameterFile, OutputFile) for f in files: item.addItem(self.resolveValueDescription(f), f) elif isinstance(param, ParameterGeometryPredicate): item = GeometryPredicateSelectionPanel(param.enabledPredicates) else: item = QLineEdit() try: item.setText(unicode(param.default)) except: pass return item def canUseAutoExtent(self): for param in self._alg.parameters: if isinstance(param, (ParameterRaster, ParameterVector, ParameterMultipleInput)): return True return False def setTableContent(self): params = self._alg.parameters outputs = self._alg.outputs visibleParams = [p for p in params if not p.hidden] visibleOutputs = [p for o in outputs if not o.hidden] self.tableWidget.setRowCount(len(visibleParams) + len(visibleOutputs)) for i, param in visibleParams: item = QTableWidgetItem(param.description) item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setItem(i, 0, item) item = self.getWidgetFromParameter(param) self.valueItems[param.name] = item self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22) for i, output in visibleOutputs: item = QTableWidgetItem(output.description + '<' + output.__module__.split('.')[-1] + '>') item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setItem(i, 0, item) item = QLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.valueItems[output.name] = item self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22) def setComboBoxValue(self, combo, value, param): if isinstance(value, list): value = value[0] items = [combo.itemData(i) for i in range(combo.count())] try: idx = items.index(value) combo.setCurrentIndex(idx) return except ValueError: pass if combo.isEditable(): if value is not None: combo.setEditText(unicode(value)) elif isinstance(param, ParameterSelection): combo.setCurrentIndex(int(value)) elif isinstance(param, ParameterBoolean): if value: combo.setCurrentIndex(0) else: combo.setCurrentIndex(1) def setPreviousValues(self): if self._algName is not None: alg = self.model.algs[self._algName] self.descriptionBox.setText(alg.description) for param in alg.algorithm.parameters: if param.hidden: continue widget = self.valueItems[param.name] if param.name in alg.params: value = alg.params[param.name] else: value = None if isinstance(param, ( ParameterRaster, ParameterVector, ParameterTable, ParameterTableField, ParameterSelection, ParameterNumber, ParameterBoolean, ParameterExtent, ParameterFile, ParameterPoint )): self.setComboBoxValue(widget, value, param) elif isinstance(param, ParameterString): if param.multiline: widget.setValue(value) else: self.setComboBoxValue(widget, value, param) elif isinstance(param, ParameterCrs): widget.setAuthId(value) elif isinstance(param, ParameterFixedTable): pass # TODO! elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType(ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) selected = [] for i, opt in enumerate(options): if opt in value: selected.append(i) widget.setSelectedItems(selected) elif isinstance(param, ParameterGeometryPredicate): widget.setValue(value) for name, out in alg.outputs.iteritems(): widget = self.valueItems[name].setText(out.description) selected = [] dependencies = self.getAvailableDependencies() for idx, dependency in enumerate(dependencies): if dependency.name in alg.dependencies: selected.append(idx) self.dependenciesPanel.setSelectedItems(selected) def createAlgorithm(self): alg = Algorithm(self._alg.commandLineName()) alg.setName(self.model) alg.description = self.descriptionBox.text() params = self._alg.parameters outputs = self._alg.outputs for param in params: if param.hidden: continue if not self.setParamValue(alg, param, self.valueItems[param.name]): return None for output in outputs: if not output.hidden: name = unicode(self.valueItems[output.name].text()) if name.strip() != '' and name != ModelerParametersDialog.ENTER_NAME: alg.outputs[output.name] = ModelerOutput(name) selectedOptions = self.dependenciesPanel.selectedoptions availableDependencies = self.getAvailableDependencies() for selected in selectedOptions: alg.dependencies.append(availableDependencies[selected].name) return alg def setParamValueLayerOrTable(self, alg, param, widget): idx = widget.currentIndex() if idx < 0: return False else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamTableFieldValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = unicode(widget.currentText()).strip() if s == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = s return True else: alg.params[param.name] = widget.itemData(widget.currentIndex()) return True def setParamStringValue(self, alg, param, widget): if param.multiline: value = widget.getValue() option = widget.getOption() if option == MultilineTextPanel.USE_TEXT: if value == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = value else: alg.params[param.name] = value else: idx = widget.findText(widget.currentText()) if idx < 0: value = widget.currentText().strip() if value == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = value else: alg.params[param.name] = widget.itemData(widget.currentIndex()) return True def setParamFileValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: value = widget.currentText() else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamNumberValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = widget.currentText().strip() if s: try: value = float(s) except: return False elif param.optional: value = None else: return False else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamExtentValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = unicode(widget.currentText()).strip() if s: try: tokens = s.split(',') if len(tokens) != 4: return False for token in tokens: float(token) except: return False elif param.optional: s = None else: return False alg.params[param.name] = [s] else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamPointValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = unicode(widget.currentText()).strip() if s: try: tokens = s.split(',') if len(tokens) != 2: return False for token in tokens: float(token) except: return False elif param.optional: s = None else: return False alg.params[param.name] = [s] else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamValue(self, alg, param, widget): if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable)): return self.setParamValueLayerOrTable(alg, param, widget) elif isinstance(param, ParameterBoolean): if widget.currentIndex() < 2: value = widget.currentIndex() == 0 else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True elif isinstance(param, ParameterString): return self.setParamStringValue(alg, param, widget) elif isinstance(param, ParameterNumber): return self.setParamNumberValue(alg, param, widget) elif isinstance(param, ParameterExtent): return self.setParamExtentValue(alg, param, widget) elif isinstance(param, ParameterPoint): return self.setParamPointValue(alg, param, widget) elif isinstance(param, ParameterFile): return self.setParamFileValue(alg, param, widget) elif isinstance(param, ParameterSelection): alg.params[param.name] = widget.currentIndex() return True elif isinstance(param, ParameterRange): alg.params[param.name] = widget.getValue() return True elif isinstance(param, ParameterCrs): authid = widget.getValue() if authid is None and not param.optional: return False alg.params[param.name] = authid return True elif isinstance(param, ParameterFixedTable): table = widget.table if not bool(table) and not param.optional: return False alg.params[param.name] = ParameterFixedTable.tableToString(table) return True elif isinstance(param, ParameterTableField): return self.setParamTableFieldValue(alg, param, widget) elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType(ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) values = [options[i] for i in widget.selectedoptions] if len(values) == 0 and not param.optional: return False alg.params[param.name] = values return True elif isinstance(param, ParameterGeometryPredicate): alg.params[param.name] = widget.value() return True else: alg.params[param.name] = unicode(widget.text()) return True def okPressed(self): self.alg = self.createAlgorithm() if self.alg is not None: self.close() else: QMessageBox.warning(self, self.tr('Unable to add algorithm'), self.tr('Wrong or missing parameter values')) def cancelPressed(self): self.alg = None self.close()