def setupUi(self): self.setMinimumWidth(500) self.setMinimumHeight(400) self.resize(640, 450) self.verticalLayout = QVBoxLayout(self) self.verticalLayout.setSpacing(2) self.verticalLayout.setMargin(0) self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.verticalLayout.addWidget(self.bar) self.tree = QTreeWidget(self) self.tree.setAlternatingRowColors(True) self.verticalLayout.addWidget(self.tree) self.horizontalLayout = QHBoxLayout(self) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok) self.horizontalLayout.addWidget(self.buttonBox) self.verticalLayout.addLayout(self.horizontalLayout) self.setWindowTitle("Configuration options") self.tree.headerItem().setText(0, "Setting") self.tree.headerItem().setText(1, "Value") self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject)
def _setupUI(self): self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) self.setMinimumHeight(180) self.main_horizontal_layout = QHBoxLayout(self) italic_font = QFont() italic_font.setItalic(True) # unselected widget self.unselected_widget = QListWidget(self) self._set_list_widget_defaults(self.unselected_widget) unselected_label = QLabel() unselected_label.setText("Unselected") unselected_label.setAlignment(Qt.AlignCenter) unselected_label.setFont(italic_font) unselected_v_layout = QVBoxLayout() unselected_v_layout.addWidget(unselected_label) unselected_v_layout.addWidget(self.unselected_widget) # selected widget self.selected_widget = QListWidget(self) self._set_list_widget_defaults(self.selected_widget) selected_label = QLabel() selected_label.setText("Selected") selected_label.setAlignment(Qt.AlignCenter) selected_label.setFont(italic_font) selected_v_layout = QVBoxLayout() selected_v_layout.addWidget(selected_label) selected_v_layout.addWidget(self.selected_widget) # buttons self.buttons_vertical_layout = QVBoxLayout() self.buttons_vertical_layout.setContentsMargins(0, -1, 0, -1) self.select_all_btn = SmallQPushButton(">>") self.deselect_all_btn = SmallQPushButton("<<") self.select_btn = SmallQPushButton(">") self.deselect_btn = SmallQPushButton("<") self.select_btn.setToolTip("Add the selected items") self.deselect_btn.setToolTip("Remove the selected items") self.select_all_btn.setToolTip("Add all") self.deselect_all_btn.setToolTip("Remove all") # add buttons spacer_label = QLabel() # pragmatic way to create a spacer with # the same height of the labels on top # of the lists, in order to align the # buttons with the lists. self.buttons_vertical_layout.addWidget(spacer_label) self.buttons_vertical_layout.addWidget(self.select_btn) self.buttons_vertical_layout.addWidget(self.deselect_btn) self.buttons_vertical_layout.addWidget(self.select_all_btn) self.buttons_vertical_layout.addWidget(self.deselect_all_btn) # add sub widgets self.main_horizontal_layout.addLayout(unselected_v_layout) self.main_horizontal_layout.addLayout(self.buttons_vertical_layout) self.main_horizontal_layout.addLayout(selected_v_layout)
def setupUi(self): self.resize(500, 350) self.setWindowTitle("Remote connections manager") self.horizontalLayout = QHBoxLayout() self.horizontalLayout.setSpacing(2) self.horizontalLayout.setMargin(0) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Vertical) self.buttonBox.setStandardButtons(QDialogButtonBox.Close) self.table = QTableWidget() self.table.verticalHeader().setVisible(False) self.table.setSelectionMode(QAbstractItemView.SingleSelection) self.table.setSelectionBehavior(QAbstractItemView.SelectRows) self.addRowButton = QPushButton() self.addRowButton.setText("Add connection") self.editRowButton = QPushButton() self.editRowButton.setText("Edit connection") self.removeRowButton = QPushButton() self.removeRowButton.setText("Remove connection") self.buttonBox.addButton(self.addRowButton, QDialogButtonBox.ActionRole) self.buttonBox.addButton(self.editRowButton, QDialogButtonBox.ActionRole) self.buttonBox.addButton(self.removeRowButton, QDialogButtonBox.ActionRole) self.setTableContent() self.horizontalLayout.addWidget(self.table) self.horizontalLayout.addWidget(self.buttonBox) self.setLayout(self.horizontalLayout) self.buttonBox.rejected.connect(self.close) self.editRowButton.clicked.connect(self.editRow) self.addRowButton.clicked.connect(self.addRow) self.removeRowButton.clicked.connect(self.removeRow) QMetaObject.connectSlotsByName(self) self.editRowButton.setEnabled(False) self.removeRowButton.setEnabled(False)
def __init__(self, repo, path): super(VersionViewerDialog, self).__init__(config.iface.mainWindow(), Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.repo = repo self.path = path self.setupUi(self) self.listWidget.itemClicked.connect(self.commitClicked) settings = QSettings() horizontalLayout = QHBoxLayout() horizontalLayout.setSpacing(0) horizontalLayout.setMargin(0) self.mapCanvas = QgsMapCanvas() self.mapCanvas.setCanvasColor(Qt.white) self.mapCanvas.enableAntiAliasing(settings.value("/qgis/enable_anti_aliasing", False, type = bool)) self.mapCanvas.useImageToRender(settings.value("/qgis/use_qimage_to_render", False, type = bool)) action = settings.value("/qgis/wheel_action", 0, type = float) zoomFactor = settings.value("/qgis/zoom_factor", 2, type = float) self.mapCanvas.setWheelAction(QgsMapCanvas.WheelAction(action), zoomFactor) horizontalLayout.addWidget(self.mapCanvas) self.mapWidget.setLayout(horizontalLayout) self.panTool = QgsMapToolPan(self.mapCanvas) self.mapCanvas.setMapTool(self.panTool) versions = repo.log(path = path) if versions: for commit in versions: item = CommitListItem(commit, repo, path) self.listWidget.addItem(item) ''''w = CommitListItemWidget(commit) self.ui.listWidget.setItemWidget(item, w)''' else: raise GeoGigException("The selected feature is not versioned yet")
def __init__(self, parent, tree, providerName, param): QTreeWidgetItem.__init__(self, parent) self.providereName = providerName self.param = param self.tree = tree self.setText(0, param.description) self.paramName = settingName(providerName, param.name) if isinstance(param.defaultValue, bool): self.value = QSettings().value(self.paramName, defaultValue=param.defaultValue, type=bool) if self.value: self.setCheckState(1, Qt.Checked) else: self.setCheckState(1, Qt.Unchecked) elif isinstance(param.defaultValue, list): self.combo = QComboBox() for element in param.defaultValue: self.combo.addItem(element) self.tree.setItemWidget(self, 1, self.combo) self.value = QSettings().value(self.paramName, defaultValue=param.defaultValue[0]) idx = self.combo.findText(self.value) self.combo.setCurrentIndex(idx) elif param.description == "Password": self.passwordField = QLineEdit() self.passwordField.setEchoMode(QLineEdit.Password); #self.passwordField.setStyleSheet("QLineEdit { border: none }"); self.value = QSettings().value(self.paramName, defaultValue=param.defaultValue) self.passwordField.setText(str(self.value)) self.tree.setItemWidget(self, 1, self.passwordField) elif param.action is not None: layout = QHBoxLayout() layout.setMargin(0) layout.setSpacing(0) self.textbox = QLineEdit() self.value = QSettings().value(self.paramName, defaultValue=param.defaultValue) self.textbox.setText(str(self.value)) layout.addWidget(self.textbox) self.button = QToolButton() self.button.setText(param.actionText) self.button.clicked.connect(param.action) layout.addWidget(self.button) self.widget = QWidget() self.widget.setLayout(layout) self.tree.setItemWidget(self, 1, self.widget) else: self.textbox = QLineEdit() #self.textbox.setStyleSheet("QLineEdit { border: none }"); self.tree.setItemWidget(self, 1, self.textbox) self.value = QSettings().value(self.paramName, defaultValue=param.defaultValue) self.textbox.setText(str(self.value))
def __init__(self, parent): super(ConfigOptionsPage, self).__init__(parent) self.config_widget = ConfigDialog() layout = QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.setMargin(0) self.setLayout(layout) layout.addWidget(self.config_widget) self.setObjectName('processingOptions')
def treeItemClicked(self, item): if item.childCount(): return color = {"MODIFIED": QColor(255, 170, 0), "ADDED":Qt.green, "REMOVED":Qt.red , "NO_CHANGE":Qt.white} changeTypeName = ["", "ADDED", "MODIFIED", "REMOVED"] path = item.text(0) if path not in self.changes: return oldfeature = self.changes[path].oldfeature newfeature = self.changes[path].newfeature changetype = self.changes[path].changetype self.attributesTable.clear() self.attributesTable.verticalHeader().show() self.attributesTable.horizontalHeader().show() self.attributesTable.setRowCount(len(newfeature)) self.attributesTable.setVerticalHeaderLabels([a for a in newfeature]) self.attributesTable.setHorizontalHeaderLabels(["Old value", "New value", "Change type"]) for i, attrib in enumerate(newfeature): self.attributesTable.setItem(i, 0, DiffItem(oldfeature.get(attrib, None))) self.attributesTable.setItem(i, 1, DiffItem(newfeature.get(attrib, None))) attribChangeType = changeTypeName[changetype] isChangedGeom = False if changetype == LOCAL_FEATURE_MODIFIED: oldvalue = oldfeature.get(attrib, None) newvalue = newfeature.get(attrib, None) try:# to avoid false change detection due to different precisions oldvalue = QgsGeometry.fromWkt(oldvalue).exportToWkt(7) newvalue = QgsGeometry.fromWkt(newvalue).exportToWkt(7) if oldvalue != newvalue and None not in [oldvalue, newvalue]: widget = QWidget() btn = QPushButton() btn.setText("View detail") g1 = QgsGeometry.fromWkt(oldvalue) g2 = QgsGeometry.fromWkt(newvalue) btn.clicked.connect(lambda: self.viewGeometryChanges(g1, g2)) label = QLabel() label.setText(attribChangeType) layout = QHBoxLayout(widget) layout.addWidget(label); layout.addWidget(btn); layout.setContentsMargins(0, 0, 0, 0) widget.setLayout(layout) self.attributesTable.setItem(i, 2, QTableWidgetItem("")) self.attributesTable.setCellWidget(i, 2, widget) isChangedGeom = True except: pass if oldvalue == newvalue: attribChangeType = "NO_CHANGE" if not isChangedGeom: self.attributesTable.setItem(i, 2, QTableWidgetItem(attribChangeType)) for col in range(3): self.attributesTable.item(i, col).setBackgroundColor(color[attribChangeType]); self.attributesTable.resizeColumnsToContents() self.attributesTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
def initGui(self): self.combo = ExtendedComboBox() self.fillCombo() self.combo.setEditable(True) self.label = QLabel("Enter command:") self.errorLabel = QLabel("Enter command:") self.vlayout = QVBoxLayout() self.vlayout.setSpacing(2) self.vlayout.setMargin(0) self.vlayout.addSpacerItem(QSpacerItem(0, OFFSET, QSizePolicy.Maximum, QSizePolicy.Expanding)) self.hlayout = QHBoxLayout() self.hlayout.addWidget(self.label) self.vlayout.addLayout(self.hlayout) self.hlayout2 = QHBoxLayout() self.hlayout2.addWidget(self.combo) self.vlayout.addLayout(self.hlayout2) self.vlayout.addSpacerItem(QSpacerItem(0, OFFSET, QSizePolicy.Maximum, QSizePolicy.Expanding)) self.setLayout(self.vlayout) self.combo.lineEdit().returnPressed.connect(self.run) self.prepareGui()
def __init__(self, conflicts): super(ConflictDialog, self).__init__(None, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.solved = False self.resolvedConflicts = {} self.conflicts = conflicts self.setupUi(self) self.setWindowFlags(self.windowFlags() | Qt.WindowSystemMenuHint | Qt.WindowMinMaxButtonsHint) self.zoomButton.clicked.connect(self.zoomToFullExtent) self.solveButton.clicked.connect(self.solve) self.conflictsTree.itemClicked.connect(self.treeItemClicked) self.attributesTable.cellClicked.connect(self.cellClicked) self.solveAllLocalButton.clicked.connect(self.solveAllLocal) self.solveAllRemoteButton.clicked.connect(self.solveAllRemote) self.solveLocalButton.clicked.connect(self.solveLocal) self.solveRemoteButton.clicked.connect(self.solveRemote) self.showRemoteCheck.stateChanged.connect(self.showGeoms) self.showLocalCheck.stateChanged.connect(self.showGeoms) self.lastSelectedItem = None self.currentPath = None self.currentConflict = None self.theirsLayer = None self.oursLayer = None settings = QSettings() horizontalLayout = QHBoxLayout() horizontalLayout.setSpacing(0) horizontalLayout.setMargin(0) self.mapCanvas = QgsMapCanvas() self.mapCanvas.setCanvasColor(Qt.white) self.mapCanvas.enableAntiAliasing(settings.value("/qgis/enable_anti_aliasing", False, type = bool)) self.mapCanvas.useImageToRender(settings.value("/qgis/use_qimage_to_render", False, type = bool)) self.mapCanvas.mapRenderer().setProjectionsEnabled(True) action = settings.value("/qgis/wheel_action", 0, type = float) zoomFactor = settings.value("/qgis/zoom_factor", 2, type = float) self.mapCanvas.setWheelAction(QgsMapCanvas.WheelAction(action), zoomFactor) horizontalLayout.addWidget(self.mapCanvas) self.canvasWidget.setLayout(horizontalLayout) self.panTool = QgsMapToolPan(self.mapCanvas) self.mapCanvas.setMapTool(self.panTool) self.solveButton.setEnabled(False) self.solveLocalButton.setEnabled(False) self.solveRemoteButton.setEnabled(False) self.fillConflictsTree()
class RefPanel(QWidget): refChanged = pyqtSignal() def __init__(self, repo, ref = None): super(RefPanel, self).__init__(None) self.repo = repo self.ref = ref self.horizontalLayout = QHBoxLayout(self) self.horizontalLayout.setSpacing(2) self.horizontalLayout.setMargin(0) self.text = QLineEdit() self.text.setEnabled(False) if ref is not None: self.text.setText(ref.humantext()) self.text.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.horizontalLayout.addWidget(self.text) self.pushButton = QToolButton() self.pushButton.setText("...") self.pushButton.clicked.connect(self.showSelectionDialog) self.pushButton.setEnabled(self.repo is not None) self.horizontalLayout.addWidget(self.pushButton) self.setLayout(self.horizontalLayout) def showSelectionDialog(self): from geogig.gui.dialogs.historyviewer import HistoryViewerDialog dialog = HistoryViewerDialog(self.repo) dialog.exec_() ref = dialog.ref if ref: commit = Commit.fromref(self.repo, ref) self.setRef(commit) def setRepo(self, repo): self.repo = repo self.pushButton.setEnabled(True) self.setRef(Commitish(repo, repo.HEAD)) def setRef(self, ref): self.ref = ref self.text.setText(ref.humantext()) self.refChanged.emit() def getRef(self): return self.ref
class FileDirectorySelector(QWidget): def __init__(self, parent=None, selectFile=False): QWidget.__init__(self, parent) # create gui self.btnSelect = QToolButton() self.btnSelect.setText('…') 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, selected_filter = 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, iface): QDialog.__init__(self, iface.mainWindow()) self.workerThread = None self.state = False self.outputLoc = None self.resultStatus = None self.reRun = False self.savedProj = None # Build GUI Elements self.setWindowTitle("SEILAPLAN wird ausgeführt") self.resize(500, 100) self.container = QVBoxLayout() self.progressBar = QProgressBar(self) self.progressBar.setMinimumWidth(500) self.statusLabel = QLabel(self) self.hbox = QHBoxLayout() self.cancelButton = QDialogButtonBox() self.closeButton = QDialogButtonBox() self.resultLabel = ClickLabel(self) self.resultLabel.setMaximumWidth(500) self.resultLabel.setSizePolicy( QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)) self.resultLabel.setWordWrap(True) self.rerunButton = QPushButton("Berechnungen wiederholen") self.rerunButton.setVisible(False) spacer = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum) self.cancelButton.setStandardButtons(QDialogButtonBox.Cancel) self.cancelButton.clicked.connect(self.onAbort) self.closeButton.setStandardButtons(QDialogButtonBox.Close) self.closeButton.clicked.connect(self.onClose) self.hbox.addWidget(self.rerunButton) self.hbox.addItem(spacer) self.hbox.addWidget(self.cancelButton) self.hbox.setAlignment(self.cancelButton, Qt.AlignHCenter) self.hbox.addWidget(self.closeButton) self.hbox.setAlignment(self.closeButton, Qt.AlignHCenter) self.closeButton.hide() self.container.addWidget(self.progressBar) self.container.addWidget(self.statusLabel) self.container.addWidget(self.resultLabel) self.container.addLayout(self.hbox) self.container.setSizeConstraint(QLayout.SetFixedSize) self.setLayout(self.container)
def __init__(self, parameter, parent=None): """Constructor. :param parameter: A DefaultValueParameter object. :type parameter: DefaultValueParameter """ super(DefaultValueParameterWidget, self).__init__(parameter, parent) self.radio_button_layout = QHBoxLayout() # Create radio button group self.input_button_group = QButtonGroup() for i in range(len(self._parameter.labels)): if '%s' in self._parameter.labels[i]: label = ( self._parameter.labels[i] % self._parameter.options[i]) else: label = self._parameter.labels[i] radio_button = QRadioButton(label) self.radio_button_layout.addWidget(radio_button) self.input_button_group.addButton(radio_button, i) if self._parameter.value == \ self._parameter.options[i]: radio_button.setChecked(True) # Create double spin box for custom value self.custom_value = QDoubleSpinBox() self.custom_value.setSingleStep(0.1) if self._parameter.options[-1]: self.custom_value.setValue(self._parameter.options[-1]) self.radio_button_layout.addWidget(self.custom_value) self.toggle_custom_value() self.inner_input_layout.addLayout(self.radio_button_layout) # Connect # noinspection PyUnresolvedReferences self.input_button_group.buttonClicked.connect( self.toggle_custom_value)
class MultipleDirectorySelector(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) # create gui self.btnSelect = QToolButton() self.btnSelect.setText('…') 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.setFocusPolicy(Qt.StrongFocus) self.btnSelect.clicked.connect(self.select) def select(self): text = self.lineEdit.text() if text != '': items = text.split(';') else: items = [] dlg = DirectorySelectorDialog(None, items) if dlg.exec_(): text = dlg.value() self.lineEdit.setText(text) self.canFocusOut = True def text(self): return self.lineEdit.text() def setText(self, value): self.lineEdit.setText(value)
def __init__(self, repo, ref = None): super(RefPanel, self).__init__(None) self.repo = repo self.ref = ref self.horizontalLayout = QHBoxLayout(self) self.horizontalLayout.setSpacing(2) self.horizontalLayout.setMargin(0) self.text = QLineEdit() self.text.setEnabled(False) if ref is not None: self.text.setText(ref.humantext()) self.text.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.horizontalLayout.addWidget(self.text) self.pushButton = QToolButton() self.pushButton.setText("...") self.pushButton.clicked.connect(self.showSelectionDialog) self.pushButton.setEnabled(self.repo is not None) self.horizontalLayout.addWidget(self.pushButton) self.setLayout(self.horizontalLayout)
def __init__(self, parent=None): QWidget.__init__(self, parent) # create gui self.btnSelect = QToolButton() self.btnSelect.setText('…') 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.setFocusPolicy(Qt.StrongFocus) self.btnSelect.clicked.connect(self.select)
def __init__(self, param, row, col, dialog): super(BatchInputSelectionPanel, self).__init__(None) self.param = param self.dialog = dialog self.row = row self.col = col self.horizontalLayout = QHBoxLayout(self) self.horizontalLayout.setSpacing(0) self.horizontalLayout.setMargin(0) self.text = QLineEdit() self.text.setObjectName("text") self.text.setMinimumWidth(300) self.setValue("") self.text.editingFinished.connect(self.textEditingFinished) 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, 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, 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)
class BatchInputSelectionPanel(QWidget): valueChanged = pyqtSignal() def __init__(self, param, row, col, dialog): super(BatchInputSelectionPanel, self).__init__(None) self.param = param self.dialog = dialog self.row = row self.col = col self.horizontalLayout = QHBoxLayout(self) self.horizontalLayout.setSpacing(0) self.horizontalLayout.setMargin(0) self.text = QLineEdit() self.text.setObjectName('text') self.text.setMinimumWidth(300) self.setValue('') self.text.editingFinished.connect(self.textEditingFinished) 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 _panel(self): return self.dialog.mainWidget() def _table(self): return self._panel().tblParameters def showPopupMenu(self): popupmenu = QMenu() if not (isinstance(self.param, QgsProcessingParameterMultipleLayers) and self.param.layerType == dataobjects.TYPE_FILE): selectLayerAction = QAction(self.tr('Select from open layers'), self.pushButton) selectLayerAction.triggered.connect(self.showLayerSelectionDialog) popupmenu.addAction(selectLayerAction) selectFileAction = QAction(self.tr('Select from file system'), self.pushButton) selectFileAction.triggered.connect(self.showFileSelectionDialog) popupmenu.addAction(selectFileAction) popupmenu.exec_(QCursor.pos()) def showLayerSelectionDialog(self): layers = [] if (isinstance(self.param, QgsProcessingParameterRasterLayer) or (isinstance(self.param, QgsProcessingParameterMultipleLayers) and self.param.layerType() == QgsProcessing.TypeRaster)): layers = QgsProcessingUtils.compatibleRasterLayers( QgsProject.instance()) elif isinstance(self.param, QgsProcessingParameterVectorLayer): layers = QgsProcessingUtils.compatibleVectorLayers( QgsProject.instance()) else: datatypes = [QgsProcessing.TypeVectorAnyGeometry] if isinstance(self.param, QgsProcessingParameterFeatureSource): datatypes = self.param.dataTypes() elif isinstance(self.param, QgsProcessingParameterMultipleLayers): datatypes = [self.param.layerType()] if QgsProcessing.TypeVectorAnyGeometry not in datatypes: layers = QgsProcessingUtils.compatibleVectorLayers( QgsProject.instance(), datatypes) else: layers = QgsProcessingUtils.compatibleVectorLayers( QgsProject.instance()) dlg = MultipleInputDialog([layer.name() for layer in layers]) dlg.exec_() def generate_layer_id(layer): # prefer layer name if unique if len([ l for l in layers if l.name().lower() == layer.name().lower() ]) == 1: return layer.name() else: # otherwise fall back to layer id return layer.id() if dlg.selectedoptions is not None: selected = dlg.selectedoptions if len(selected) == 1: self.setValue(generate_layer_id(layers[selected[0]])) else: if isinstance(self.param, QgsProcessingParameterMultipleLayers): self.text.setText(';'.join(layers[idx].id() for idx in selected)) else: rowdif = len(selected) - (self._table().rowCount() - self.row) for i in range(rowdif): self._panel().addRow() for i, layeridx in enumerate(selected): self._table().cellWidget( i + self.row, self.col).setValue( generate_layer_id(layers[layeridx])) def showFileSelectionDialog(self): settings = QgsSettings() text = str(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 = str(settings.value('/Processing/LastInputPath')) else: path = '' ret, selected_filter = QFileDialog.getOpenFileNames( self, self.tr('Open file'), path, getFileFilter(self.param)) if ret: files = list(ret) settings.setValue('/Processing/LastInputPath', os.path.dirname(str(files[0]))) for i, filename in enumerate(files): files[i] = dataobjects.getRasterSublayer(filename, self.param) if len(files) == 1: self.text.setText(files[0]) self.textEditingFinished() else: if isinstance(self.param, QgsProcessingParameterMultipleLayers): self.text.setText(';'.join(str(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).setValue(f) def textEditingFinished(self): self._value = self.text.text() self.valueChanged.emit() def value(self): return self._value def setValue(self, value): self._value = value if isinstance(value, QgsMapLayer): self.text.setText(value.name()) else: # should be basestring self.text.setText(value) self.valueChanged.emit()
class ExpressionLineEdit(QLineEdit): def __init__(self, column, host=None, parent=None): # Use a different pixmap self._current_profile = current_profile() QLineEdit.__init__(self, parent) self.column = column self._entity = self.column.entity self.layer = self.create_layer() self.host = host # Configure load button self.btn_load = QToolButton(parent) self.btn_load.setCursor(Qt.PointingHandCursor) self.btn_load.setFocusPolicy(Qt.NoFocus) px = GuiUtils.get_icon_pixmap('expression.png') self.btn_load.setIcon(QIcon(px)) self.btn_load.setIconSize(px.size()) self.btn_load.setStyleSheet('background: transparent; padding: 0px; ' 'border: none;') frame_width = self.set_button_minimum_size(self.btn_load) # Ensure that text does not overlay button padding = self.btn_load.sizeHint().width() + frame_width + 1 self.setStyleSheet('padding-right: ' + str(padding * 2) + 'px;') # Set layout self.button_layout = QHBoxLayout(self) self.button_layout.addWidget(self.btn_load, 0, Qt.AlignRight) self.button_layout.setSpacing(0) self.button_layout.setMargin(5) # Readonly as text generated automatically self.setReadOnly(True) # Current model object self._current_item = None def create_layer(self): srid = None column = '' if self.entity.has_geometry_column(): geom_cols = [col.name for col in self.entity.columns.values() if col.TYPE_INFO == 'GEOMETRY'] column = geom_cols[0] geom_col_obj = self.entity.columns[column] if geom_col_obj.srid >= 100000: srid = geom_col_obj.srid layer = vector_layer(self.entity.name, geom_column=column, proj_wkt=srid) return layer def get_feature_value(self, model=None): self.layer.startEditing() feature = None request = QgsFeatureRequest() if model is None: model = self.host.model() request.setFilterFid(model.id) feature_itr = self.layer.getFeatures(request) for feat in feature_itr: feature = feat break exp = QgsExpression(self.column.expression) if exp.hasParserError(): raise Exception(exp.parserErrorString()) exp.prepare(self.layer.fields()) if feature is not None: value = exp.evaluate(feature) return value else: return None def set_button_minimum_size(self, button): """ Sets the minimum button size. :param button: The button to be set. :type button: QToolButton :return: Returns the frame width of the button :rtype: Integer """ frame_width = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth) msz = self.minimumSizeHint() self.setMinimumSize( max( msz.width(), button.sizeHint().height() + frame_width * 2 + 2 ), max( msz.height(), button.sizeHint().height() + frame_width * 2 + 2 ) ) return frame_width @property def entity(self): """ :return: Returns the entity object corresponding to this widget. :rtype: Entity """ return self._entity def clear_line_edit(self): """ Clears the text in the line edit. """ self.clear() def on_expression_triggered(self, model=None): """ Slot raised to load browser for selecting foreign key entities. To be implemented by subclasses. """ self.format_display(self.get_feature_value(model)) return self.get_feature_value() def format_display(self, value): """ Extract object values to show in the line edit based on the specified display columns. """ if value is not None: self.setText(str(value))
def fillTreeUsingProviders(self): self.items = {} self.model.clear() self.model.setHorizontalHeaderLabels([self.tr('Setting'), self.tr('Value')]) settings = ProcessingConfig.getSettings() rootItem = self.model.invisibleRootItem() """ Filter 'General', 'Models' and 'Scripts' items """ priorityKeys = [self.tr('General'), self.tr('Models'), self.tr('Scripts')] for group in priorityKeys: groupItem = QStandardItem(group) icon = ProcessingConfig.getGroupIcon(group) groupItem.setIcon(icon) groupItem.setEditable(False) emptyItem = QStandardItem() emptyItem.setEditable(False) rootItem.insertRow(0, [groupItem, emptyItem]) if not group in settings: continue # add menu item only if it has any search matches for setting in settings[group]: if setting.hidden or setting.name.startswith("MENU_"): continue labelItem = QStandardItem(setting.description) labelItem.setIcon(icon) labelItem.setEditable(False) self.items[setting] = SettingItem(setting) groupItem.insertRow(0, [labelItem, self.items[setting]]) """ Filter 'Providers' items """ providersItem = QStandardItem(self.tr('Providers')) icon = QgsApplication.getThemeIcon("/processingAlgorithm.svg") providersItem.setIcon(icon) providersItem.setEditable(False) emptyItem = QStandardItem() emptyItem.setEditable(False) rootItem.insertRow(0, [providersItem, emptyItem]) for group in list(settings.keys()): if group in priorityKeys or group == menusSettingsGroup: continue groupItem = QStandardItem(group) icon = ProcessingConfig.getGroupIcon(group) groupItem.setIcon(icon) groupItem.setEditable(False) for setting in settings[group]: if setting.hidden: continue labelItem = QStandardItem(setting.description) labelItem.setIcon(icon) labelItem.setEditable(False) self.items[setting] = SettingItem(setting) groupItem.insertRow(0, [labelItem, self.items[setting]]) emptyItem = QStandardItem() emptyItem.setEditable(False) providersItem.appendRow([groupItem, emptyItem]) """ Filter 'Menus' items """ self.menusItem = QStandardItem(self.tr('Menus')) icon = QIcon(os.path.join(pluginPath, 'images', 'menu.png')) self.menusItem.setIcon(icon) self.menusItem.setEditable(False) emptyItem = QStandardItem() emptyItem.setEditable(False) rootItem.insertRow(0, [self.menusItem, emptyItem]) button = QPushButton(self.tr('Reset to defaults')) button.clicked.connect(self.resetMenusToDefaults) layout = QHBoxLayout() layout.setContentsMargins(0, 0, 0, 0) layout.addWidget(button) layout.addStretch() widget = QWidget() widget.setLayout(layout) self.tree.setIndexWidget(emptyItem.index(), widget) for provider in QgsApplication.processingRegistry().providers(): providerDescription = provider.name() groupItem = QStandardItem(providerDescription) icon = provider.icon() groupItem.setIcon(icon) groupItem.setEditable(False) for alg in provider.algorithms(): algItem = QStandardItem(alg.displayName()) algItem.setIcon(icon) algItem.setEditable(False) try: settingMenu = ProcessingConfig.settings["MENU_" + alg.id()] settingButton = ProcessingConfig.settings["BUTTON_" + alg.id()] settingIcon = ProcessingConfig.settings["ICON_" + alg.id()] except: continue self.items[settingMenu] = SettingItem(settingMenu) self.items[settingButton] = SettingItem(settingButton) self.items[settingIcon] = SettingItem(settingIcon) menuLabelItem = QStandardItem("Menu path") menuLabelItem.setEditable(False) buttonLabelItem = QStandardItem("Add button in toolbar") buttonLabelItem.setEditable(False) iconLabelItem = QStandardItem("Icon") iconLabelItem.setEditable(False) emptyItem = QStandardItem() emptyItem.setEditable(False) algItem.insertRow(0, [menuLabelItem, self.items[settingMenu]]) algItem.insertRow(0, [buttonLabelItem, self.items[settingButton]]) algItem.insertRow(0, [iconLabelItem, self.items[settingIcon]]) groupItem.insertRow(0, [algItem, emptyItem]) emptyItem = QStandardItem() emptyItem.setEditable(False) self.menusItem.appendRow([groupItem, emptyItem]) self.tree.sortByColumn(0, Qt.AscendingOrder) self.adjustColumns()
def setupUi(self): self.setWindowTitle(self.tr('Parameter definition')) self.verticalLayout = QVBoxLayout(self) self.verticalLayout.setSpacing(40) self.verticalLayout.setMargin(20) self.horizontalLayoutName = QHBoxLayout(self) self.horizontalLayoutName.setSpacing(2) self.horizontalLayoutName.setMargin(0) self.label = QLabel(self.tr('Parameter name')) self.horizontalLayoutName.addWidget(self.label) self.nameTextBox = QLineEdit() self.horizontalLayoutName.addWidget(self.nameTextBox) self.verticalLayout.addLayout(self.horizontalLayoutName) self.horizontalLayoutRequired = QHBoxLayout(self) self.horizontalLayoutRequired.setSpacing(2) self.horizontalLayoutRequired.setMargin(0) self.horizontalLayoutParent = QHBoxLayout(self) self.horizontalLayoutParent.setSpacing(2) self.horizontalLayoutParent.setMargin(0) self.horizontalLayoutDefault = QHBoxLayout(self) self.horizontalLayoutDefault.setSpacing(2) self.horizontalLayoutDefault.setMargin(0) self.horizontalLayoutDatatype = QHBoxLayout(self) self.horizontalLayoutDatatype.setSpacing(2) self.horizontalLayoutDatatype.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.horizontalLayoutParent.addWidget(self.state) self.verticalLayout.addLayout(self.horizontalLayoutParent) elif self.paramType in ( ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD, ModelerParameterDefinitionDialog.PARAMETER_TABLE_MULTIPLE_FIELD)\ or isinstance(self.param, (ParameterTableField, ParameterTableMultipleField)): self.horizontalLayoutParent.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.horizontalLayoutParent.addWidget(self.parentCombo) self.verticalLayout.addLayout(self.horizontalLayoutParent) # add the datatype selector self.horizontalLayoutDatatype.addWidget(QLabel(self.tr('Allowed ' 'data type'))) self.datatypeCombo = QComboBox() self.datatypeCombo.addItem(self.tr('Any'), -1) self.datatypeCombo.addItem(self.tr('Number'), 0) self.datatypeCombo.addItem(self.tr('String'), 1) self.horizontalLayoutDatatype.addWidget(self.datatypeCombo) if self.param is not None and self.param.datatype is not None: # QComboBoxes indexes start at 0, # self.param.datatype start with -1 that is why I need to do +1 datatype_index = self.param.datatype + 1 self.datatypeCombo.setCurrentIndex(datatype_index) self.verticalLayout.addLayout(self.horizontalLayoutDatatype) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or \ isinstance(self.param, ParameterVector): self.horizontalLayoutParent.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.horizontalLayoutParent.addWidget(self.shapetypeCombo) self.verticalLayout.addLayout(self.horizontalLayoutParent) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or \ isinstance(self.param, ParameterMultipleInput): self.horizontalLayoutParent.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.horizontalLayoutParent.addWidget(self.datatypeCombo) self.verticalLayout.addLayout(self.horizontalLayoutParent) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or \ isinstance(self.param, ParameterNumber): self.horizontalLayoutParent.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.horizontalLayoutParent.addWidget(self.minTextBox) self.horizontalLayoutParent.addWidget(self.maxTextBox) self.verticalLayout.addLayout(self.horizontalLayoutParent) self.horizontalLayoutDefault.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.horizontalLayoutDefault.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayoutDefault) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or \ isinstance(self.param, ParameterString): self.horizontalLayoutParent.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() if self.param is not None: self.defaultTextBox.setText(self.param.default) self.horizontalLayoutParent.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayoutParent) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or \ isinstance(self.param, ParameterFile): self.horizontalLayoutParent.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.horizontalLayoutParent.addWidget(self.fileFolderCombo) self.verticalLayout.addLayout(self.horizontalLayoutParent) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_POINT or \ isinstance(self.param, ParameterPoint): self.horizontalLayoutParent.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() if self.param is not None: self.defaultTextBox.setText(self.param.default) self.horizontalLayoutParent.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayoutParent) self.horizontalLayoutRequired.addWidget(QLabel(self.tr('Required'))) self.yesNoCombo = QComboBox() self.yesNoCombo.addItem(self.tr('Yes')) self.yesNoCombo.addItem(self.tr('No')) self.horizontalLayoutRequired.addWidget(self.yesNoCombo) if self.param is not None: self.yesNoCombo.setCurrentIndex( 1 if self.param.optional else 0) self.verticalLayout.addLayout(self.horizontalLayoutRequired) 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 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, QgsProcessingParameterFolderDestination): self.selectDirectory() return filefilter = self.output.createFileFilter() settings = QgsSettings() if settings.contains('/Processing/LastBatchOutputPath'): path = str(settings.value('/Processing/LastBatchOutputPath')) else: path = '' filename, selectedFileFilter = QFileDialog.getSaveFileName( self, self.tr('Save File'), path, filefilter) 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: 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('.')] \ + str(i + 1) + filename[filename.rfind('.'):] self.table.cellWidget(i + self.row, self.col).setValue(name) elif dlg.mode == AutofillDialog.FILL_WITH_PARAMETER: for row in range(self.row, self.table.rowCount()): v = self.panel.valueForParameter( row - 1, dlg.param_name) param = self.alg.parameterDefinition(dlg.param_name) if isinstance(param, (QgsProcessingParameterRasterLayer, QgsProcessingParameterFeatureSource, QgsProcessingParameterVectorLayer, QgsProcessingParameterMultipleLayers)): if isinstance(v, QgsMapLayer): s = v.name() else: if v in QgsProject.instance().mapLayers(): layer = QgsProject.instance().mapLayer(v) # value is a layer ID, but we'd prefer to show a layer name if it's unique in the project if len([ l for _, l in QgsProject.instance( ).mapLayers().items() if l.name().lower() == layer.name().lower() ]) == 1: s = layer.name() else: # otherwise fall back to layer id s = v else: # else try to use file base name # TODO: this is bad for database sources!! s = os.path.basename(v) s = os.path.splitext(s)[0] elif isinstance(param, QgsProcessingParameterBoolean): s = 'true' if v else 'false' elif isinstance(param, QgsProcessingParameterEnum): s = param.options()[v] else: s = str(v) name = filename[:filename.rfind('.')] + s \ + filename[filename.rfind('.'):] self.table.cellWidget(row, self.col).setValue(name) def selectDirectory(self): settings = QgsSettings() if settings.contains('/Processing/LastBatchOutputPath'): lastDir = str(settings.value('/Processing/LastBatchOutputPath')) else: lastDir = '' dirName = QFileDialog.getExistingDirectory(self, self.tr('Output 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 str(self.text.text())
class ListMultiSelectWidget(QGroupBox): """Widget to show two parallel lists and move elements between the two usage from code: self.myWidget = ListMultiSelectWidget(title='myTitle') self.myLayout.insertWidget(1, self.myWidget) usage from designer: insert a QGroupBox in your UI file optionally give a title to the QGroupBox promote it to ListMultiSelectWidget """ selection_changed = pyqtSignal() def __init__(self, parent=None, title=None): QGroupBox.__init__(self) self.setTitle(title) self.selected_widget = None self.deselected_widget = None self._setupUI() # connect actions self.select_all_btn.clicked.connect(self._select_all) self.deselect_all_btn.clicked.connect(self._deselect_all) self.select_btn.clicked.connect(self._select) self.deselect_btn.clicked.connect(self._deselect) self.deselected_widget.itemDoubleClicked.connect(self._select) self.selected_widget.itemDoubleClicked.connect(self._deselect) def get_selected_items(self): """ :return list with all the selected items text """ return self._get_items(self.selected_widget) def get_deselected_items(self): """ :return list with all the deselected items text """ return self._get_items(self.deselected_widget) def add_selected_items(self, items): """ :param items list of strings to be added in the selected list """ self._add_items(self.selected_widget, items) def add_deselected_items(self, items): """ :param items list of strings to be added in the deselected list """ self._add_items(self.deselected_widget, items) def set_selected_items(self, items): """ :param items list of strings to be set as the selected list """ self._set_items(self.selected_widget, items) def set_deselected_items(self, items): """ :param items list of strings to be set as the deselected list """ self._set_items(self.deselected_widget, items) def clear(self): """ removes all items from selected and deselected """ self.set_selected_items([]) self.set_deselected_items([]) def addItem(self, item): """ This is for Processing :param item: string to be added in the deselected list """ self.add_deselected_items([item]) def addItems(self, items): """ This is for Processing :param items: list of strings to be added in the deselected list """ self.add_deselected_items(items) def _get_items(self, widget): for i in range(widget.count()): yield widget.item(i).text() def _set_items(self, widget, items): widget.clear() self._add_items(widget, items) def _add_items(self, widget, items): widget.addItems(items) def _select_all(self): self.deselected_widget.selectAll() self._do_move(self.deselected_widget, self.selected_widget) def _deselect_all(self): self.selected_widget.selectAll() self._do_move(self.selected_widget, self.deselected_widget) def _select(self): self._do_move(self.deselected_widget, self.selected_widget) def _deselect(self): self._do_move(self.selected_widget, self.deselected_widget) def _do_move(self, fromList, toList): for item in fromList.selectedItems(): prev_from_item = fromList.item(fromList.row(item) - 1) toList.addItem(fromList.takeItem(fromList.row(item))) fromList.scrollToItem(prev_from_item) self.selection_changed.emit() def _setupUI(self): self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) self.setMinimumHeight(180) self.main_horizontal_layout = QHBoxLayout(self) italic_font = QFont() italic_font.setItalic(True) # deselected widget self.deselected_widget = QListWidget(self) self._set_list_widget_defaults(self.deselected_widget) deselected_label = QLabel() deselected_label.setText('Deselected') deselected_label.setAlignment(Qt.AlignCenter) deselected_label.setFont(italic_font) deselected_v_layout = QVBoxLayout() deselected_v_layout.addWidget(deselected_label) deselected_v_layout.addWidget(self.deselected_widget) # selected widget self.selected_widget = QListWidget(self) self._set_list_widget_defaults(self.selected_widget) selected_label = QLabel() selected_label.setText('Selected') selected_label.setAlignment(Qt.AlignCenter) selected_label.setFont(italic_font) selected_v_layout = QVBoxLayout() selected_v_layout.addWidget(selected_label) selected_v_layout.addWidget(self.selected_widget) # buttons self.buttons_vertical_layout = QVBoxLayout() self.buttons_vertical_layout.setContentsMargins(0, -1, 0, -1) self.select_all_btn = SmallQPushButton('>>') self.deselect_all_btn = SmallQPushButton('<<') self.select_btn = SmallQPushButton('>') self.deselect_btn = SmallQPushButton('<') self.select_btn.setToolTip('Add the selected items') self.deselect_btn.setToolTip('Remove the selected items') self.select_all_btn.setToolTip('Add all') self.deselect_all_btn.setToolTip('Remove all') # add buttons spacer_label = QLabel() # pragmatic way to create a spacer with # the same height of the labels on top # of the lists, in order to align the # buttons with the lists. self.buttons_vertical_layout.addWidget(spacer_label) self.buttons_vertical_layout.addWidget(self.select_btn) self.buttons_vertical_layout.addWidget(self.deselect_btn) self.buttons_vertical_layout.addWidget(self.select_all_btn) self.buttons_vertical_layout.addWidget(self.deselect_all_btn) # add sub widgets self.main_horizontal_layout.addLayout(deselected_v_layout) self.main_horizontal_layout.addLayout(self.buttons_vertical_layout) self.main_horizontal_layout.addLayout(selected_v_layout) def _set_list_widget_defaults(self, widget): widget.setAlternatingRowColors(True) widget.setSortingEnabled(True) widget.setDragEnabled(True) widget.setDragDropMode(QAbstractItemView.DragDrop) widget.setDragDropOverwriteMode(False) widget.setDefaultDropAction(Qt.MoveAction) widget.setSelectionMode(QAbstractItemView.MultiSelection)
def createWidget(self): if self.dialogType == DIALOG_STANDARD: widget = QWidget() layout = QHBoxLayout() layout.setMargin(0) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(2) self.combo = QgsMapLayerComboBox() layout.addWidget(self.combo) btn = QToolButton() btn.setText('...') btn.setToolTip(self.tr("Select file")) btn.clicked.connect(self.selectFile) layout.addWidget(btn) widget.setLayout(layout) if self.param.optional: self.combo.setAllowEmptyLayer(True) self.combo.setFilters(QgsMapLayerProxyModel.VectorLayer) self.combo.setExcludedProviders(['grass']) try: if iface.activeLayer().type() == QgsMapLayer.VectorLayer: self.combo.setLayer(iface.activeLayer()) except: pass self.combo.currentIndexChanged.connect( lambda: self.widgetValueHasChanged.emit(self)) self.combo.currentTextChanged.connect( lambda: self.widgetValueHasChanged.emit(self)) return widget elif self.dialogType == DIALOG_BATCH: return BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) else: self.combo = QComboBox() layers = self.dialog.getAvailableValuesOfType( ParameterRaster, OutputRaster) self.combo.setEditable(True) tables = self.dialog.getAvailableValuesOfType( ParameterTable, OutputTable) layers = self.dialog.getAvailableValuesOfType( ParameterVector, OutputVector) if self.param.optional: self.combo.addItem(self.NOT_SELECTED, None) for table in tables: self.combo.addItem(self.dialog.resolveValueDescription(table), table) for layer in layers: self.combo.addItem(self.dialog.resolveValueDescription(layer), layer) widget = QWidget() layout = QHBoxLayout() layout.setMargin(0) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(2) layout.addWidget(self.combo) btn = QToolButton() btn.setText('...') btn.setToolTip(self.tr("Select file")) btn.clicked.connect(self.selectFile) layout.addWidget(btn) widget.setLayout(layout) return widget
def loadLayerForEnrichment(self): layers = QgsProject.instance().layerTreeRoot().children() selectedLayerIndex = self.chooseLayerEnrich.currentIndex() if len(layers) == 0: return layer = layers[selectedLayerIndex].layer() self.enrichTableResult.hide() while self.enrichTableResult.rowCount() > 0: self.enrichTableResult.removeRow(0) self.enrichTable.show() self.addEnrichedLayerRowButton.setEnabled(True) fieldnames = [field.name() for field in layer.fields()] while self.enrichTable.rowCount() > 0: self.enrichTable.removeRow(0) row = 0 self.enrichTable.setColumnCount(9) self.enrichTable.setHorizontalHeaderLabels([ "Column", "EnrichmentConcept", "TripleStore", "Strategy", "content", "ID Column", "ID Property", "ID Domain", "Language" ]) for field in fieldnames: item = QTableWidgetItem(field) item.setFlags(QtCore.Qt.ItemIsEnabled) currentRowCount = self.enrichTable.rowCount() self.enrichTable.insertRow(row) self.enrichTable.setItem(row, 0, item) cbox = QComboBox() cbox.addItem("No Enrichment") cbox.addItem("Keep Local") cbox.addItem("Keep Remote") cbox.addItem("Replace Local") cbox.addItem("Merge") cbox.addItem("Ask User") cbox.addItem("Exclude") self.enrichTable.setCellWidget(row, 3, cbox) cbox = QComboBox() cbox.addItem("Enrich Value") cbox.addItem("Enrich URI") cbox.addItem("Enrich Both") self.enrichTable.setCellWidget(row, 4, cbox) cbox = QComboBox() for fieldd in fieldnames: cbox.addItem(fieldd) self.enrichTable.setCellWidget(row, 5, cbox) itemm = QTableWidgetItem( "http://www.w3.org/2000/01/rdf-schema#label") self.enrichTable.setItem(row, 6, itemm) itemm = QTableWidgetItem("") self.enrichTable.setItem(row, 7, itemm) itemm = QTableWidgetItem("") self.enrichTable.setItem(row, 8, itemm) celllayout = QHBoxLayout() upbutton = QPushButton("Up") removebutton = QPushButton("Remove", self) removebutton.clicked.connect(self.deleteEnrichRow) downbutton = QPushButton("Down") celllayout.addWidget(upbutton) celllayout.addWidget(downbutton) celllayout.addWidget(removebutton) w = QWidget() w.setLayout(celllayout) optitem = QTableWidgetItem() #self.enrichTable.setCellWidget(row,4,w) #self.enrichTable.setItem(row,3,cbox) row += 1 self.originalRowCount = row
def initWidgets(self): # If there are advanced parameters — show corresponding groupbox for param in self.alg.parameters: if param.isAdvanced: self.grpAdvanced.show() break # Create widgets and put them in layouts 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)') if param.optional: desc += self.tr(' [optional]') wrapper = self.getWidgetWrapperFromParameter(param) self.wrappers[param.name] = wrapper widget = wrapper.widget if widget is not None: if isinstance(param, ParameterVector): layout = QHBoxLayout() layout.setSpacing(2) layout.setMargin(0) layout.addWidget(widget) button = QToolButton() icon = QIcon( os.path.join(pluginPath, 'images', 'iterate.png')) button.setIcon(icon) button.setToolTip(self.tr('Iterate over this layer')) button.setCheckable(True) layout.addWidget(button) self.iterateButtons[param.name] = button button.toggled.connect(self.buttonToggled) widget = QWidget() widget.setLayout(layout) tooltips = self.alg.getParameterDescriptions() widget.setToolTip(tooltips.get(param.name, param.description)) if type(widget) is QCheckBox: # checkbox widget - so description is embedded in widget rather than a separate # label widget.setText(desc) else: label = QLabel(desc) # label.setToolTip(tooltip) self.labels[param.name] = label if param.isAdvanced: self.layoutAdvanced.addWidget(label) else: self.layoutMain.insertWidget( self.layoutMain.count() - 2, label) if param.isAdvanced: self.layoutAdvanced.addWidget(widget) else: self.layoutMain.insertWidget(self.layoutMain.count() - 2, widget) for output in self.alg.outputs: if output.hidden: continue label = QLabel(output.description) widget = OutputSelectionPanel(output, self.alg) self.layoutMain.insertWidget(self.layoutMain.count() - 1, label) self.layoutMain.insertWidget(self.layoutMain.count() - 1, widget) if isinstance(output, (OutputRaster, OutputVector, OutputTable)): check = QCheckBox() check.setText( self.tr('Open output file after running algorithm')) check.setChecked(True) self.layoutMain.insertWidget(self.layoutMain.count() - 1, check) self.checkBoxes[output.name] = check self.outputWidgets[output.name] = widget for wrapper in list(self.wrappers.values()): wrapper.postInitialize(list(self.wrappers.values()))
def initWidgets(self): # Heavy overload # If there are advanced parameters — show corresponding groupbox for param in self.alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: self.grpAdvanced.show() break #widget_context = QgsProcessingParameterWidgetContext() #if iface is not None: # widget_context.setMapCanvas(iface.mapCanvas()) # Create widgets and put them in layouts for param in self.alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue print('initWidgets - param.name(): {}'.format(param.name())) if param.isDestination(): # and param.name() != 'OUTPUT_ASC': continue else: wrapper = WidgetWrapperFactory.create_wrapper(param, self.parent) self.wrappers[param.name()] = wrapper #widget = wrapper.widget # For compatibility with 3.x API, we need to check whether the wrapper is # the deprecated WidgetWrapper class. If not, it's the newer # QgsAbstractProcessingParameterWidgetWrapper class # TODO QGIS 4.0 - remove is_python_wrapper = issubclass(wrapper.__class__, WidgetWrapper) if not is_python_wrapper: from qgis.gui import (QgsProcessingContextGenerator, QgsProcessingParameterWidgetContext) widget_context = QgsProcessingParameterWidgetContext() if iface is not None: widget_context.setMapCanvas(iface.mapCanvas()) wrapper.setWidgetContext(widget_context) widget = wrapper.createWrappedWidget(self.processing_context) wrapper.registerProcessingContextGenerator(self.context_generator) else: widget = wrapper.widget #if self.in_place and param.name() in ('INPUT', 'OUTPUT'): # don't show the input/output parameter widgets in in-place mode # we still need to CREATE them, because other wrappers may need to interact # with them (e.g. those parameters which need the input layer for field # selections/crs properties/etc) # continue if widget is not None: if is_python_wrapper: widget.setToolTip(param.toolTip()) if isinstance(param, QgsProcessingParameterFeatureSource): layout = QHBoxLayout() layout.setSpacing(6) layout.setMargin(0) layout.addWidget(widget) button = QToolButton() icon = QIcon(os.path.join(pluginPath, 'images', 'iterate.png')) button.setIcon(icon) button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) button.setToolTip(self.tr('Iterate over this layer, creating a separate output for every feature in the layer')) button.setCheckable(True) layout.addWidget(button) layout.setAlignment(button, Qt.AlignTop) self.iterateButtons[param.name()] = button button.toggled.connect(self.buttonToggled) widget = QWidget() widget.setLayout(layout) label = None if not is_python_wrapper: label = wrapper.createWrappedLabel() else: label = wrapper.label if label is not None: if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: self.layoutAdvanced.addWidget(label) else: self.layoutMain.insertWidget( self.layoutMain.count() - 2, label) elif is_python_wrapper: desc = param.description() if isinstance(param, QgsProcessingParameterExtent): desc += self.tr(' (xmin, xmax, ymin, ymax)') if isinstance(param, QgsProcessingParameterPoint): desc += self.tr(' (x, y)') if param.flags() & QgsProcessingParameterDefinition.FlagOptional: desc += self.tr(' [optional]') widget.setText(desc) if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: self.layoutAdvanced.addWidget(widget) else: self.layoutMain.insertWidget( self.layoutMain.count() - 2, widget) for output in self.alg.destinationParameterDefinitions(): if output.flags() & QgsProcessingParameterDefinition.FlagHidden: continue #if self.in_place and param.name() in ('INPUT', 'OUTPUT'): # continue label = QLabel(output.description()) #print('initWidgets 2 - param.name(): {}'.format(param.name())) widget = DestinationSelectionPanel(output, self.alg) # TODO, overload self.layoutMain.insertWidget(self.layoutMain.count() - 1, label) self.layoutMain.insertWidget(self.layoutMain.count() - 1, widget) if isinstance(output, (QgsProcessingParameterRasterDestination, QgsProcessingParameterFeatureSink, QgsProcessingParameterVectorDestination # alk: checkboxes for Chloe handling ,ChloeCSVParameterFileDestination, ChloeASCParameterFileDestination, ChloeParameterFolderDestination) ): check = QCheckBox() check.setText(QCoreApplication.translate('ParametersPanel', 'Open output file(s) after running algorithm')) def skipOutputChanged(checkbox, skipped): checkbox.setEnabled(not skipped) if skipped: checkbox.setChecked(False) check.setChecked(not widget.outputIsSkipped()) check.setEnabled(not widget.outputIsSkipped()) widget.skipOutputChanged.connect(partial(skipOutputChanged, check)) self.layoutMain.insertWidget(self.layoutMain.count() - 1, check) self.checkBoxes[output.name()] = check # initial state if hasattr(output,'addToMapDefaultState'): check.setChecked(output.addToMapDefaultState) widget.setToolTip(param.toolTip()) self.outputWidgets[output.name()] = widget for wrapper in list(self.wrappers.values()): wrapper.postInitialize(list(self.wrappers.values())) # # alk: checkboxes for Chloe handling # for output in self.alg.destinationParameterDefinitions(): # if output.flags() & QgsProcessingParameterDefinition.FlagHidden: # continue # if isinstance(output, (ChloeCSVParameterFileDestination)) or isinstance(output, (ChloeASCParameterFileDestination)): # check = QCheckBox() # check.setText(QCoreApplication.translate('ParametersPanel', 'Open output file(s) after running algorithm')) # def skipOutputChanged(checkbox, skipped): # checkbox.setEnabled(not skipped) # if skipped: # checkbox.setChecked(False) # check.setChecked(not widget.outputIsSkipped()) # check.setEnabled(not widget.outputIsSkipped()) # widget.skipOutputChanged.connect(partial(skipOutputChanged, check)) # print(str(self.layoutMain)+1) # self.layoutMain.insertWidget(self.layoutMain.count() - 1, check) # self.checkBoxes[output.name()] = check # # connecting alg outputLoading info with checkbox state # self.alg.outputLoading[output.name()] = check.isChecked() # def updateOutputLoadingState(alg, outputName, checkbox, state): # self.alg.outputLoading[outputName] = checkbox.isChecked() # print( outputName + " " + str(checkbox.isChecked()) + " " + str(self.alg.outputLoading) + " " + str(self.alg)) # #print(str(self.alg.parameters)) # check.stateChanged.connect(partial(updateOutputLoadingState, self, output.name(), check)) # alk: addition of wrapper special config handling # for dependancy between wrapper, i.e. changing the value # of a FileSelectionPanel entails the update of another widget for k in self.wrappers: w = self.wrappers[k] if hasattr(w,'getParentWidgetConfig'): print(str(w) + " " + "getParentWidgetConfig") config = w.getParentWidgetConfig() if config != None: p = self.wrappers[config['paramName']] m = getattr(w, config['refreshMethod']) if m!=None: print(str(p) + " " + str(p.widget)) # todo generalize valueChanged handling # to any type of widget componant if isinstance(p.widget, FileSelectionPanel): p.widget.leText.textChanged.connect(m) elif isinstance(p, RasterWidgetWrapper): try: p.combo.valueChanged.connect(m) # QGIS 3.8 version except: p.combo.currentIndexChanged.connect(m) # QGIS LTR 3.4
def initGui(self): self.setWindowTitle('GeoGig user configuration') verticalLayout = QVBoxLayout() horizontalLayout = QHBoxLayout() horizontalLayout.setSpacing(30) horizontalLayout.setMargin(0) usernameLabel = QLabel('Username') self.usernameBox = QLineEdit() horizontalLayout.addWidget(usernameLabel) horizontalLayout.addWidget(self.usernameBox) verticalLayout.addLayout(horizontalLayout) horizontalLayout = QHBoxLayout() horizontalLayout.setSpacing(30) horizontalLayout.setMargin(0) emailLabel = QLabel('User email') self.emailBox = QLineEdit() horizontalLayout.addWidget(emailLabel) horizontalLayout.addWidget(self.emailBox) verticalLayout.addLayout(horizontalLayout) self.groupBox = QGroupBox() self.groupBox.setTitle("User data") self.groupBox.setLayout(verticalLayout) layout = QVBoxLayout() layout.addWidget(self.groupBox) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) layout.addWidget(self.buttonBox) self.setLayout(layout) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) self.resize(400, 200)
class CommanderWindow(QDialog): def __init__(self, parent, canvas): self.canvas = canvas QDialog.__init__(self, parent, Qt.FramelessWindowHint) self.commands = imp.load_source('commands', self.commandsFile()) self.initGui() def commandsFolder(self): folder = str(os.path.join(userFolder(), 'commander')) mkdir(folder) return os.path.abspath(folder) def commandsFile(self): f = os.path.join(self.commandsFolder(), 'commands.py') if not os.path.exists(f): with open(f, 'w') as out: out.write('from qgis.core import *\n') out.write('import processing\n\n') out.write('def removeall():\n') out.write('\tmapreg = QgsProject.instance()\n') out.write('\tmapreg.removeAllMapLayers()\n\n') out.write('def load(*args):\n') out.write('\tprocessing.load(args[0])\n') return f def algsListHasChanged(self): self.fillCombo() def initGui(self): self.combo = ExtendedComboBox() self.fillCombo() self.combo.setEditable(True) self.label = QLabel('Enter command:') self.errorLabel = QLabel('Enter command:') self.vlayout = QVBoxLayout() self.vlayout.setSpacing(2) self.vlayout.setMargin(0) self.vlayout.addSpacerItem( QSpacerItem(0, OFFSET, QSizePolicy.Maximum, QSizePolicy.Expanding)) self.hlayout = QHBoxLayout() self.hlayout.addWidget(self.label) self.vlayout.addLayout(self.hlayout) self.hlayout2 = QHBoxLayout() self.hlayout2.addWidget(self.combo) self.vlayout.addLayout(self.hlayout2) self.vlayout.addSpacerItem( QSpacerItem(0, OFFSET, QSizePolicy.Maximum, QSizePolicy.Expanding)) self.setLayout(self.vlayout) self.combo.lineEdit().returnPressed.connect(self.run) self.prepareGui() def fillCombo(self): self.combo.clear() # Add algorithms for provider in list(algList.algs.values()): for alg in provider: self.combo.addItem('Processing algorithm: ' + alg) # Add functions for command in dir(self.commands): if isinstance(self.commands.__dict__.get(command), types.FunctionType): self.combo.addItem('Command: ' + command) # Add menu entries menuActions = [] actions = iface.mainWindow().menuBar().actions() for action in actions: menuActions.extend(self.getActions(action)) for action in menuActions: self.combo.addItem('Menu action: ' + str(action.text())) def prepareGui(self): self.combo.setEditText('') self.combo.setMaximumSize( QSize(self.canvas.rect().width() - 2 * OFFSET, ITEMHEIGHT)) self.combo.view().setStyleSheet('min-height: 150px') self.combo.setFocus(Qt.OtherFocusReason) self.label.setMaximumSize(self.combo.maximumSize()) self.label.setVisible(False) self.adjustSize() pt = self.canvas.rect().topLeft() absolutePt = self.canvas.mapToGlobal(pt) self.move(absolutePt) self.resize(self.canvas.rect().width(), HEIGHT) self.setStyleSheet('CommanderWindow {background-color: #e7f5fe; \ border: 1px solid #b9cfe4;}') def getActions(self, action): menuActions = [] menu = action.menu() if menu is None: menuActions.append(action) return menuActions else: actions = menu.actions() for subaction in actions: if subaction.menu() is not None: menuActions.extend(self.getActions(subaction)) elif not subaction.isSeparator(): menuActions.append(subaction) return menuActions def run(self): s = str(self.combo.currentText()) if s.startswith('Processing algorithm: '): algName = s[len('Processing algorithm: '):] alg = algList.getAlgorithm(algName) if alg is not None: self.close() self.runAlgorithm(alg) elif s.startswith("Command: "): command = s[len("Command: "):] try: self.runCommand(command) self.close() except Exception as e: self.label.setVisible(True) self.label.setText('Error:' + str(e)) elif s.startswith('Menu action: '): actionName = s[len('Menu action: '):] menuActions = [] actions = iface.mainWindow().menuBar().actions() for action in actions: menuActions.extend(self.getActions(action)) for action in menuActions: if action.text() == actionName: self.close() action.trigger() return else: try: self.runCommand(s) self.close() except Exception as e: self.label.setVisible(True) self.label.setText('Error:' + str(e)) def runCommand(self, command): tokens = command.split(' ') if len(tokens) == 1: method = self.commands.__dict__.get(command) if method is not None: method() else: raise Exception('Wrong command') else: method = self.commands.__dict__.get(tokens[0]) if method is not None: method(*tokens[1:]) else: raise Exception('Wrong command') def runAlgorithm(self, alg): alg = alg.getCopy() message = alg.checkBeforeOpeningParametersDialog() if message: dlg = MessageDialog() dlg.setTitle(self.tr('Missing dependency')) dlg.setMessage(message) dlg.exec_() return dlg = alg.getCustomParametersDialog() if not dlg: dlg = AlgorithmDialog(alg) canvas = iface.mapCanvas() prevMapTool = canvas.mapTool() dlg.show() dlg.exec_() if canvas.mapTool() != prevMapTool: try: canvas.mapTool().reset() except: pass canvas.setMapTool(prevMapTool)
def setupUi(self): self.labels = {} self.widgets = {} self.checkBoxes = {} self.showAdvanced = False self.wrappers = {} self.valueItems = {} self.dependentItems = {} self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok | QDialogButtonBox.Help) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(5) self.verticalLayout.setMargin(20) self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.verticalLayout.addWidget(self.bar) hLayout = QHBoxLayout() hLayout.setSpacing(5) hLayout.setMargin(0) descriptionLabel = QLabel(self.tr("Description")) self.descriptionBox = QLineEdit() self.descriptionBox.setText(self._alg.displayName()) 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.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: 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.parameterDefinitions(): if param.isDestination( ) or param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue desc = param.description() if isinstance(param, QgsProcessingParameterExtent): desc += self.tr('(xmin, xmax, ymin, ymax)') if isinstance(param, QgsProcessingParameterPoint): desc += self.tr('(x, y)') if param.flags() & QgsProcessingParameterDefinition.FlagOptional: desc += self.tr(' [optional]') label = QLabel(desc) self.labels[param.name()] = label wrapper = WidgetWrapperFactory.create_wrapper(param, self) self.wrappers[param.name()] = wrapper widget = wrapper.widget if widget is not None: self.valueItems[param.name()] = widget tooltip = param.description() label.setToolTip(tooltip) widget.setToolTip(tooltip) if param.flags( ) & QgsProcessingParameterDefinition.FlagAdvanced: label.setVisible(self.showAdvanced) widget.setVisible(self.showAdvanced) self.widgets[param.name()] = widget self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(widget) for dest in self._alg.destinationParameterDefinitions(): if dest.flags() & QgsProcessingParameterDefinition.FlagHidden: continue if isinstance(dest, (QgsProcessingParameterRasterDestination, QgsProcessingParameterFeatureSink, QgsProcessingParameterFileDestination, QgsProcessingParameterFolderDestination)): label = QLabel(dest.description()) item = QgsFilterLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(item) self.valueItems[dest.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.setPreviousValues() self.setWindowTitle(self._alg.displayName()) self.verticalLayout2 = QVBoxLayout() self.verticalLayout2.setSpacing(2) self.verticalLayout2.setMargin(0) self.paramPanel = QWidget() self.paramPanel.setLayout(self.verticalLayout) self.scrollArea = QgsScrollArea() self.scrollArea.setWidget(self.paramPanel) self.scrollArea.setWidgetResizable(True) self.verticalLayout2.addWidget(self.scrollArea) self.verticalLayout2.addWidget(self.buttonBox) self.setLayout(self.verticalLayout2) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) self.buttonBox.helpRequested.connect(self.openHelp) QMetaObject.connectSlotsByName(self) for wrapper in list(self.wrappers.values()): wrapper.postInitialize(list(self.wrappers.values()))
def __init__(self, column, parent=None, pixmap=None, host=None): """ Class constructor. :param column: Column object containing foreign key information. :type column: BaseColumn :param parent: Parent widget for the control. :type parent: QWidget :param pixmap: Pixmap to use for the line edit button. :type pixmap: QPixmap """ QLineEdit.__init__(self, parent) self.column = column self._entity = self.column.entity self.entity_dialog = host # Configure load button self.btn_load = QToolButton(parent) self.btn_load.setCursor(Qt.PointingHandCursor) self.btn_load.setFocusPolicy(Qt.NoFocus) px = GuiUtils.get_icon_pixmap('select_record.png') if not pixmap is None: px = pixmap self.btn_load.setIcon(QIcon(px)) self.btn_load.setIconSize(px.size()) self.btn_load.setStyleSheet('background: transparent; padding: 0px; ' 'border: none;') self.btn_load.clicked.connect(self.on_load_foreign_key_browser) clear_px = GuiUtils.get_icon_pixmap('clear.png') self.btn_clear = QToolButton(parent) self.btn_clear.setCursor(Qt.PointingHandCursor) self.btn_clear.setFocusPolicy(Qt.NoFocus) self.btn_clear.setIcon(QIcon(clear_px)) self.btn_clear.setIconSize(clear_px.size()) self.btn_clear.setStyleSheet('background: transparent; padding: 0px; ' 'border: none;') self.btn_clear.clicked.connect(self.clear_line_edit) frame_width = self.set_button_minimum_size(self.btn_load) self.set_button_minimum_size(self.btn_clear) # Ensure that text does not overlay button padding = self.btn_load.sizeHint().width() + frame_width + 1 self.setStyleSheet('padding-right: ' + str(padding * 2) + 'px;') # Set layout self.button_layout = QHBoxLayout(self) self.button_layout.addWidget(self.btn_clear, 0, Qt.AlignRight) self.button_layout.addWidget(self.btn_load, 0, Qt.AlignRight) self.button_layout.setSpacing(0) self.button_layout.setMargin(5) self.btn_clear.setVisible(False) # Readonly as text is loaded from the related entity self.setReadOnly(True) # Current model object self._current_item = None
def __init__(self, scene): QWidget.__init__(self) self.scene = scene self.properties = scene[PROPERTIES] self.setMouseTracking(True) datetime = iso8601.parse_date(self.properties["acquired"]) time = datetime.strftime("%H:%M:%S") date = datetime.strftime("%b %d, %Y") text = f"""{date}<span style="color: rgb(100,100,100);"> {time} UTC</span><br> <b>{PlanetClient.getInstance().item_types_names()[self.properties['item_type']]}</b> """ self.nameLabel = QLabel(text) self.iconLabel = QLabel() self.toolsButton = QLabel() self.toolsButton.setPixmap(COG_ICON.pixmap(QSize(18, 18))) self.toolsButton.mousePressEvent = self.showContextMenu pixmap = QPixmap(PLACEHOLDER_THUMB, "SVG") thumb = pixmap.scaled(48, 48, Qt.KeepAspectRatio, Qt.SmoothTransformation) self.iconLabel.setPixmap(thumb) layout = QHBoxLayout() layout.setMargin(2) vlayout = QVBoxLayout() vlayout.setMargin(0) vlayout.addWidget(self.iconLabel) self.iconWidget = QWidget() self.iconWidget.setFixedSize(48, 48) self.iconWidget.setLayout(vlayout) layout.addWidget(self.iconWidget) layout.addWidget(self.nameLabel) layout.addStretch() layout.addWidget(self.toolsButton) layout.addSpacing(10) self.setLayout(layout) self.nam = QNetworkAccessManager() self.nam.finished.connect(self.iconDownloaded) url = f"{scene['_links']['thumbnail']}?api_key={PlanetClient.getInstance().api_key()}" self.nam.get(QNetworkRequest(QUrl(url))) self.footprint = QgsRubberBand(iface.mapCanvas(), QgsWkbTypes.PolygonGeometry) self.footprint.setStrokeColor(PLANET_COLOR) self.footprint.setWidth(2) self.geom = qgsgeometry_from_geojson(scene[GEOMETRY]) self.setStyleSheet("SceneItemWidget{border: 2px solid transparent;}")
class ForeignKeyLineEdit(QLineEdit): """ Line edit that enables the browsing of related entities defined through foreign key constraint. """ def __init__(self, column, parent=None, pixmap=None, host=None): """ Class constructor. :param column: Column object containing foreign key information. :type column: BaseColumn :param parent: Parent widget for the control. :type parent: QWidget :param pixmap: Pixmap to use for the line edit button. :type pixmap: QPixmap """ QLineEdit.__init__(self, parent) self.column = column self._entity = self.column.entity self.entity_dialog = host # Configure load button self.btn_load = QToolButton(parent) self.btn_load.setCursor(Qt.PointingHandCursor) self.btn_load.setFocusPolicy(Qt.NoFocus) px = GuiUtils.get_icon_pixmap('select_record.png') if not pixmap is None: px = pixmap self.btn_load.setIcon(QIcon(px)) self.btn_load.setIconSize(px.size()) self.btn_load.setStyleSheet('background: transparent; padding: 0px; ' 'border: none;') self.btn_load.clicked.connect(self.on_load_foreign_key_browser) clear_px = GuiUtils.get_icon_pixmap('clear.png') self.btn_clear = QToolButton(parent) self.btn_clear.setCursor(Qt.PointingHandCursor) self.btn_clear.setFocusPolicy(Qt.NoFocus) self.btn_clear.setIcon(QIcon(clear_px)) self.btn_clear.setIconSize(clear_px.size()) self.btn_clear.setStyleSheet('background: transparent; padding: 0px; ' 'border: none;') self.btn_clear.clicked.connect(self.clear_line_edit) frame_width = self.set_button_minimum_size(self.btn_load) self.set_button_minimum_size(self.btn_clear) # Ensure that text does not overlay button padding = self.btn_load.sizeHint().width() + frame_width + 1 self.setStyleSheet('padding-right: ' + str(padding * 2) + 'px;') # Set layout self.button_layout = QHBoxLayout(self) self.button_layout.addWidget(self.btn_clear, 0, Qt.AlignRight) self.button_layout.addWidget(self.btn_load, 0, Qt.AlignRight) self.button_layout.setSpacing(0) self.button_layout.setMargin(5) self.btn_clear.setVisible(False) # Readonly as text is loaded from the related entity self.setReadOnly(True) # Current model object self._current_item = None def set_button_minimum_size(self, button): """ Sets the minimum button size. :param button: The button to be set. :type button: QToolButton :return: Returns the frame width of the button :rtype: Integer """ frame_width = self.style().pixelMetric(QStyle.PM_DefaultFrameWidth) msz = self.minimumSizeHint() self.setMinimumSize( max( msz.width(), button.sizeHint().height() + frame_width * 2 + 2 ), max( msz.height(), button.sizeHint().height() + frame_width * 2 + 2 ) ) return frame_width @property def current_item(self): return self._current_item @current_item.setter def current_item(self, value): # Update display every time the current item is changed. self._current_item = value self.format_display() @property def entity(self): """ :return: Returns the entity object corresponding to this widget. :rtype: Entity """ return self._entity def clear_line_edit(self): """ Clears the text in the line edit. """ self.clear() self.hide_clear_button() def hide_clear_button(self): """ Hides the clear button. """ self.btn_clear.setVisible(False) self.button_layout.setStretch(0, 0) def show_clear_button(self): """ Shows the clear button if a text exists. """ if len(self.text()) > 0: self.btn_clear.setVisible(True) self.button_layout.setStretch(0, 5) def on_load_foreign_key_browser(self): """ Slot raised to load browser for selecting foreign key entities. To be implemented by subclasses. """ raise NotImplementedError def format_display(self): """ Extract object values to show in the line edit based on the specified display columns. """ raise NotImplementedError def parent_entity_model(self): """ :return: Returns the database model corresponding to the parent table of the relation defined by this column. Please note that the database model will not contain relationship configurations in its attributes. :rtype: object """ entity = self.column.entity_relation.parent return entity_model(entity, entity_only=True) def load_current_item_from_id(self, id): """ Loads the current item from the id corresponding to the primary key. :param id: Primary key of the referenced entity. :type id: int """ QApplication.processEvents() model = self.parent_entity_model() if model is None: return model_obj = model() res = model_obj.queryObject().filter(model.id == id).first() if not res is None: self.current_item = res
def setupUi(self): self.labels = {} self.widgets = {} self.checkBoxes = {} self.showAdvanced = False self.wrappers = {} 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) self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.verticalLayout.addWidget(self.bar) hLayout = QHBoxLayout() hLayout.setSpacing(5) hLayout.setMargin(0) descriptionLabel = QLabel(self.tr("Description")) self.descriptionBox = QLineEdit() self.descriptionBox.setText(self._alg.displayName()) 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)') if param.optional: desc += self.tr(' [optional]') label = QLabel(desc) self.labels[param.name] = label wrapper = param.wrapper(self) self.wrappers[param.name] = wrapper widget = wrapper.widget if widget is not None: self.valueItems[param.name] = widget if param.name in list(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.setPreviousValues() self.setWindowTitle(self._alg.displayName()) 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 = QgsScrollArea() self.scrollArea.setWidget(self.paramPanel) self.scrollArea.setWidgetResizable(True) self.tabWidget.addTab(self.scrollArea, self.tr('Parameters')) self.txtHelp = QTextBrowser() html = None isText, algHelp = self._alg.help() if algHelp is not None: algHelp = algHelp if isText else QUrl(algHelp) try: if isText: self.txtHelp.setHtml(algHelp) else: html = self.tr( '<p>Downloading algorithm help... Please wait.</p>') self.txtHelp.setHtml(html) self.tabWidget.addTab(self.txtHelp, 'Help') self.reply = QgsNetworkAccessManager.instance().get( QNetworkRequest(algHelp)) self.reply.finished.connect(self.requestFinished) except: pass 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) for wrapper in list(self.wrappers.values()): wrapper.postInitialize(list(self.wrappers.values()))
def setupUi(self): type_metadata = QgsApplication.processingRegistry().parameterType( self.param.type() if self.param else self.paramType) self.setWindowTitle( self.tr('{} Parameter Definition').format(type_metadata.name())) self.mainLayout = QVBoxLayout() self.tab = QTabWidget() self.mainLayout.addWidget(self.tab) self.setMinimumWidth(300) self.verticalLayout = QVBoxLayout() self.label = QLabel(self.tr('Parameter name')) self.verticalLayout.addWidget(self.label) self.nameTextBox = QLineEdit() self.verticalLayout.addWidget(self.nameTextBox) if isinstance(self.param, QgsProcessingParameterDefinition): self.nameTextBox.setText(self.param.description()) if self.paramType == parameters.PARAMETER_TABLE_FIELD or \ isinstance(self.param, QgsProcessingParameterField): self.verticalLayout.addWidget(QLabel(self.tr('Parent layer'))) self.parentCombo = QComboBox() idx = 0 for param in list(self.alg.parameterComponents().values()): definition = self.alg.parameterDefinition( param.parameterName()) if isinstance(definition, (QgsProcessingParameterFeatureSource, QgsProcessingParameterVectorLayer)): self.parentCombo.addItem(definition.description(), definition.name()) if self.param is not None: if self.param.parentLayerParameterName( ) == definition.name(): self.parentCombo.setCurrentIndex(idx) idx += 1 self.verticalLayout.addWidget(self.parentCombo) # add the datatype selector self.verticalLayout.addWidget(QLabel(self.tr('Allowed data type'))) self.datatypeCombo = QComboBox() self.datatypeCombo.addItem(self.tr('Any'), -1) self.datatypeCombo.addItem(self.tr('Number'), 0) self.datatypeCombo.addItem(self.tr('String'), 1) self.datatypeCombo.addItem(self.tr('Date/time'), 2) self.verticalLayout.addWidget(self.datatypeCombo) if self.param is not None and self.param.dataType() is not None: # QComboBoxes indexes start at 0, # self.param.datatype start with -1 that is why I need to do +1 datatypeIndex = self.param.dataType() + 1 self.datatypeCombo.setCurrentIndex(datatypeIndex) self.multipleCheck = QCheckBox() self.multipleCheck.setText(self.tr('Accept multiple fields')) self.multipleCheck.setChecked(False) if self.param is not None: self.multipleCheck.setChecked(self.param.allowMultiple()) self.verticalLayout.addWidget(self.multipleCheck) self.verticalLayout.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() self.defaultTextBox.setToolTip( self. tr('Default field name, or ; separated list of field names for multiple field parameters' )) if self.param is not None: default = self.param.defaultValue() if default is not None: self.defaultTextBox.setText(str(default)) self.verticalLayout.addWidget(self.defaultTextBox) elif self.paramType == parameters.PARAMETER_BAND or \ isinstance(self.param, QgsProcessingParameterBand): self.verticalLayout.addWidget(QLabel(self.tr('Parent layer'))) self.parentCombo = QComboBox() idx = 0 for param in list(self.alg.parameterComponents().values()): definition = self.alg.parameterDefinition( param.parameterName()) if isinstance(definition, (QgsProcessingParameterRasterLayer)): self.parentCombo.addItem(definition.description(), definition.name()) if self.param is not None: if self.param.parentLayerParameterName( ) == definition.name(): self.parentCombo.setCurrentIndex(idx) idx += 1 self.verticalLayout.addWidget(self.parentCombo) elif (self.paramType in (parameters.PARAMETER_VECTOR, parameters.PARAMETER_TABLE) or isinstance(self.param, (QgsProcessingParameterFeatureSource, QgsProcessingParameterVectorLayer))): self.verticalLayout.addWidget(QLabel(self.tr('Geometry type'))) self.shapetypeCombo = QComboBox() self.shapetypeCombo.addItem(self.tr('Geometry Not Required'), QgsProcessing.TypeVector) self.shapetypeCombo.addItem(self.tr('Point'), QgsProcessing.TypeVectorPoint) self.shapetypeCombo.addItem(self.tr('Line'), QgsProcessing.TypeVectorLine) self.shapetypeCombo.addItem(self.tr('Polygon'), QgsProcessing.TypeVectorPolygon) self.shapetypeCombo.addItem(self.tr('Any Geometry Type'), QgsProcessing.TypeVectorAnyGeometry) if self.param is not None: self.shapetypeCombo.setCurrentIndex( self.shapetypeCombo.findData(self.param.dataTypes()[0])) self.verticalLayout.addWidget(self.shapetypeCombo) elif (self.paramType == parameters.PARAMETER_MULTIPLE or isinstance(self.param, QgsProcessingParameterMultipleLayers)): self.verticalLayout.addWidget(QLabel(self.tr('Data type'))) self.datatypeCombo = QComboBox() self.datatypeCombo.addItem(self.tr('Any Map Layer'), QgsProcessing.TypeMapLayer) self.datatypeCombo.addItem( self.tr('Vector (No Geometry Required)'), QgsProcessing.TypeVector) self.datatypeCombo.addItem(self.tr('Vector (Point)'), QgsProcessing.TypeVectorPoint) self.datatypeCombo.addItem(self.tr('Vector (Line)'), QgsProcessing.TypeVectorLine) self.datatypeCombo.addItem(self.tr('Vector (Polygon)'), QgsProcessing.TypeVectorPolygon) self.datatypeCombo.addItem(self.tr('Vector (Any Geometry Type)'), QgsProcessing.TypeVectorAnyGeometry) self.datatypeCombo.addItem(self.tr('Raster'), QgsProcessing.TypeRaster) self.datatypeCombo.addItem(self.tr('File'), QgsProcessing.TypeFile) if self.param is not None: self.datatypeCombo.setCurrentIndex( self.datatypeCombo.findData(self.param.layerType())) self.verticalLayout.addWidget(self.datatypeCombo) elif (self.paramType == parameters.PARAMETER_MAP_LAYER or isinstance(self.param, QgsProcessingParameterMapLayer)): self.verticalLayout.addWidget(QLabel(self.tr('Data type'))) self.datatypeCombo = QComboBox() self.datatypeCombo.addItem(self.tr('Any Map Layer'), QgsProcessing.TypeMapLayer) self.datatypeCombo.addItem(self.tr('Vector (Point)'), QgsProcessing.TypeVectorPoint) self.datatypeCombo.addItem(self.tr('Vector (Line)'), QgsProcessing.TypeVectorLine) self.datatypeCombo.addItem(self.tr('Vector (Polygon)'), QgsProcessing.TypeVectorPolygon) self.datatypeCombo.addItem(self.tr('Vector (Any Geometry Type)'), QgsProcessing.TypeVectorAnyGeometry) self.datatypeCombo.addItem(self.tr('Raster'), QgsProcessing.TypeRaster) self.datatypeCombo.addItem(self.tr('Mesh'), QgsProcessing.TypeMesh) if self.param is not None: self.datatypeCombo.setCurrentIndex( self.datatypeCombo.findData(self.param.dataTypes()[0])) self.verticalLayout.addWidget(self.datatypeCombo) elif (self.paramType in (parameters.PARAMETER_NUMBER, parameters.PARAMETER_DISTANCE, parameters.PARAMETER_SCALE) or isinstance(self.param, (QgsProcessingParameterNumber, QgsProcessingParameterDistance, QgsProcessingParameterScale))): if (self.paramType == parameters.PARAMETER_DISTANCE or isinstance(self.param, QgsProcessingParameterDistance)): self.verticalLayout.addWidget(QLabel(self.tr('Linked input'))) self.parentCombo = QComboBox() self.parentCombo.addItem('', '') idx = 1 for param in list(self.alg.parameterComponents().values()): definition = self.alg.parameterDefinition( param.parameterName()) if isinstance(definition, (QgsProcessingParameterFeatureSource, QgsProcessingParameterVectorLayer, QgsProcessingParameterMapLayer, QgsProcessingParameterCrs)): self.parentCombo.addItem(definition.description(), definition.name()) if self.param is not None: if self.param.parentParameterName( ) == definition.name(): self.parentCombo.setCurrentIndex(idx) idx += 1 self.verticalLayout.addWidget(self.parentCombo) elif (self.paramType != parameters.PARAMETER_SCALE and not isinstance(self.param, QgsProcessingParameterScale)): self.verticalLayout.addWidget(QLabel(self.tr('Number type'))) self.type_combo = QComboBox() self.type_combo.addItem(self.tr('Float'), QgsProcessingParameterNumber.Double) self.type_combo.addItem(self.tr('Integer'), QgsProcessingParameterNumber.Integer) if self.param: self.type_combo.setCurrentIndex( self.type_combo.findData(self.param.dataType())) self.verticalLayout.addWidget(self.type_combo) if (self.paramType != parameters.PARAMETER_SCALE and not isinstance(self.param, QgsProcessingParameterScale)): self.verticalLayout.addWidget(QLabel(self.tr('Min value'))) self.minTextBox = QLineEdit() self.verticalLayout.addWidget(self.minTextBox) self.verticalLayout.addWidget(QLabel(self.tr('Max value'))) self.maxTextBox = QLineEdit() self.verticalLayout.addWidget(self.maxTextBox) if self.param is not None: self.minTextBox.setText(str(self.param.minimum())) self.maxTextBox.setText(str(self.param.maximum())) self.verticalLayout.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() self.defaultTextBox.setText(self.tr('0')) if self.param is not None: default = self.param.defaultValue() if self.param.dataType( ) == QgsProcessingParameterNumber.Integer: default = int(math.floor(float(default))) if default: self.defaultTextBox.setText(str(default)) self.verticalLayout.addWidget(self.defaultTextBox) elif isinstance(self.param, QgsProcessingDestinationParameter): self.verticalLayout.addWidget(QLabel(self.tr('Default value'))) self.defaultWidget = QgsProcessingLayerOutputDestinationWidget( self.param, defaultSelection=True) self.verticalLayout.addWidget(self.defaultWidget) self.verticalLayout.addSpacing(20) self.requiredCheck = QCheckBox() self.requiredCheck.setText(self.tr('Mandatory')) self.requiredCheck.setChecked(True) if self.param is not None: self.requiredCheck.setChecked( not self.param.flags() & QgsProcessingParameterDefinition.FlagOptional) self.verticalLayout.addWidget(self.requiredCheck) self.advancedCheck = QCheckBox() self.advancedCheck.setText(self.tr('Advanced')) self.advancedCheck.setChecked(False) if self.param is not None: self.advancedCheck.setChecked( self.param.flags() & QgsProcessingParameterDefinition.FlagAdvanced) self.verticalLayout.addWidget(self.advancedCheck) # If child algorithm output is mandatory, disable checkbox if isinstance(self.param, QgsProcessingDestinationParameter): provider_name, child_name, output_name = self.param.name().split( ':') child = self.alg.childAlgorithms()['{}:{}'.format( provider_name, child_name)] model_output = child.modelOutput(output_name) param_def = child.algorithm().parameterDefinition( model_output.childOutputName()) if not (param_def.flags() & QgsProcessingParameterDefinition.FlagOptional): self.requiredCheck.setEnabled(False) self.requiredCheck.setChecked(True) self.advancedCheck.setEnabled(False) self.advancedCheck.setChecked(False) self.verticalLayout.addStretch() w = QWidget() w.setLayout(self.verticalLayout) self.tab.addTab(w, self.tr('Properties')) self.commentLayout = QVBoxLayout() self.commentEdit = QTextEdit() self.commentEdit.setAcceptRichText(False) self.commentLayout.addWidget(self.commentEdit, 1) hl = QHBoxLayout() hl.setContentsMargins(0, 0, 0, 0) hl.addWidget(QLabel(self.tr('Color'))) self.comment_color_button = QgsColorButton() self.comment_color_button.setAllowOpacity(True) self.comment_color_button.setWindowTitle(self.tr('Comment Color')) self.comment_color_button.setShowNull(True, self.tr('Default')) hl.addWidget(self.comment_color_button) self.commentLayout.addLayout(hl) w2 = QWidget() w2.setLayout(self.commentLayout) self.tab.addTab(w2, self.tr('Comments')) 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.accept) self.buttonBox.rejected.connect(self.reject) self.mainLayout.addWidget(self.buttonBox) self.setLayout(self.mainLayout)
def createWidget(self): if self.dialogType == DIALOG_STANDARD: widget = QWidget() layout = QHBoxLayout() layout.setMargin(0) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(2) self.combo = QgsMapLayerComboBox() layout.addWidget(self.combo) btn = QToolButton() btn.setText('...') btn.setToolTip(self.tr("Select file")) btn.clicked.connect(self.selectFile) layout.addWidget(btn) widget.setLayout(layout) filters = QgsMapLayerProxyModel.Filters() if self.param.datatype == [-1] or -1 in self.param.datatype: filters = QgsMapLayerProxyModel.HasGeometry if QgsWkbTypes.PointGeometry in self.param.datatype: filters |= QgsMapLayerProxyModel.PointLayer if QgsWkbTypes.LineGeometry in self.param.datatype: filters |= QgsMapLayerProxyModel.LineLayer if QgsWkbTypes.PolygonGeometry in self.param.datatype: filters |= QgsMapLayerProxyModel.PolygonLayer try: if iface.activeLayer().type() == QgsMapLayer.VectorLayer: self.combo.setLayer(iface.activeLayer()) except: pass if self.param.optional: self.combo.setAllowEmptyLayer(True) if ProcessingConfig.getSetting(ProcessingConfig.SHOW_CRS_DEF): self.combo.setShowCrs(True) self.combo.setFilters(filters) self.combo.setExcludedProviders(['grass']) self.combo.currentIndexChanged.connect( lambda: self.widgetValueHasChanged.emit(self)) self.combo.currentTextChanged.connect( lambda: self.widgetValueHasChanged.emit(self)) return widget elif self.dialogType == DIALOG_BATCH: widget = BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) widget.valueChanged.connect( lambda: self.widgetValueHasChanged.emit(self)) return widget else: self.combo = QComboBox() layers = self.dialog.getAvailableValuesOfType( ParameterVector, OutputVector) self.combo.setEditable(True) for layer in layers: self.combo.addItem(self.dialog.resolveValueDescription(layer), layer) if self.param.optional: self.combo.setEditText("") widget = QWidget() layout = QHBoxLayout() layout.setMargin(0) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(2) layout.addWidget(self.combo) btn = QToolButton() btn.setText('...') btn.setToolTip(self.tr("Select file")) btn.clicked.connect(self.selectFile) layout.addWidget(btn) widget.setLayout(layout) return widget
class BatchInputSelectionPanel(QWidget): valueChanged = pyqtSignal() def __init__(self, param, row, col, dialog): super(BatchInputSelectionPanel, self).__init__(None) self.param = param self.dialog = dialog self.row = row self.col = col self.horizontalLayout = QHBoxLayout(self) self.horizontalLayout.setSpacing(0) self.horizontalLayout.setMargin(0) self.text = QLineEdit() self.text.setObjectName('text') self.text.setMinimumWidth(300) self.setValue('') self.text.editingFinished.connect(self.textEditingFinished) 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 _panel(self): return self.dialog.mainWidget() def _table(self): return self._panel().tblParameters def showPopupMenu(self): popupmenu = QMenu() if not (isinstance(self.param, QgsProcessingParameterMultipleLayers) and self.param.layerType == dataobjects.TYPE_FILE): selectLayerAction = QAction( QCoreApplication.translate('BatchInputSelectionPanel', 'Select from Open Layers…'), self.pushButton) selectLayerAction.triggered.connect(self.showLayerSelectionDialog) popupmenu.addAction(selectLayerAction) selectFileAction = QAction( QCoreApplication.translate('BatchInputSelectionPanel', 'Select from File System…'), self.pushButton) selectFileAction.triggered.connect(self.showFileSelectionDialog) popupmenu.addAction(selectFileAction) popupmenu.exec_(QCursor.pos()) def showLayerSelectionDialog(self): layers = [] if (isinstance(self.param, QgsProcessingParameterRasterLayer) or (isinstance(self.param, QgsProcessingParameterMultipleLayers) and self.param.layerType() == QgsProcessing.TypeRaster)): layers = QgsProcessingUtils.compatibleRasterLayers(QgsProject.instance()) elif isinstance(self.param, QgsProcessingParameterVectorLayer): layers = QgsProcessingUtils.compatibleVectorLayers(QgsProject.instance()) elif (isinstance(self.param, QgsProcessingParameterMeshLayer) or (isinstance(self.param, QgsProcessingParameterMultipleLayers) and self.param.layerType() == QgsProcessing.TypeMesh)): layers = QgsProcessingUtils.compatibleMeshLayers(QgsProject.instance()) else: datatypes = [QgsProcessing.TypeVectorAnyGeometry] if isinstance(self.param, QgsProcessingParameterFeatureSource): datatypes = self.param.dataTypes() elif isinstance(self.param, QgsProcessingParameterMultipleLayers): datatypes = [self.param.layerType()] if QgsProcessing.TypeVectorAnyGeometry not in datatypes: layers = QgsProcessingUtils.compatibleVectorLayers(QgsProject.instance(), datatypes) else: layers = QgsProcessingUtils.compatibleVectorLayers(QgsProject.instance()) dlg = MultipleInputDialog([layer.name() for layer in layers]) dlg.exec_() def generate_layer_id(layer): # prefer layer name if unique if len([l for l in layers if l.name().lower() == layer.name().lower()]) == 1: return layer.name() else: # otherwise fall back to layer id return layer.id() if dlg.selectedoptions is not None: selected = dlg.selectedoptions if len(selected) == 1: self.setValue(generate_layer_id(layers[selected[0]])) else: if isinstance(self.param, QgsProcessingParameterMultipleLayers): self.text.setText(';'.join(layers[idx].id() for idx in selected)) else: rowdif = len(selected) - (self._table().rowCount() - self.row) for i in range(rowdif): self._panel().addRow() for i, layeridx in enumerate(selected): self._table().cellWidget(i + self.row, self.col).setValue(generate_layer_id(layers[layeridx])) def showFileSelectionDialog(self): settings = QgsSettings() text = str(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 = str(settings.value('/Processing/LastInputPath')) else: path = '' ret, selected_filter = QFileDialog.getOpenFileNames(self, self.tr('Select Files'), path, getFileFilter(self.param)) if ret: files = list(ret) settings.setValue('/Processing/LastInputPath', os.path.dirname(str(files[0]))) for i, filename in enumerate(files): files[i] = dataobjects.getRasterSublayer(filename, self.param) if len(files) == 1: self.text.setText(files[0]) self.textEditingFinished() else: if isinstance(self.param, QgsProcessingParameterMultipleLayers): self.text.setText(';'.join(str(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).setValue(f) def textEditingFinished(self): self._value = self.text.text() self.valueChanged.emit() def value(self): return self._value if self._value else None def setValue(self, value): self._value = value if isinstance(value, QgsMapLayer): self.text.setText(value.name()) else: # should be basestring self.text.setText(value) self.valueChanged.emit()
def _setupUI(self): self.setSizePolicy( QSizePolicy.Preferred, QSizePolicy.Preferred) self.setMinimumHeight(180) self.main_horizontal_layout = QHBoxLayout(self) italic_font = QFont() italic_font.setItalic(True) # deselected widget self.deselected_widget = QListWidget(self) self._set_list_widget_defaults(self.deselected_widget) deselected_label = QLabel() deselected_label.setText('Deselected') deselected_label.setAlignment(Qt.AlignCenter) deselected_label.setFont(italic_font) deselected_v_layout = QVBoxLayout() deselected_v_layout.addWidget(deselected_label) deselected_v_layout.addWidget(self.deselected_widget) # selected widget self.selected_widget = QListWidget(self) self._set_list_widget_defaults(self.selected_widget) selected_label = QLabel() selected_label.setText('Selected') selected_label.setAlignment(Qt.AlignCenter) selected_label.setFont(italic_font) selected_v_layout = QVBoxLayout() selected_v_layout.addWidget(selected_label) selected_v_layout.addWidget(self.selected_widget) # buttons self.buttons_vertical_layout = QVBoxLayout() self.buttons_vertical_layout.setContentsMargins(0, -1, 0, -1) self.select_all_btn = SmallQPushButton('>>') self.deselect_all_btn = SmallQPushButton('<<') self.select_btn = SmallQPushButton('>') self.deselect_btn = SmallQPushButton('<') self.select_btn.setToolTip('Add the selected items') self.deselect_btn.setToolTip('Remove the selected items') self.select_all_btn.setToolTip('Add all') self.deselect_all_btn.setToolTip('Remove all') # add buttons spacer_label = QLabel() # pragmatic way to create a spacer with # the same height of the labels on top # of the lists, in order to align the # buttons with the lists. self.buttons_vertical_layout.addWidget(spacer_label) self.buttons_vertical_layout.addWidget(self.select_btn) self.buttons_vertical_layout.addWidget(self.deselect_btn) self.buttons_vertical_layout.addWidget(self.select_all_btn) self.buttons_vertical_layout.addWidget(self.deselect_all_btn) # add sub widgets self.main_horizontal_layout.addLayout(deselected_v_layout) self.main_horizontal_layout.addLayout(self.buttons_vertical_layout) self.main_horizontal_layout.addLayout(selected_v_layout)
def initWidgets(self): # If there are advanced parameters — show corresponding groupbox for param in self.alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: self.grpAdvanced.show() break widget_context = QgsProcessingParameterWidgetContext() if iface is not None: widget_context.setMapCanvas(iface.mapCanvas()) # Create widgets and put them in layouts for param in self.alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue if param.isDestination(): continue else: wrapper = WidgetWrapperFactory.create_wrapper(param, self.parent) self.wrappers[param.name()] = wrapper # For compatibility with 3.x API, we need to check whether the wrapper is # the deprecated WidgetWrapper class. If not, it's the newer # QgsAbstractProcessingParameterWidgetWrapper class # TODO QGIS 4.0 - remove is_python_wrapper = issubclass(wrapper.__class__, WidgetWrapper) if not is_python_wrapper: wrapper.setWidgetContext(widget_context) widget = wrapper.createWrappedWidget(self.processing_context) wrapper.registerProcessingContextGenerator(self.context_generator) else: widget = wrapper.widget if self.in_place and param.name() in ('INPUT', 'OUTPUT'): # don't show the input/output parameter widgets in in-place mode # we still need to CREATE them, because other wrappers may need to interact # with them (e.g. those parameters which need the input layer for field # selections/crs properties/etc) continue if widget is not None: if is_python_wrapper: widget.setToolTip(param.toolTip()) if isinstance(param, QgsProcessingParameterFeatureSource): layout = QHBoxLayout() layout.setSpacing(6) layout.setMargin(0) layout.addWidget(widget) button = QToolButton() icon = QIcon(os.path.join(pluginPath, 'images', 'iterate.png')) button.setIcon(icon) button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) button.setToolTip(self.tr('Iterate over this layer, creating a separate output for every feature in the layer')) button.setCheckable(True) layout.addWidget(button) layout.setAlignment(button, Qt.AlignTop) self.iterateButtons[param.name()] = button button.toggled.connect(self.buttonToggled) widget = QWidget() widget.setLayout(layout) label = None if not is_python_wrapper: label = wrapper.createWrappedLabel() else: label = wrapper.label if label is not None: if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: self.layoutAdvanced.addWidget(label) else: self.layoutMain.insertWidget( self.layoutMain.count() - 2, label) elif is_python_wrapper: desc = param.description() if isinstance(param, QgsProcessingParameterExtent): desc += self.tr(' (xmin, xmax, ymin, ymax)') if isinstance(param, QgsProcessingParameterPoint): desc += self.tr(' (x, y)') if param.flags() & QgsProcessingParameterDefinition.FlagOptional: desc += self.tr(' [optional]') widget.setText(desc) if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: self.layoutAdvanced.addWidget(widget) else: self.layoutMain.insertWidget( self.layoutMain.count() - 2, widget) for output in self.alg.destinationParameterDefinitions(): if output.flags() & QgsProcessingParameterDefinition.FlagHidden: continue if self.in_place and param.name() in ('INPUT', 'OUTPUT'): continue label = QLabel(output.description()) widget = DestinationSelectionPanel(output, self.alg) self.layoutMain.insertWidget(self.layoutMain.count() - 1, label) self.layoutMain.insertWidget(self.layoutMain.count() - 1, widget) if isinstance(output, (QgsProcessingParameterRasterDestination, QgsProcessingParameterFeatureSink, QgsProcessingParameterVectorDestination)): check = QCheckBox() check.setText(QCoreApplication.translate('ParametersPanel', 'Open output file after running algorithm')) def skipOutputChanged(checkbox, skipped): checkbox.setEnabled(not skipped) if skipped: checkbox.setChecked(False) check.setChecked(not widget.outputIsSkipped()) check.setEnabled(not widget.outputIsSkipped()) widget.skipOutputChanged.connect(partial(skipOutputChanged, check)) self.layoutMain.insertWidget(self.layoutMain.count() - 1, check) self.checkBoxes[output.name()] = check widget.setToolTip(param.toolTip()) self.outputWidgets[output.name()] = widget for wrapper in list(self.wrappers.values()): wrapper.postInitialize(list(self.wrappers.values()))
def createWidget(self): if self.dialogType == DIALOG_MODELER: self.combo = QComboBox() widget = QWidget() layout = QHBoxLayout() layout.setMargin(0) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(1) layout.addWidget(self.combo) btn = QToolButton() btn.setIcon( QgsApplication.getThemeIcon("mActionSetProjection.svg")) btn.setToolTip(self.tr("Select CRS")) btn.clicked.connect(self.selectProjection) layout.addWidget(btn) widget.setLayout(layout) self.combo.setEditable(True) crss = self.dialog.getAvailableValuesOfType(ParameterCrs) for crs in crss: self.combo.addItem(self.dialog.resolveValueDescription(crs), crs) raster = self.dialog.getAvailableValuesOfType( ParameterRaster, OutputRaster) vector = self.dialog.getAvailableValuesOfType( ParameterVector, OutputVector) for r in raster: self.combo.addItem( "Crs of layer " + self.dialog.resolveValueDescription(r), r) for v in vector: self.combo.addItem( "Crs of layer " + self.dialog.resolveValueDescription(v), v) if not self.param.default: self.combo.setEditText(self.param.default) return widget else: widget = QgsProjectionSelectionWidget() if self.param.optional: widget.setOptionVisible(QgsProjectionSelectionWidget.CrsNotSet, True) if self.param.default: if self.param.default == 'ProjectCrs': crs = QgsProject.instance().crs() else: crs = QgsCoordinateReferenceSystem(self.param.default) widget.setCrs(crs) else: widget.setOptionVisible(QgsProjectionSelectionWidget.CrsNotSet, True) return widget
def initWidgets(self): #tooltips = self.alg.getParameterDescriptions() # If there are advanced parameters — show corresponding groupbox for param in self.alg.parameters: if param.isAdvanced: self.grpAdvanced.show() break # Create widgets and put them in layouts 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)') try: if param.optional: desc += self.tr(' [optional]') except: pass widget = self.getWidgetFromParameter(param) self.valueItems[param.name] = widget if isinstance(param, ParameterVector) and \ not self.alg.allowOnlyOpenedLayers: layout = QHBoxLayout() layout.setSpacing(2) layout.setMargin(0) layout.addWidget(widget) button = QToolButton() icon = QIcon(os.path.join(pluginPath, 'images', 'iterate.png')) button.setIcon(icon) button.setToolTip(self.tr('Iterate over this layer')) button.setCheckable(True) layout.addWidget(button) self.iterateButtons[param.name] = button button.toggled.connect(self.buttonToggled) widget = QWidget() widget.setLayout(layout) #~ if param.name in tooltips.keys(): #~ tooltip = tooltips[param.name] #~ else: #~ tooltip = param.description #~ widget.setToolTip(tooltip) if isinstance(param, ParameterBoolean): widget.setText(desc) if param.isAdvanced: self.layoutAdvanced.addWidget(widget) else: self.layoutMain.insertWidget(self.layoutMain.count() - 2, widget) else: label = QLabel(desc) #label.setToolTip(tooltip) self.labels[param.name] = label if param.isAdvanced: self.layoutAdvanced.addWidget(label) self.layoutAdvanced.addWidget(widget) else: self.layoutMain.insertWidget(self.layoutMain.count() - 2, label) self.layoutMain.insertWidget(self.layoutMain.count() - 2, widget) self.widgets[param.name] = widget for output in self.alg.outputs: if output.hidden: continue label = QLabel(output.description) widget = OutputSelectionPanel(output, self.alg) self.layoutMain.insertWidget(self.layoutMain.count() - 1, label) self.layoutMain.insertWidget(self.layoutMain.count() - 1, widget) if isinstance(output, (OutputRaster, OutputVector, OutputTable)): check = QCheckBox() check.setText( self.tr('Open output file after running algorithm')) check.setChecked(True) self.layoutMain.insertWidget(self.layoutMain.count() - 1, check) self.checkBoxes[output.name] = check self.valueItems[output.name] = widget
def __init__(self, parent, repo, refa, refb): super(DiffViewerDialog, self).__init__(parent, Qt.WindowSystemMenuHint | Qt.WindowTitleHint) self.repo = repo self.setupUi(self) self.setWindowFlags(self.windowFlags() | Qt.WindowSystemMenuHint) self.commit1 = refa self.commit1Panel = RefPanel(self.repo, refa) layout = QHBoxLayout() layout.setSpacing(0) layout.setMargin(0) layout.addWidget(self.commit1Panel) self.commit1Widget.setLayout(layout) self.commit2 = refb self.commit2Panel = RefPanel(self.repo, refb) layout = QHBoxLayout() layout.setSpacing(0) layout.setMargin(0) layout.addWidget(self.commit2Panel) self.commit2Widget.setLayout(layout) self.commit1Panel.refChanged.connect(self.refsHaveChanged) self.commit2Panel.refChanged.connect(self.refsHaveChanged) self.featuresTree.currentItemChanged.connect(self.treeItemChanged) self.featuresTree.header().hide() self.computeDiffs() self.groupBox.adjustSize()
def addAuthWidget(self): layout = QHBoxLayout() layout.setContentsMargins(0, 3, 0, 0) layout.addWidget(self.mapserverAuth) self.mapserverAuthWidget.setLayout(layout) self.mapserverAuthWidget.setFixedHeight(self.txtMapserverUrl.height())
def createWidget(self): if self.dialogType == DIALOG_STANDARD: widget = QWidget() layout = QHBoxLayout() layout.setMargin(0) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(2) self.combo = QgsMapLayerComboBox() layout.addWidget(self.combo) btn = QToolButton() btn.setText('...') btn.setToolTip(self.tr("Select file")) btn.clicked.connect(self.selectFile) layout.addWidget(btn) widget.setLayout(layout) filters = QgsMapLayerProxyModel.Filters() if self.param.datatype == [-1] or -1 in self.param.datatype: filters = QgsMapLayerProxyModel.HasGeometry if QgsWkbTypes.PointGeometry in self.param.datatype: filters |= QgsMapLayerProxyModel.PointLayer if QgsWkbTypes.LineGeometry in self.param.datatype: filters |= QgsMapLayerProxyModel.LineLayer if QgsWkbTypes.PolygonGeometry in self.param.datatype: filters |= QgsMapLayerProxyModel.PolygonLayer if self.param.optional: self.combo.setAllowEmptyLayer(True) if ProcessingConfig.getSetting(ProcessingConfig.SHOW_CRS_DEF): self.combo.setShowCrs(True) self.combo.setFilters(filters) self.combo.setExcludedProviders(['grass']) self.combo.currentIndexChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) self.combo.currentTextChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) return widget elif self.dialogType == DIALOG_BATCH: widget = BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) widget.valueChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) return widget else: self.combo = QComboBox() layers = self.dialog.getAvailableValuesOfType(ParameterVector, OutputVector) self.combo.setEditable(True) for layer in layers: self.combo.addItem(self.dialog.resolveValueDescription(layer), layer) if self.param.optional: self.combo.setEditText("") widget = QWidget() layout = QHBoxLayout() layout.setMargin(0) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(2) layout.addWidget(self.combo) btn = QToolButton() btn.setText('...') btn.setToolTip(self.tr("Select file")) btn.clicked.connect(self.selectFile) layout.addWidget(btn) widget.setLayout(layout) return widget
def setupUi(self): self.labels = {} self.widgets = {} self.checkBoxes = {} self.showAdvanced = False self.wrappers = {} self.valueItems = {} self.dependentItems = {} self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok | QDialogButtonBox.Help) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(5) self.verticalLayout.setMargin(20) self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.verticalLayout.addWidget(self.bar) hLayout = QHBoxLayout() hLayout.setSpacing(5) hLayout.setMargin(0) descriptionLabel = QLabel(self.tr("Description")) self.descriptionBox = QLineEdit() self.descriptionBox.setText(self._alg.displayName()) 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.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: 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.parameterDefinitions(): if param.isDestination() or param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue desc = param.description() if isinstance(param, QgsProcessingParameterExtent): desc += self.tr('(xmin, xmax, ymin, ymax)') if isinstance(param, QgsProcessingParameterPoint): desc += self.tr('(x, y)') if param.flags() & QgsProcessingParameterDefinition.FlagOptional: desc += self.tr(' [optional]') label = QLabel(desc) self.labels[param.name()] = label wrapper = WidgetWrapperFactory.create_wrapper(param, self) self.wrappers[param.name()] = wrapper widget = wrapper.widget if widget is not None: self.valueItems[param.name()] = widget tooltip = param.description() label.setToolTip(tooltip) widget.setToolTip(tooltip) if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: label.setVisible(self.showAdvanced) widget.setVisible(self.showAdvanced) self.widgets[param.name()] = widget self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(widget) for dest in self._alg.destinationParameterDefinitions(): if dest.flags() & QgsProcessingParameterDefinition.FlagHidden: continue if isinstance(dest, (QgsProcessingParameterRasterDestination, QgsProcessingParameterVectorDestination, QgsProcessingParameterFeatureSink, QgsProcessingParameterFileDestination, QgsProcessingParameterFolderDestination)): label = QLabel(dest.description()) item = QgsFilterLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(item) self.valueItems[dest.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.setPreviousValues() self.setWindowTitle(self._alg.displayName()) self.verticalLayout2 = QVBoxLayout() self.verticalLayout2.setSpacing(2) self.verticalLayout2.setMargin(0) self.paramPanel = QWidget() self.paramPanel.setLayout(self.verticalLayout) self.scrollArea = QgsScrollArea() self.scrollArea.setWidget(self.paramPanel) self.scrollArea.setWidgetResizable(True) self.verticalLayout2.addWidget(self.scrollArea) self.verticalLayout2.addWidget(self.buttonBox) self.setLayout(self.verticalLayout2) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) self.buttonBox.helpRequested.connect(self.openHelp) QMetaObject.connectSlotsByName(self) for wrapper in list(self.wrappers.values()): wrapper.postInitialize(list(self.wrappers.values()))
def addAuthWidgets(self): self.geoserverAuth = QgsAuthConfigSelect() self.geoserverAuth.selectedConfigIdChanged.connect( self._setCurrentServerHasChanges) layout = QHBoxLayout() layout.setMargin(0) layout.addWidget(self.geoserverAuth) self.geoserverAuthWidget.setLayout(layout) self.geoserverAuthWidget.setFixedHeight(self.txtGeoserverUrl.height()) self.mapserverAuth = QgsAuthConfigSelect() self.mapserverAuth.selectedConfigIdChanged.connect( self._setCurrentServerHasChanges) layout = QHBoxLayout() layout.setMargin(0) layout.addWidget(self.mapserverAuth) self.mapserverAuthWidget.setLayout(layout) self.mapserverAuthWidget.setFixedHeight(self.txtGeoserverUrl.height()) self.postgisAuth = QgsAuthConfigSelect() self.postgisAuth.selectedConfigIdChanged.connect( self._setCurrentServerHasChanges) layout = QHBoxLayout() layout.setMargin(0) layout.addWidget(self.postgisAuth) self.postgisAuthWidget.setLayout(layout) self.postgisAuthWidget.setFixedHeight(self.txtGeoserverUrl.height()) self.cswAuth = QgsAuthConfigSelect() self.cswAuth.selectedConfigIdChanged.connect( self._setCurrentServerHasChanges) layout = QHBoxLayout() layout.setMargin(0) layout.addWidget(self.cswAuth) self.cswAuthWidget.setLayout(layout) self.cswAuthWidget.setFixedHeight(self.txtGeoserverUrl.height()) self.geocatLiveGeoserverAuth = QgsAuthConfigSelect() self.geocatLiveGeoserverAuth.selectedConfigIdChanged.connect( self._setCurrentServerHasChanges) layout = QHBoxLayout() layout.setMargin(0) layout.addWidget(self.geocatLiveGeoserverAuth) self.geocatLiveGeoserverAuthWidget.setLayout(layout) self.geocatLiveGeoserverAuthWidget.setFixedHeight( self.txtGeoserverUrl.height()) self.geocatLiveGeonetworkAuth = QgsAuthConfigSelect() self.geocatLiveGeonetworkAuth.selectedConfigIdChanged.connect( self._setCurrentServerHasChanges) layout = QHBoxLayout() layout.setMargin(0) layout.addWidget(self.geocatLiveGeonetworkAuth) self.geocatLiveGeonetworkAuthWidget.setLayout(layout) self.geocatLiveGeonetworkAuthWidget.setFixedHeight( self.txtGeoserverUrl.height())
class BatchInputSelectionPanel(QWidget): valueChanged = pyqtSignal() def __init__(self, param, row, col, dialog): super(BatchInputSelectionPanel, self).__init__(None) self.param = param self.dialog = dialog self.row = row self.col = col self.horizontalLayout = QHBoxLayout(self) self.horizontalLayout.setSpacing(0) self.horizontalLayout.setMargin(0) self.text = QLineEdit() self.text.setObjectName('text') self.text.setMinimumWidth(300) self.setValue('') self.text.editingFinished.connect(self.textEditingFinished) 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 _panel(self): return self.dialog.mainWidget def _table(self): return self._panel().tblParameters def showPopupMenu(self): popupmenu = QMenu() if not (isinstance(self.param, ParameterMultipleInput) and self.param.datatype == dataobjects.TYPE_FILE): selectLayerAction = QAction( self.tr('Select from open layers'), self.pushButton) selectLayerAction.triggered.connect(self.showLayerSelectionDialog) popupmenu.addAction(selectLayerAction) selectFileAction = QAction( self.tr('Select from filesystem'), self.pushButton) selectFileAction.triggered.connect(self.showFileSelectionDialog) popupmenu.addAction(selectFileAction) popupmenu.exec_(QCursor.pos()) def showLayerSelectionDialog(self): if (isinstance(self.param, ParameterRaster) or (isinstance(self.param, ParameterMultipleInput) and self.param.datatype == dataobjects.TYPE_RASTER)): layers = dataobjects.getRasterLayers() elif isinstance(self.param, ParameterTable): layers = dataobjects.getTables() else: if isinstance(self.param, ParameterVector): datatype = self.param.datatype else: datatype = [self.param.datatype] layers = dataobjects.getVectorLayers(datatype) dlg = MultipleInputDialog([layer.name() for layer in layers]) dlg.exec_() if dlg.selectedoptions is not None: selected = dlg.selectedoptions if len(selected) == 1: self.setValue(layers[selected[0]]) else: if isinstance(self.param, ParameterMultipleInput): self.text.setText(';'.join(layers[idx].name() for idx in selected)) else: rowdif = len(selected) - (self._table().rowCount() - self.row) for i in range(rowdif): self._panel().addRow() for i, layeridx in enumerate(selected): self._table().cellWidget(i + self.row, self.col).setValue(layers[layeridx]) def showFileSelectionDialog(self): settings = QSettings() text = str(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 = str(settings.value('/Processing/LastInputPath')) else: path = '' ret, selected_filter = 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(str(files[0]))) for i, filename in enumerate(files): files[i] = dataobjects.getRasterSublayer(filename, self.param) if len(files) == 1: self.text.setText(files[0]) self.textEditingFinished() else: if isinstance(self.param, ParameterMultipleInput): self.text.setText(';'.join(str(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).setValue(f) def textEditingFinished(self): self._value = self.text.text() self.valueChanged.emit() def value(self): return self._value def setValue(self, value): self._value = value if isinstance(value, QgsMapLayer): self.text.setText(value.name()) else: # should be basestring self.text.setText(value) self.valueChanged.emit()
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, QgsProcessingParameterFolderDestination): self.selectDirectory() return filefilter = getFileFilter(self.output) settings = QgsSettings() if settings.contains('/Processing/LastBatchOutputPath'): path = str(settings.value('/Processing/LastBatchOutputPath')) else: path = '' filename, selectedFileFilter = QFileDialog.getSaveFileName( self, self.tr('Save File'), path, filefilter) 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('.')] \ + str(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_index) param = self.alg.parameterDefinitions()[ dlg.param_index] if isinstance( param, (QgsProcessingParameterRasterLayer, QgsProcessingParameterFeatureSource, QgsProcessingParameterVectorLayer, QgsProcessingParameterMultipleLayers)): v = widget.value() if isinstance(v, QgsMapLayer): s = v.name() else: s = os.path.basename(v) s = os.path.splitext(s)[0] elif isinstance(param, QgsProcessingParameterBoolean): s = str(widget.currentIndex() == 0) elif isinstance(param, QgsProcessingParameterEnum): s = str(widget.currentText()) elif isinstance(param, QgsProcessingParameterMatrix): s = str(widget.table) else: s = str(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 = QgsSettings() if settings.contains('/Processing/LastBatchOutputPath'): lastDir = str(settings.value('/Processing/LastBatchOutputPath')) else: lastDir = '' dirName = QFileDialog.getExistingDirectory(self, self.tr('Output 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 str(self.text.text())
def initWidgets(self): # If there are advanced parameters — show corresponding groupbox for param in self.alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: self.grpAdvanced.show() break # Create widgets and put them in layouts for param in self.alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue if param.isDestination(): continue else: desc = param.description() if isinstance(param, QgsProcessingParameterExtent): desc += self.tr(' (xmin, xmax, ymin, ymax)') if isinstance(param, QgsProcessingParameterPoint): desc += self.tr(' (x, y)') if param.flags( ) & QgsProcessingParameterDefinition.FlagOptional: desc += self.tr(' [optional]') wrapper = WidgetWrapperFactory.create_wrapper( param, self.parent) self.wrappers[param.name()] = wrapper widget = wrapper.widget if widget is not None: if isinstance(param, QgsProcessingParameterFeatureSource): layout = QHBoxLayout() layout.setSpacing(6) layout.setMargin(0) layout.addWidget(widget) button = QToolButton() icon = QIcon( os.path.join(pluginPath, 'images', 'iterate.png')) button.setIcon(icon) button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) button.setToolTip( self. tr('Iterate over this layer, creating a separate output for every feature in the layer' )) button.setCheckable(True) layout.addWidget(button) layout.setAlignment(button, Qt.AlignTop) self.iterateButtons[param.name()] = button button.toggled.connect(self.buttonToggled) widget = QWidget() widget.setLayout(layout) widget.setToolTip(param.toolTip()) if isinstance(widget, QCheckBox): # checkbox widget - so description is embedded in widget rather than a separate # label widget.setText(desc) else: label = QLabel(desc) # label.setToolTip(tooltip) self.labels[param.name()] = label if param.flags( ) & QgsProcessingParameterDefinition.FlagAdvanced: self.layoutAdvanced.addWidget(label) else: self.layoutMain.insertWidget( self.layoutMain.count() - 2, label) if param.flags( ) & QgsProcessingParameterDefinition.FlagAdvanced: self.layoutAdvanced.addWidget(widget) else: self.layoutMain.insertWidget( self.layoutMain.count() - 2, widget) for output in self.alg.destinationParameterDefinitions(): if output.flags() & QgsProcessingParameterDefinition.FlagHidden: continue label = QLabel(output.description()) widget = DestinationSelectionPanel(output, self.alg) self.layoutMain.insertWidget(self.layoutMain.count() - 1, label) self.layoutMain.insertWidget(self.layoutMain.count() - 1, widget) if isinstance(output, (QgsProcessingParameterRasterDestination, QgsProcessingParameterFeatureSink, QgsProcessingParameterVectorDestination)): check = QCheckBox() check.setText( self.tr('Open output file after running algorithm')) check.setChecked(True) self.layoutMain.insertWidget(self.layoutMain.count() - 1, check) self.checkBoxes[output.name()] = check widget.setToolTip(param.toolTip()) self.outputWidgets[output.name()] = widget for wrapper in list(self.wrappers.values()): wrapper.postInitialize(list(self.wrappers.values()))
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_TABLE_MULTIPLE_FIELD = 'Table multiple 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_TABLE_MULTIPLE_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.horizontalLayoutName = QHBoxLayout(self) self.horizontalLayoutName.setSpacing(2) self.horizontalLayoutName.setMargin(0) self.label = QLabel(self.tr('Parameter name')) self.horizontalLayoutName.addWidget(self.label) self.nameTextBox = QLineEdit() self.horizontalLayoutName.addWidget(self.nameTextBox) self.verticalLayout.addLayout(self.horizontalLayoutName) self.horizontalLayoutRequired = QHBoxLayout(self) self.horizontalLayoutRequired.setSpacing(2) self.horizontalLayoutRequired.setMargin(0) self.horizontalLayoutParent = QHBoxLayout(self) self.horizontalLayoutParent.setSpacing(2) self.horizontalLayoutParent.setMargin(0) self.horizontalLayoutDefault = QHBoxLayout(self) self.horizontalLayoutDefault.setSpacing(2) self.horizontalLayoutDefault.setMargin(0) self.horizontalLayoutDatatype = QHBoxLayout(self) self.horizontalLayoutDatatype.setSpacing(2) self.horizontalLayoutDatatype.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.horizontalLayoutParent.addWidget(self.state) self.verticalLayout.addLayout(self.horizontalLayoutParent) elif self.paramType in ( ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD, ModelerParameterDefinitionDialog.PARAMETER_TABLE_MULTIPLE_FIELD)\ or isinstance(self.param, (ParameterTableField, ParameterTableMultipleField)): self.horizontalLayoutParent.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.horizontalLayoutParent.addWidget(self.parentCombo) self.verticalLayout.addLayout(self.horizontalLayoutParent) # add the datatype selector self.horizontalLayoutDatatype.addWidget(QLabel(self.tr('Allowed ' 'data type'))) self.datatypeCombo = QComboBox() self.datatypeCombo.addItem(self.tr('Any'), -1) self.datatypeCombo.addItem(self.tr('Number'), 0) self.datatypeCombo.addItem(self.tr('String'), 1) self.horizontalLayoutDatatype.addWidget(self.datatypeCombo) if self.param is not None and self.param.datatype is not None: # QComboBoxes indexes start at 0, # self.param.datatype start with -1 that is why I need to do +1 datatype_index = self.param.datatype + 1 self.datatypeCombo.setCurrentIndex(datatype_index) self.verticalLayout.addLayout(self.horizontalLayoutDatatype) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_VECTOR or \ isinstance(self.param, ParameterVector): self.horizontalLayoutParent.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.horizontalLayoutParent.addWidget(self.shapetypeCombo) self.verticalLayout.addLayout(self.horizontalLayoutParent) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or \ isinstance(self.param, ParameterMultipleInput): self.horizontalLayoutParent.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.horizontalLayoutParent.addWidget(self.datatypeCombo) self.verticalLayout.addLayout(self.horizontalLayoutParent) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or \ isinstance(self.param, ParameterNumber): self.horizontalLayoutParent.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.horizontalLayoutParent.addWidget(self.minTextBox) self.horizontalLayoutParent.addWidget(self.maxTextBox) self.verticalLayout.addLayout(self.horizontalLayoutParent) self.horizontalLayoutDefault.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.horizontalLayoutDefault.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayoutDefault) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or \ isinstance(self.param, ParameterString): self.horizontalLayoutParent.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() if self.param is not None: self.defaultTextBox.setText(self.param.default) self.horizontalLayoutParent.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayoutParent) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or \ isinstance(self.param, ParameterFile): self.horizontalLayoutParent.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.horizontalLayoutParent.addWidget(self.fileFolderCombo) self.verticalLayout.addLayout(self.horizontalLayoutParent) elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_POINT or \ isinstance(self.param, ParameterPoint): self.horizontalLayoutParent.addWidget(QLabel(self.tr('Default value'))) self.defaultTextBox = QLineEdit() if self.param is not None: self.defaultTextBox.setText(self.param.default) self.horizontalLayoutParent.addWidget(self.defaultTextBox) self.verticalLayout.addLayout(self.horizontalLayoutParent) self.horizontalLayoutRequired.addWidget(QLabel(self.tr('Required'))) self.yesNoCombo = QComboBox() self.yesNoCombo.addItem(self.tr('Yes')) self.yesNoCombo.addItem(self.tr('No')) self.horizontalLayoutRequired.addWidget(self.yesNoCombo) if self.param is not None: self.yesNoCombo.setCurrentIndex( 1 if self.param.optional else 0) self.verticalLayout.addLayout(self.horizontalLayoutRequired) 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 in ( ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD, ModelerParameterDefinitionDialog.PARAMETER_TABLE_MULTIPLE_FIELD)\ or isinstance(self.param, (ParameterTableField, ParameterTableMultipleField)): 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()) datatype = self.datatypeCombo.itemData( self.datatypeCombo.currentIndex()) if (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or isinstance(self.param, ParameterTableField)): self.param = ParameterTableField( name, description, parent, datatype) else: self.param = ParameterTableMultipleField( name, description, parent, datatype) 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()
def setupUi(self): self.checkBoxes = {} self.showAdvanced = False self.wrappers = {} self.valueItems = {} self.dependentItems = {} self.algorithmItem = None self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok | QDialogButtonBox.Help) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(5) self.verticalLayout.setMargin(20) self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.verticalLayout.addWidget(self.bar) hLayout = QHBoxLayout() hLayout.setSpacing(5) hLayout.setMargin(0) descriptionLabel = QLabel(self.tr("Description")) self.descriptionBox = QLineEdit() self.descriptionBox.setText(self._alg.displayName()) 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) widget_context = QgsProcessingParameterWidgetContext() widget_context.setProject(QgsProject.instance()) if iface is not None: widget_context.setMapCanvas(iface.mapCanvas()) widget_context.setModel(self.model) widget_context.setModelChildAlgorithmId(self.childId) self.algorithmItem = QgsGui.instance().processingGuiRegistry().algorithmConfigurationWidget(self._alg) if self.algorithmItem: self.algorithmItem.setWidgetContext(widget_context) self.algorithmItem.registerProcessingContextGenerator(self.context_generator) if self.configuration: self.algorithmItem.setConfiguration(self.configuration) self.verticalLayout.addWidget(self.algorithmItem) for param in self._alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: 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.parameterDefinitions(): if param.isDestination() or param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue wrapper = WidgetWrapperFactory.create_wrapper(param, self) self.wrappers[param.name()] = wrapper wrapper.setWidgetContext(widget_context) wrapper.registerProcessingContextGenerator(self.context_generator) if issubclass(wrapper.__class__, QgsProcessingModelerParameterWidget): widget = wrapper else: widget = wrapper.widget if widget is not None: self.valueItems[param.name()] = widget if issubclass(wrapper.__class__, QgsProcessingModelerParameterWidget): label = wrapper.createLabel() else: tooltip = param.description() widget.setToolTip(tooltip) label = wrapper.label self.widget_labels[param.name()] = label if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: label.setVisible(self.showAdvanced) widget.setVisible(self.showAdvanced) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(widget) for dest in self._alg.destinationParameterDefinitions(): if dest.flags() & QgsProcessingParameterDefinition.FlagHidden: continue if isinstance(dest, (QgsProcessingParameterRasterDestination, QgsProcessingParameterVectorDestination, QgsProcessingParameterFeatureSink, QgsProcessingParameterFileDestination, QgsProcessingParameterFolderDestination)): label = QLabel(dest.description()) item = QgsFilterLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(self.tr('[Enter name if this is a final result]')) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(item) self.valueItems[dest.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.setPreviousValues() self.setWindowTitle(self._alg.displayName()) self.verticalLayout2 = QVBoxLayout() self.verticalLayout2.setSpacing(2) self.verticalLayout2.setMargin(0) self.paramPanel = QWidget() self.paramPanel.setLayout(self.verticalLayout) self.scrollArea = QgsScrollArea() self.scrollArea.setWidget(self.paramPanel) self.scrollArea.setWidgetResizable(True) self.verticalLayout2.addWidget(self.scrollArea) self.verticalLayout2.addWidget(self.buttonBox) self.setLayout(self.verticalLayout2) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) self.buttonBox.helpRequested.connect(self.openHelp) QMetaObject.connectSlotsByName(self)
def setupUi(self): self.checkBoxes = {} self.showAdvanced = False self.wrappers = {} self.valueItems = {} self.dependentItems = {} self.algorithmItem = None self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok | QDialogButtonBox.Help) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(5) self.verticalLayout.setMargin(20) self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.verticalLayout.addWidget(self.bar) hLayout = QHBoxLayout() hLayout.setSpacing(5) hLayout.setMargin(0) descriptionLabel = QLabel(self.tr("Description")) self.descriptionBox = QLineEdit() self.descriptionBox.setText(self._alg.displayName()) 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) self.algorithmItem = QgsGui.instance().processingGuiRegistry( ).algorithmConfigurationWidget(self._alg) if self.configuration: self.algorithmItem.setConfiguration(self.configuration) self.verticalLayout.addWidget(self.algorithmItem) widget_context = QgsProcessingParameterWidgetContext() if iface is not None: widget_context.setMapCanvas(iface.mapCanvas()) widget_context.setModel(self.model) widget_context.setModelChildAlgorithmId(self.childId) for param in self._alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: 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.parameterDefinitions(): if param.isDestination( ) or param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue wrapper = WidgetWrapperFactory.create_wrapper(param, self) self.wrappers[param.name()] = wrapper if issubclass(wrapper.__class__, QgsProcessingModelerParameterWidget): wrapper.setWidgetContext(widget_context) wrapper.registerProcessingContextGenerator( self.context_generator) widget = wrapper else: widget = wrapper.widget if widget is not None: self.valueItems[param.name()] = widget if issubclass(wrapper.__class__, QgsProcessingModelerParameterWidget): label = wrapper.createLabel() else: tooltip = param.description() widget.setToolTip(tooltip) label = wrapper.label self.widget_labels[param.name()] = label if param.flags( ) & QgsProcessingParameterDefinition.FlagAdvanced: label.setVisible(self.showAdvanced) widget.setVisible(self.showAdvanced) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(widget) for dest in self._alg.destinationParameterDefinitions(): if dest.flags() & QgsProcessingParameterDefinition.FlagHidden: continue if isinstance(dest, (QgsProcessingParameterRasterDestination, QgsProcessingParameterVectorDestination, QgsProcessingParameterFeatureSink, QgsProcessingParameterFileDestination, QgsProcessingParameterFolderDestination)): label = QLabel(dest.description()) item = QgsFilterLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText( self.tr('[Enter name if this is a final result]')) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(item) self.valueItems[dest.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.setPreviousValues() self.setWindowTitle(self._alg.displayName()) self.verticalLayout2 = QVBoxLayout() self.verticalLayout2.setSpacing(2) self.verticalLayout2.setMargin(0) self.paramPanel = QWidget() self.paramPanel.setLayout(self.verticalLayout) self.scrollArea = QgsScrollArea() self.scrollArea.setWidget(self.paramPanel) self.scrollArea.setWidgetResizable(True) self.verticalLayout2.addWidget(self.scrollArea) self.verticalLayout2.addWidget(self.buttonBox) self.setLayout(self.verticalLayout2) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) self.buttonBox.helpRequested.connect(self.openHelp) QMetaObject.connectSlotsByName(self)
def treeItemChanged(self, current, previous): qgsgeom1 = None qgsgeom2 = None crs = "EPSG:4326" if not isinstance(current, FeatureItem): self.attributesTable.clear() self.attributesTable.setRowCount(0) return color = {"MODIFIED": QColor(255, 170, 0), "ADDED":Qt.green, "REMOVED":Qt.red , "NO_CHANGE":Qt.white} path = current.layername + "/" + current.featureid featurediff = self.changes[path].featurediff() self.attributesTable.clear() self.attributesTable.verticalHeader().show() self.attributesTable.horizontalHeader().show() self.attributesTable.setRowCount(len(featurediff)) self.attributesTable.setVerticalHeaderLabels([a["attributename"] for a in featurediff]) self.attributesTable.setHorizontalHeaderLabels(["Old value", "New value", "Change type"]) for i, attrib in enumerate(featurediff): try: if attrib["changetype"] == "MODIFIED": oldvalue = attrib["oldvalue"] newvalue = attrib["newvalue"] elif attrib["changetype"] == "ADDED": newvalue = attrib["newvalue"] oldvalue = "" elif attrib["changetype"] == "REMOVED": oldvalue = attrib["oldvalue"] newvalue = "" else: oldvalue = newvalue = attrib["oldvalue"] except: oldvalue = newvalue = "" self.attributesTable.setItem(i, 0, DiffItem(oldvalue)) self.attributesTable.setItem(i, 1, DiffItem(newvalue)) try: self.attributesTable.setItem(i, 2, QTableWidgetItem("")) if qgsgeom1 is None or qgsgeom2 is None: if "crs" in attrib: crs = attrib["crs"] qgsgeom1 = QgsGeometry.fromWkt(oldvalue) qgsgeom2 = QgsGeometry.fromWkt(newvalue) if qgsgeom1 is not None and qgsgeom2 is not None: widget = QWidget() btn = QPushButton() btn.setText("View detail") btn.clicked.connect(lambda: self.viewGeometryChanges(qgsgeom1, qgsgeom2, crs)) label = QLabel() label.setText(attrib["changetype"]) layout = QHBoxLayout(widget) layout.addWidget(label); layout.addWidget(btn); layout.setContentsMargins(0, 0, 0, 0) widget.setLayout(layout) self.attributesTable.setCellWidget(i, 2, widget) else: self.attributesTable.setItem(i, 2, QTableWidgetItem(attrib["changetype"])) else: self.attributesTable.setItem(i, 2, QTableWidgetItem(attrib["changetype"])) except: self.attributesTable.setItem(i, 2, QTableWidgetItem(attrib["changetype"])) for col in range(3): self.attributesTable.item(i, col).setBackgroundColor(color[attrib["changetype"]]); self.attributesTable.resizeColumnsToContents() self.attributesTable.horizontalHeader().setResizeMode(QHeaderView.Stretch)
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 == dataobjects.TYPE_FILE): selectLayerAction = QAction( self.tr('Select from open layers'), self.pushButton) selectLayerAction.triggered.connect(self.showLayerSelectionDialog) popupmenu.addAction(selectLayerAction) selectFileAction = QAction( self.tr('Select from filesystem'), self.pushButton) selectFileAction.triggered.connect(self.showFileSelectionDialog) popupmenu.addAction(selectFileAction) popupmenu.exec_(QCursor.pos()) def showLayerSelectionDialog(self): if (isinstance(self.param, ParameterRaster) or (isinstance(self.param, ParameterMultipleInput) and self.param.datatype == dataobjects.TYPE_RASTER)): layers = dataobjects.getRasterLayers() elif isinstance(self.param, ParameterTable): layers = dataobjects.getTables() else: if isinstance(self.param, ParameterVector): datatype = self.param.datatype else: datatype = [self.param.datatype] layers = dataobjects.getVectorLayers(datatype) dlg = MultipleInputDialog([layer.name() for layer in layers]) dlg.exec_() if dlg.selectedoptions is not None: selected = dlg.selectedoptions if len(selected) == 1: self.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, selected_filter = 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 createWidget(self): if self.dialogType == DIALOG_MODELER: self.combo = QComboBox() widget = QWidget() layout = QHBoxLayout() layout.setMargin(0) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(1) layout.addWidget(self.combo) btn = QToolButton() btn.setIcon(QgsApplication.getThemeIcon("mActionSetProjection.svg")) btn.setToolTip(self.tr("Select CRS")) btn.clicked.connect(self.selectProjection) layout.addWidget(btn) widget.setLayout(layout) self.combo.setEditable(True) crss = self.dialog.getAvailableValuesOfType(ParameterCrs) for crs in crss: self.combo.addItem(self.dialog.resolveValueDescription(crs), crs) raster = self.dialog.getAvailableValuesOfType(ParameterRaster, OutputRaster) vector = self.dialog.getAvailableValuesOfType(ParameterVector, OutputVector) for r in raster: self.combo.addItem("Crs of layer " + self.dialog.resolveValueDescription(r), r) for v in vector: self.combo.addItem("Crs of layer " + self.dialog.resolveValueDescription(v), v) if not self.param.default: self.combo.setEditText(self.param.default) return widget else: widget = QgsProjectionSelectionWidget() if self.param.optional: widget.setOptionVisible(QgsProjectionSelectionWidget.CrsNotSet, True) if self.param.default: crs = QgsCoordinateReferenceSystem(self.param.default) widget.setCrs(crs) return widget
def createWidget(self): if self.dialogType == DIALOG_STANDARD: widget = QWidget() layout = QHBoxLayout() layout.setMargin(0) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(2) self.combo = QgsMapLayerComboBox() layout.addWidget(self.combo) btn = QToolButton() btn.setText('...') btn.setToolTip(self.tr("Select file")) btn.clicked.connect(self.selectFile) layout.addWidget(btn) widget.setLayout(layout) if self.param.optional: self.combo.setAllowEmptyLayer(True) self.combo.setFilters(QgsMapLayerProxyModel.VectorLayer) self.combo.setExcludedProviders(['grass']) self.combo.currentIndexChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) self.combo.currentTextChanged.connect(lambda: self.widgetValueHasChanged.emit(self)) return widget elif self.dialogType == DIALOG_BATCH: return BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) else: self.combo = QComboBox() layers = self.dialog.getAvailableValuesOfType(ParameterRaster, OutputRaster) self.combo.setEditable(True) tables = self.dialog.getAvailableValuesOfType(ParameterTable, OutputTable) layers = self.dialog.getAvailableValuesOfType(ParameterVector, OutputVector) if self.param.optional: self.combo.addItem(self.NOT_SELECTED, None) for table in tables: self.combo.addItem(self.dialog.resolveValueDescription(table), table) for layer in layers: self.combo.addItem(self.dialog.resolveValueDescription(layer), layer) widget = QWidget() layout = QHBoxLayout() layout.setMargin(0) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(2) layout.addWidget(self.combo) btn = QToolButton() btn.setText('...') btn.setToolTip(self.tr("Select file")) btn.clicked.connect(self.selectFile) layout.addWidget(btn) widget.setLayout(layout) return widget