class LessonFinishedDialog(QDialog): def __init__(self, lesson): super(LessonFinishedDialog, self).__init__(iface.mainWindow()) self.reopen = False self.lesson = lesson self.setWindowTitle("Lesson finished") self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(10) self.verticalLayout.setMargin(10) txt = "<p>Congratulations! You have correctly finished this lesson.</p>" if lesson.nextLessons: txt += "<p>We recommend you the following lessons to continue:</p><ul>" for i, nextLesson in enumerate(lesson.nextLessons): txt+="<li><a href='%i'>%s</a>" % (i, nextLesson[1]) txt += "</ul><p>If you don't want to run more lessons, just <a href='exit'>close this dialog.</a></p>" txt += "<p>If you want to run another lesson, click <a href='reopen'>here</a> to reopen the lesson selector</p>" self.text = QTextBrowser() self.text.anchorClicked.connect(self.linkClicked) self.text.setHtml(txt) self.text.setOpenLinks(False) self.verticalLayout.addWidget(self.text) self.setLayout(self.verticalLayout) self.resize(400, 300) self.nextLesson = None def linkClicked(self, url): if url.path() not in ["exit", "reopen"]: self.nextLesson = lessonFromName(*self.lesson.nextLessons[int(url.path())]) if url.path() =="reopen": self.reopen = True self.close()
class QMatplotlibWidget(QWidget): def __init__(self, parent=None): QWidget.__init__(self, parent) self.canvas = QMatplotlibCanvas() self.ax = self.canvas.ax self.figure = self.canvas.figure self.toolBar = NavigationToolbar2QT(self.canvas, self) bgColor = self.palette().color(QPalette.Background).name() self.figure.set_facecolor(bgColor) self.layout = QVBoxLayout() self.layout.setSpacing(2) self.layout.setMargin(0) self.layout.addWidget(self.toolBar) self.layout.addWidget(self.canvas) self.setLayout(self.layout) self._setupToolbar() def _setupToolbar(self): self.actionToggleGrid = QAction(self.tr('Toggle grid'), self.toolBar) self.actionToggleGrid.setIcon( QIcon(os.path.join(pluginPath, 'icons', 'toggleGrid.svg'))) self.actionToggleGrid.setCheckable(True) self.actionToggleGrid.triggered.connect(self.toggleGrid) self.toolBar.insertAction(self.toolBar.actions()[7], self.actionToggleGrid) self.toolBar.insertSeparator(self.toolBar.actions()[8]) def toggleGrid(self): self.ax.grid() self.canvas.draw() def alignLabels(self): self.figure.autofmt_xdate() def clear(self): self.ax.clear() self.canvas.draw() def setTitle(self, text): self.ax.set_title(text) def setXAxisCaption(self, text): self.ax.set_xlabel(text) def setYAxisCaption(self, text): self.ax.set_ylabel(text)
def __init__(self, parent, alg): ParametersPanel.__init__(self, parent, alg) w = QWidget() layout = QVBoxLayout() layout.setMargin(0) layout.setSpacing(6) label = QLabel() label.setText(self.tr("GDAL/OGR console call")) layout.addWidget(label) self.text = QPlainTextEdit() self.text.setReadOnly(True) layout.addWidget(self.text) w.setLayout(layout) self.layoutMain.addWidget(w) self.connectParameterSignals() self.parametersHaveChanged()
class MultilineTextPanel(QWidget): USE_TEXT = 0 def __init__(self, options, parent=None): super(MultilineTextPanel, self).__init__(parent) self.options = options self.verticalLayout = QVBoxLayout(self) self.verticalLayout.setSpacing(2) self.verticalLayout.setMargin(0) self.combo = QComboBox() self.combo.addItem(self.tr('[Use text below]')) for option in options: self.combo.addItem(option[0], option[1]) self.combo.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.verticalLayout.addWidget(self.combo) self.textBox = QPlainTextEdit() self.verticalLayout.addWidget(self.textBox) self.setLayout(self.verticalLayout) def setText(self, text): self.textBox.setPlainText(text) def getOption(self): return self.combo.currentIndex() def getValue(self): if self.combo.currentIndex() == 0: return str(self.textBox.toPlainText()) else: return self.combo.currentData() def setValue(self, value): items = [self.combo.itemData(i) for i in range(1, self.combo.count())] for idx, item in enumerate(items): if item == value: self.combo.setCurrentIndex(idx) return self.combo.setCurrentIndex(0) if value: self.textBox.setPlainText(value)
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)
class ModelerDialog(BASE, WIDGET): ALG_ITEM = 'ALG_ITEM' PROVIDER_ITEM = 'PROVIDER_ITEM' GROUP_ITEM = 'GROUP_ITEM' NAME_ROLE = Qt.UserRole TAG_ROLE = Qt.UserRole + 1 TYPE_ROLE = Qt.UserRole + 2 CANVAS_SIZE = 4000 update_model = pyqtSignal() def __init__(self, model=None): super().__init__(None) self.setAttribute(Qt.WA_DeleteOnClose) self.setupUi(self) # LOTS of bug reports when we include the dock creation in the UI file # see e.g. #16428, #19068 # So just roll it all by hand......! self.propertiesDock = QgsDockWidget(self) self.propertiesDock.setFeatures( QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) self.propertiesDock.setObjectName("propertiesDock") propertiesDockContents = QWidget() self.verticalDockLayout_1 = QVBoxLayout(propertiesDockContents) self.verticalDockLayout_1.setContentsMargins(0, 0, 0, 0) self.verticalDockLayout_1.setSpacing(0) self.scrollArea_1 = QgsScrollArea(propertiesDockContents) sizePolicy = QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.scrollArea_1.sizePolicy().hasHeightForWidth()) self.scrollArea_1.setSizePolicy(sizePolicy) self.scrollArea_1.setFocusPolicy(Qt.WheelFocus) self.scrollArea_1.setFrameShape(QFrame.NoFrame) self.scrollArea_1.setFrameShadow(QFrame.Plain) self.scrollArea_1.setWidgetResizable(True) self.scrollAreaWidgetContents_1 = QWidget() self.gridLayout = QGridLayout(self.scrollAreaWidgetContents_1) self.gridLayout.setContentsMargins(6, 6, 6, 6) self.gridLayout.setSpacing(4) self.label_1 = QLabel(self.scrollAreaWidgetContents_1) self.gridLayout.addWidget(self.label_1, 0, 0, 1, 1) self.textName = QLineEdit(self.scrollAreaWidgetContents_1) self.gridLayout.addWidget(self.textName, 0, 1, 1, 1) self.label_2 = QLabel(self.scrollAreaWidgetContents_1) self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1) self.textGroup = QLineEdit(self.scrollAreaWidgetContents_1) self.gridLayout.addWidget(self.textGroup, 1, 1, 1, 1) self.label_1.setText(self.tr("Name")) self.textName.setToolTip(self.tr("Enter model name here")) self.label_2.setText(self.tr("Group")) self.textGroup.setToolTip(self.tr("Enter group name here")) self.scrollArea_1.setWidget(self.scrollAreaWidgetContents_1) self.verticalDockLayout_1.addWidget(self.scrollArea_1) self.propertiesDock.setWidget(propertiesDockContents) self.addDockWidget(Qt.DockWidgetArea(1), self.propertiesDock) self.propertiesDock.setWindowTitle(self.tr("Model properties")) self.inputsDock = QgsDockWidget(self) self.inputsDock.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) self.inputsDock.setObjectName("inputsDock") self.inputsDockContents = QWidget() self.verticalLayout_3 = QVBoxLayout(self.inputsDockContents) self.verticalLayout_3.setContentsMargins(0, 0, 0, 0) self.scrollArea_2 = QgsScrollArea(self.inputsDockContents) sizePolicy.setHeightForWidth(self.scrollArea_2.sizePolicy().hasHeightForWidth()) self.scrollArea_2.setSizePolicy(sizePolicy) self.scrollArea_2.setFocusPolicy(Qt.WheelFocus) self.scrollArea_2.setFrameShape(QFrame.NoFrame) self.scrollArea_2.setFrameShadow(QFrame.Plain) self.scrollArea_2.setWidgetResizable(True) self.scrollAreaWidgetContents_2 = QWidget() self.verticalLayout = QVBoxLayout(self.scrollAreaWidgetContents_2) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setSpacing(0) self.inputsTree = QTreeWidget(self.scrollAreaWidgetContents_2) self.inputsTree.setAlternatingRowColors(True) self.inputsTree.header().setVisible(False) self.verticalLayout.addWidget(self.inputsTree) self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2) self.verticalLayout_3.addWidget(self.scrollArea_2) self.inputsDock.setWidget(self.inputsDockContents) self.addDockWidget(Qt.DockWidgetArea(1), self.inputsDock) self.inputsDock.setWindowTitle(self.tr("Inputs")) self.algorithmsDock = QgsDockWidget(self) self.algorithmsDock.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) self.algorithmsDock.setObjectName("algorithmsDock") self.algorithmsDockContents = QWidget() self.verticalLayout_4 = QVBoxLayout(self.algorithmsDockContents) self.verticalLayout_4.setContentsMargins(0, 0, 0, 0) self.scrollArea_3 = QgsScrollArea(self.algorithmsDockContents) sizePolicy.setHeightForWidth(self.scrollArea_3.sizePolicy().hasHeightForWidth()) self.scrollArea_3.setSizePolicy(sizePolicy) self.scrollArea_3.setFocusPolicy(Qt.WheelFocus) self.scrollArea_3.setFrameShape(QFrame.NoFrame) self.scrollArea_3.setFrameShadow(QFrame.Plain) self.scrollArea_3.setWidgetResizable(True) self.scrollAreaWidgetContents_3 = QWidget() self.verticalLayout_2 = QVBoxLayout(self.scrollAreaWidgetContents_3) self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.verticalLayout_2.setSpacing(4) self.searchBox = QgsFilterLineEdit(self.scrollAreaWidgetContents_3) self.verticalLayout_2.addWidget(self.searchBox) self.algorithmTree = QTreeWidget(self.scrollAreaWidgetContents_3) self.algorithmTree.setAlternatingRowColors(True) self.algorithmTree.header().setVisible(False) self.verticalLayout_2.addWidget(self.algorithmTree) self.scrollArea_3.setWidget(self.scrollAreaWidgetContents_3) self.verticalLayout_4.addWidget(self.scrollArea_3) self.algorithmsDock.setWidget(self.algorithmsDockContents) self.addDockWidget(Qt.DockWidgetArea(1), self.algorithmsDock) self.algorithmsDock.setWindowTitle(self.tr("Algorithms")) self.searchBox.setToolTip(self.tr("Enter algorithm name to filter list")) self.searchBox.setShowSearchIcon(True) self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.centralWidget().layout().insertWidget(0, self.bar) try: self.setDockOptions(self.dockOptions() | QMainWindow.GroupedDragging) except: pass self.mToolbar.setIconSize(iface.iconSize()) self.mActionOpen.setIcon( QgsApplication.getThemeIcon('/mActionFileOpen.svg')) self.mActionSave.setIcon( QgsApplication.getThemeIcon('/mActionFileSave.svg')) self.mActionSaveAs.setIcon( QgsApplication.getThemeIcon('/mActionFileSaveAs.svg')) self.mActionZoomActual.setIcon( QgsApplication.getThemeIcon('/mActionZoomActual.svg')) self.mActionZoomIn.setIcon( QgsApplication.getThemeIcon('/mActionZoomIn.svg')) self.mActionZoomOut.setIcon( QgsApplication.getThemeIcon('/mActionZoomOut.svg')) self.mActionExportImage.setIcon( QgsApplication.getThemeIcon('/mActionSaveMapAsImage.svg')) self.mActionZoomToItems.setIcon( QgsApplication.getThemeIcon('/mActionZoomFullExtent.svg')) self.mActionExportPdf.setIcon( QgsApplication.getThemeIcon('/mActionSaveAsPDF.svg')) self.mActionExportSvg.setIcon( QgsApplication.getThemeIcon('/mActionSaveAsSVG.svg')) #self.mActionExportPython.setIcon( # QgsApplication.getThemeIcon('/mActionSaveAsPython.svg')) self.mActionEditHelp.setIcon( QgsApplication.getThemeIcon('/mActionEditHelpContent.svg')) self.mActionRun.setIcon( QgsApplication.getThemeIcon('/mActionStart.svg')) self.addDockWidget(Qt.LeftDockWidgetArea, self.propertiesDock) self.addDockWidget(Qt.LeftDockWidgetArea, self.inputsDock) self.addDockWidget(Qt.LeftDockWidgetArea, self.algorithmsDock) self.tabifyDockWidget(self.inputsDock, self.algorithmsDock) self.inputsDock.raise_() self.zoom = 1 self.setWindowFlags(Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint | Qt.WindowCloseButtonHint) settings = QgsSettings() self.restoreState(settings.value("/Processing/stateModeler", QByteArray())) self.restoreGeometry(settings.value("/Processing/geometryModeler", QByteArray())) self.scene = ModelerScene(self, dialog=self) self.scene.setSceneRect(QRectF(0, 0, self.CANVAS_SIZE, self.CANVAS_SIZE)) self.view.setScene(self.scene) self.view.setAcceptDrops(True) self.view.ensureVisible(0, 0, 10, 10) def _dragEnterEvent(event): if event.mimeData().hasText(): event.acceptProposedAction() else: event.ignore() def _dropEvent(event): if event.mimeData().hasText(): itemId = event.mimeData().text() if itemId in [param.id() for param in QgsApplication.instance().processingRegistry().parameterTypes()]: self.addInputOfType(itemId, event.pos()) else: alg = QgsApplication.processingRegistry().createAlgorithmById(itemId) if alg is not None: self._addAlgorithm(alg, event.pos()) event.accept() else: event.ignore() def _dragMoveEvent(event): if event.mimeData().hasText(): event.accept() else: event.ignore() def _wheelEvent(event): self.view.setTransformationAnchor(QGraphicsView.AnchorUnderMouse) settings = QgsSettings() factor = settings.value('/qgis/zoom_favor', 2.0) # "Normal" mouse has an angle delta of 120, precision mouses provide data # faster, in smaller steps factor = 1.0 + (factor - 1.0) / 120.0 * abs(event.angleDelta().y()) if (event.modifiers() == Qt.ControlModifier): factor = 1.0 + (factor - 1.0) / 20.0 if event.angleDelta().y() < 0: factor = 1 / factor self.view.scale(factor, factor) def _enterEvent(e): QGraphicsView.enterEvent(self.view, e) self.view.viewport().setCursor(Qt.ArrowCursor) def _mouseReleaseEvent(e): QGraphicsView.mouseReleaseEvent(self.view, e) self.view.viewport().setCursor(Qt.ArrowCursor) def _mousePressEvent(e): if e.button() == Qt.MidButton: self.previousMousePos = e.pos() else: QGraphicsView.mousePressEvent(self.view, e) def _mouseMoveEvent(e): if e.buttons() == Qt.MidButton: offset = self.previousMousePos - e.pos() self.previousMousePos = e.pos() self.view.verticalScrollBar().setValue(self.view.verticalScrollBar().value() + offset.y()) self.view.horizontalScrollBar().setValue(self.view.horizontalScrollBar().value() + offset.x()) else: QGraphicsView.mouseMoveEvent(self.view, e) self.view.setDragMode(QGraphicsView.ScrollHandDrag) self.view.dragEnterEvent = _dragEnterEvent self.view.dropEvent = _dropEvent self.view.dragMoveEvent = _dragMoveEvent self.view.wheelEvent = _wheelEvent self.view.enterEvent = _enterEvent self.view.mousePressEvent = _mousePressEvent self.view.mouseMoveEvent = _mouseMoveEvent def _mimeDataInput(items): mimeData = QMimeData() text = items[0].data(0, Qt.UserRole) mimeData.setText(text) return mimeData self.inputsTree.mimeData = _mimeDataInput self.inputsTree.setDragDropMode(QTreeWidget.DragOnly) self.inputsTree.setDropIndicatorShown(True) def _mimeDataAlgorithm(items): item = items[0] mimeData = None if isinstance(item, TreeAlgorithmItem): mimeData = QMimeData() mimeData.setText(item.alg.id()) return mimeData self.algorithmTree.mimeData = _mimeDataAlgorithm self.algorithmTree.setDragDropMode(QTreeWidget.DragOnly) self.algorithmTree.setDropIndicatorShown(True) if hasattr(self.searchBox, 'setPlaceholderText'): self.searchBox.setPlaceholderText(QCoreApplication.translate('ModelerDialog', 'Search…')) if hasattr(self.textName, 'setPlaceholderText'): self.textName.setPlaceholderText(self.tr('Enter model name here')) if hasattr(self.textGroup, 'setPlaceholderText'): self.textGroup.setPlaceholderText(self.tr('Enter group name here')) # Connect signals and slots self.inputsTree.doubleClicked.connect(self.addInput) self.searchBox.textChanged.connect(self.textChanged) self.algorithmTree.doubleClicked.connect(self.addAlgorithm) # Ctrl+= should also trigger a zoom in action ctrlEquals = QShortcut(QKeySequence("Ctrl+="), self) ctrlEquals.activated.connect(self.zoomIn) self.mActionOpen.triggered.connect(self.openModel) self.mActionSave.triggered.connect(self.save) self.mActionSaveAs.triggered.connect(self.saveAs) self.mActionZoomIn.triggered.connect(self.zoomIn) self.mActionZoomOut.triggered.connect(self.zoomOut) self.mActionZoomActual.triggered.connect(self.zoomActual) self.mActionZoomToItems.triggered.connect(self.zoomToItems) self.mActionExportImage.triggered.connect(self.exportAsImage) self.mActionExportPdf.triggered.connect(self.exportAsPdf) self.mActionExportSvg.triggered.connect(self.exportAsSvg) #self.mActionExportPython.triggered.connect(self.exportAsPython) self.mActionEditHelp.triggered.connect(self.editHelp) self.mActionRun.triggered.connect(self.runModel) if model is not None: self.model = model.create() self.model.setSourceFilePath(model.sourceFilePath()) self.textGroup.setText(self.model.group()) self.textName.setText(self.model.displayName()) self.repaintModel() else: self.model = QgsProcessingModelAlgorithm() self.model.setProvider(QgsApplication.processingRegistry().providerById('model')) self.fillInputsTree() self.fillTreeUsingProviders() self.view.centerOn(0, 0) self.help = None self.hasChanged = False def closeEvent(self, evt): settings = QgsSettings() settings.setValue("/Processing/stateModeler", self.saveState()) settings.setValue("/Processing/geometryModeler", self.saveGeometry()) if self.hasChanged: ret = QMessageBox.question( self, self.tr('Save Model?'), self.tr('There are unsaved changes in this model. Do you want to keep those?'), QMessageBox.Save | QMessageBox.Cancel | QMessageBox.Discard, QMessageBox.Cancel) if ret == QMessageBox.Save: self.saveModel(False) evt.accept() elif ret == QMessageBox.Discard: evt.accept() else: evt.ignore() else: evt.accept() def editHelp(self): alg = self.model dlg = HelpEditionDialog(alg) dlg.exec_() if dlg.descriptions: self.model.setHelpContent(dlg.descriptions) self.hasChanged = True def runModel(self): if len(self.model.childAlgorithms()) == 0: self.bar.pushMessage("", self.tr("Model doesn't contain any algorithm and/or parameter and can't be executed"), level=Qgis.Warning, duration=5) return dlg = AlgorithmDialog(self.model) dlg.exec_() def save(self): self.saveModel(False) def saveAs(self): self.saveModel(True) def zoomIn(self): self.view.setTransformationAnchor(QGraphicsView.NoAnchor) point = self.view.mapToScene(QPoint(self.view.viewport().width() / 2, self.view.viewport().height() / 2)) settings = QgsSettings() factor = settings.value('/qgis/zoom_favor', 2.0) self.view.scale(factor, factor) self.view.centerOn(point) self.repaintModel() def zoomOut(self): self.view.setTransformationAnchor(QGraphicsView.NoAnchor) point = self.view.mapToScene(QPoint(self.view.viewport().width() / 2, self.view.viewport().height() / 2)) settings = QgsSettings() factor = settings.value('/qgis/zoom_favor', 2.0) factor = 1 / factor self.view.scale(factor, factor) self.view.centerOn(point) self.repaintModel() def zoomActual(self): point = self.view.mapToScene(QPoint(self.view.viewport().width() / 2, self.view.viewport().height() / 2)) self.view.resetTransform() self.view.centerOn(point) def zoomToItems(self): totalRect = self.scene.itemsBoundingRect() totalRect.adjust(-10, -10, 10, 10) self.view.fitInView(totalRect, Qt.KeepAspectRatio) def exportAsImage(self): self.repaintModel(controls=False) filename, fileFilter = QFileDialog.getSaveFileName(self, self.tr('Save Model As Image'), '', self.tr('PNG files (*.png *.PNG)')) if not filename: return if not filename.lower().endswith('.png'): filename += '.png' totalRect = self.scene.itemsBoundingRect() totalRect.adjust(-10, -10, 10, 10) imgRect = QRectF(0, 0, totalRect.width(), totalRect.height()) img = QImage(totalRect.width(), totalRect.height(), QImage.Format_ARGB32_Premultiplied) img.fill(Qt.white) painter = QPainter() painter.setRenderHint(QPainter.Antialiasing) painter.begin(img) self.scene.render(painter, imgRect, totalRect) painter.end() img.save(filename) self.bar.pushMessage("", self.tr("Model was correctly exported as image"), level=Qgis.Success, duration=5) self.repaintModel(controls=True) def exportAsPdf(self): self.repaintModel(controls=False) filename, fileFilter = QFileDialog.getSaveFileName(self, self.tr('Save Model As PDF'), '', self.tr('PDF files (*.pdf *.PDF)')) if not filename: return if not filename.lower().endswith('.pdf'): filename += '.pdf' totalRect = self.scene.itemsBoundingRect() totalRect.adjust(-10, -10, 10, 10) printerRect = QRectF(0, 0, totalRect.width(), totalRect.height()) printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(filename) printer.setPaperSize(QSizeF(printerRect.width(), printerRect.height()), QPrinter.DevicePixel) printer.setFullPage(True) painter = QPainter(printer) self.scene.render(painter, printerRect, totalRect) painter.end() self.bar.pushMessage("", self.tr("Model was correctly exported as PDF"), level=Qgis.Success, duration=5) self.repaintModel(controls=True) def exportAsSvg(self): self.repaintModel(controls=False) filename, fileFilter = QFileDialog.getSaveFileName(self, self.tr('Save Model As SVG'), '', self.tr('SVG files (*.svg *.SVG)')) if not filename: return if not filename.lower().endswith('.svg'): filename += '.svg' totalRect = self.scene.itemsBoundingRect() totalRect.adjust(-10, -10, 10, 10) svgRect = QRectF(0, 0, totalRect.width(), totalRect.height()) svg = QSvgGenerator() svg.setFileName(filename) svg.setSize(QSize(totalRect.width(), totalRect.height())) svg.setViewBox(svgRect) svg.setTitle(self.model.displayName()) painter = QPainter(svg) self.scene.render(painter, svgRect, totalRect) painter.end() self.bar.pushMessage("", self.tr("Model was correctly exported as SVG"), level=Qgis.Success, duration=5) self.repaintModel(controls=True) def exportAsPython(self): filename, filter = QFileDialog.getSaveFileName(self, self.tr('Save Model As Python Script'), '', self.tr('Python files (*.py *.PY)')) if not filename: return if not filename.lower().endswith('.py'): filename += '.py' text = self.model.asPythonCode() with codecs.open(filename, 'w', encoding='utf-8') as fout: fout.write(text) self.bar.pushMessage("", self.tr("Model was correctly exported as python script"), level=Qgis.Success, duration=5) def saveModel(self, saveAs): if str(self.textGroup.text()).strip() == '' \ or str(self.textName.text()).strip() == '': QMessageBox.warning( self, self.tr('Warning'), self.tr('Please enter group and model names before saving') ) return self.model.setName(str(self.textName.text())) self.model.setGroup(str(self.textGroup.text())) if self.model.sourceFilePath() and not saveAs: filename = self.model.sourceFilePath() else: filename, filter = QFileDialog.getSaveFileName(self, self.tr('Save Model'), ModelerUtils.modelsFolders()[0], self.tr('Processing models (*.model3)')) if filename: if not filename.endswith('.model3'): filename += '.model3' self.model.setSourceFilePath(filename) if filename: if not self.model.toFile(filename): if saveAs: QMessageBox.warning(self, self.tr('I/O error'), self.tr('Unable to save edits. Reason:\n {0}').format(str(sys.exc_info()[1]))) else: QMessageBox.warning(self, self.tr("Can't save model"), QCoreApplication.translate('QgsPluginInstallerInstallingDialog', ( "This model can't be saved in its original location (probably you do not " "have permission to do it). Please, use the 'Save as…' option.")) ) return self.update_model.emit() self.bar.pushMessage("", self.tr("Model was correctly saved"), level=Qgis.Success, duration=5) self.hasChanged = False def openModel(self): filename, selected_filter = QFileDialog.getOpenFileName(self, self.tr('Open Model'), ModelerUtils.modelsFolders()[0], self.tr('Processing models (*.model3 *.MODEL3)')) if filename: self.loadModel(filename) def loadModel(self, filename): alg = QgsProcessingModelAlgorithm() if alg.fromFile(filename): self.model = alg self.model.setProvider(QgsApplication.processingRegistry().providerById('model')) self.textGroup.setText(alg.group()) self.textName.setText(alg.name()) self.repaintModel() self.view.centerOn(0, 0) self.hasChanged = False else: QgsMessageLog.logMessage(self.tr('Could not load model {0}').format(filename), self.tr('Processing'), Qgis.Critical) QMessageBox.critical(self, self.tr('Open Model'), self.tr('The selected model could not be loaded.\n' 'See the log for more information.')) def repaintModel(self, controls=True): self.scene = ModelerScene(self, dialog=self) self.scene.setSceneRect(QRectF(0, 0, self.CANVAS_SIZE, self.CANVAS_SIZE)) self.scene.paintModel(self.model, controls) self.view.setScene(self.scene) def addInput(self): item = self.inputsTree.currentItem() param = item.data(0, Qt.UserRole) self.addInputOfType(param) def addInputOfType(self, paramType, pos=None): dlg = ModelerParameterDefinitionDialog(self.model, paramType) dlg.exec_() if dlg.param is not None: if pos is None: pos = self.getPositionForParameterItem() if isinstance(pos, QPoint): pos = QPointF(pos) component = QgsProcessingModelParameter(dlg.param.name()) component.setDescription(dlg.param.name()) component.setPosition(pos) self.model.addModelParameter(dlg.param, component) self.repaintModel() # self.view.ensureVisible(self.scene.getLastParameterItem()) self.hasChanged = True def getPositionForParameterItem(self): MARGIN = 20 BOX_WIDTH = 200 BOX_HEIGHT = 80 if len(self.model.parameterComponents()) > 0: maxX = max([i.position().x() for i in list(self.model.parameterComponents().values())]) newX = min(MARGIN + BOX_WIDTH + maxX, self.CANVAS_SIZE - BOX_WIDTH) else: newX = MARGIN + BOX_WIDTH / 2 return QPointF(newX, MARGIN + BOX_HEIGHT / 2) def textChanged(self): text = self.searchBox.text().strip(' ').lower() for item in list(self.disabledProviderItems.values()): item.setHidden(True) self._filterItem(self.algorithmTree.invisibleRootItem(), [t for t in text.split(' ') if t]) if text: self.algorithmTree.expandAll() self.disabledWithMatchingAlgs = [] for provider in QgsApplication.processingRegistry().providers(): if not provider.isActive(): for alg in provider.algorithms(): if text in alg.name(): self.disabledWithMatchingAlgs.append(provider.id()) break else: self.algorithmTree.collapseAll() def _filterItem(self, item, text): if (item.childCount() > 0): show = False for i in range(item.childCount()): child = item.child(i) showChild = self._filterItem(child, text) show = (showChild or show) and item not in list(self.disabledProviderItems.values()) item.setHidden(not show) return show elif isinstance(item, (TreeAlgorithmItem, TreeActionItem)): # hide if every part of text is not contained somewhere in either the item text or item user role item_text = [item.text(0).lower(), item.data(0, ModelerDialog.NAME_ROLE).lower()] if isinstance(item, TreeAlgorithmItem): item_text.append(item.alg.id().lower()) if item.alg.shortDescription(): item_text.append(item.alg.shortDescription().lower()) item_text.extend([t.lower() for t in item.data(0, ModelerDialog.TAG_ROLE)]) hide = bool(text) and not all( any(part in t for t in item_text) for part in text) item.setHidden(hide) return not hide else: item.setHidden(True) return False def fillInputsTree(self): icon = QIcon(os.path.join(pluginPath, 'images', 'input.svg')) parametersItem = QTreeWidgetItem() parametersItem.setText(0, self.tr('Parameters')) sortedParams = sorted(QgsApplication.instance().processingRegistry().parameterTypes(), key=lambda pt: pt.name()) for param in sortedParams: if param.flags() & QgsProcessingParameterType.ExposeToModeler: paramItem = QTreeWidgetItem() paramItem.setText(0, param.name()) paramItem.setData(0, Qt.UserRole, param.id()) paramItem.setIcon(0, icon) paramItem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled) paramItem.setToolTip(0, param.description()) parametersItem.addChild(paramItem) self.inputsTree.addTopLevelItem(parametersItem) parametersItem.setExpanded(True) def addAlgorithm(self): item = self.algorithmTree.currentItem() if isinstance(item, TreeAlgorithmItem): alg = QgsApplication.processingRegistry().createAlgorithmById(item.alg.id()) self._addAlgorithm(alg) def _addAlgorithm(self, alg, pos=None): dlg = ModelerParametersDialog(alg, self.model) if dlg.exec_(): alg = dlg.createAlgorithm() if pos is None: alg.setPosition(self.getPositionForAlgorithmItem()) else: alg.setPosition(pos) from processing.modeler.ModelerGraphicItem import ModelerGraphicItem for i, out in enumerate(alg.modelOutputs()): alg.modelOutput(out).setPosition(alg.position() + QPointF(ModelerGraphicItem.BOX_WIDTH, (i + 1.5) * ModelerGraphicItem.BOX_HEIGHT)) self.model.addChildAlgorithm(alg) self.repaintModel() self.hasChanged = True def getPositionForAlgorithmItem(self): MARGIN = 20 BOX_WIDTH = 200 BOX_HEIGHT = 80 if self.model.childAlgorithms(): maxX = max([alg.position().x() for alg in list(self.model.childAlgorithms().values())]) maxY = max([alg.position().y() for alg in list(self.model.childAlgorithms().values())]) newX = min(MARGIN + BOX_WIDTH + maxX, self.CANVAS_SIZE - BOX_WIDTH) newY = min(MARGIN + BOX_HEIGHT + maxY, self.CANVAS_SIZE - BOX_HEIGHT) else: newX = MARGIN + BOX_WIDTH / 2 newY = MARGIN * 2 + BOX_HEIGHT + BOX_HEIGHT / 2 return QPointF(newX, newY) def fillTreeUsingProviders(self): self.algorithmTree.clear() self.disabledProviderItems = {} # TODO - replace with proper model for toolbox! # first add qgis/native providers, since they create top level groups for provider in QgsApplication.processingRegistry().providers(): if provider.id() in ('qgis', 'native', '3d'): self.addAlgorithmsFromProvider(provider, self.algorithmTree.invisibleRootItem()) else: continue self.algorithmTree.sortItems(0, Qt.AscendingOrder) for provider in QgsApplication.processingRegistry().providers(): if provider.id() in ('qgis', 'native', '3d'): # already added continue else: providerItem = TreeProviderItem(provider, self.algorithmTree, self) # insert non-native providers at end of tree, alphabetically for i in range(self.algorithmTree.invisibleRootItem().childCount()): child = self.algorithmTree.invisibleRootItem().child(i) if isinstance(child, TreeProviderItem): if child.text(0) > providerItem.text(0): break self.algorithmTree.insertTopLevelItem(i + 1, providerItem) if not provider.isActive(): providerItem.setHidden(True) self.disabledProviderItems[provider.id()] = providerItem def addAlgorithmsFromProvider(self, provider, parent): groups = {} count = 0 algs = provider.algorithms() active = provider.isActive() # Add algorithms for alg in algs: if alg.flags() & QgsProcessingAlgorithm.FlagHideFromModeler: continue groupItem = None if alg.group() in groups: groupItem = groups[alg.group()] else: # check if group already exists for i in range(parent.childCount()): if parent.child(i).text(0) == alg.group(): groupItem = parent.child(i) groups[alg.group()] = groupItem break if not groupItem: groupItem = TreeGroupItem(alg.group()) if not active: groupItem.setInactive() if provider.id() in ('qgis', 'native', '3d'): groupItem.setIcon(0, provider.icon()) groups[alg.group()] = groupItem algItem = TreeAlgorithmItem(alg) if not active: algItem.setForeground(0, Qt.darkGray) groupItem.addChild(algItem) count += 1 text = provider.name() if not provider.id() in ('qgis', 'native', '3d'): if not active: def activateProvider(): self.activateProvider(provider.id()) label = QLabel(text + " <a href='%s'>Activate</a>") label.setStyleSheet("QLabel {background-color: white; color: grey;}") label.linkActivated.connect(activateProvider) self.algorithmTree.setItemWidget(parent, 0, label) else: parent.setText(0, text) for group, groupItem in sorted(groups.items(), key=operator.itemgetter(1)): parent.addChild(groupItem) if not provider.id() in ('qgis', 'native', '3d'): parent.setHidden(parent.childCount() == 0)
class ModelerParametersDialog(QDialog): def __init__(self, alg, model, algName=None, configuration=None): QDialog.__init__(self) self.setModal(True) self._alg = alg # The algorithm to define in this dialog. It is an instance of QgsProcessingAlgorithm self.model = model # The model this algorithm is going to be added to. It is an instance of QgsProcessingModelAlgorithm self.childId = algName # The name of the algorithm in the model, in case we are editing it and not defining it for the first time self.configuration = configuration self.setupUi() self.params = None settings = QgsSettings() self.restoreGeometry( settings.value("/Processing/modelParametersDialogGeometry", QByteArray())) def closeEvent(self, event): settings = QgsSettings() settings.setValue("/Processing/modelParametersDialogGeometry", self.saveGeometry()) super(ModelerParametersDialog, self).closeEvent(event) 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) 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 widget = wrapper.widget if widget is not None: self.valueItems[param.name()] = widget tooltip = param.description() widget.setToolTip(tooltip) if param.flags( ) & QgsProcessingParameterDefinition.FlagAdvanced: wrapper.label.setVisible(self.showAdvanced) widget.setVisible(self.showAdvanced) self.verticalLayout.addWidget(wrapper.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) for wrapper in list(self.wrappers.values()): wrapper.postInitialize(list(self.wrappers.values())) def getAvailableDependencies(self): # spellok if self.childId is None: dependent = [] else: dependent = list(self.model.dependentChildAlgorithms(self.childId)) dependent.append(self.childId) opts = [] for alg in list(self.model.childAlgorithms().values()): if alg.childId() not in dependent: opts.append(alg) return opts def getDependenciesPanel(self): return MultipleInputPanel([ alg.description() for alg in self.getAvailableDependencies() ]) # spellok def showAdvancedParametersClicked(self): self.showAdvanced = not self.showAdvanced if self.showAdvanced: self.advancedButton.setText(self.tr('Hide advanced parameters')) else: self.advancedButton.setText(self.tr('Show advanced parameters')) for param in self._alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: self.wrappers[param.name()].widget.setVisible( self.showAdvanced) self.wrappers[param.name()].label.setVisible(self.showAdvanced) def getAvailableValuesOfType(self, paramType, outTypes=[], dataTypes=[]): # upgrade paramType to list if paramType is None: paramType = [] elif not isinstance(paramType, (tuple, list)): paramType = [paramType] if outTypes is None: outTypes = [] elif not isinstance(outTypes, (tuple, list)): outTypes = [outTypes] return self.model.availableSourcesForChild(self.childId, [ p.typeName() for p in paramType if issubclass(p, QgsProcessingParameterDefinition) ], [ o.typeName() for o in outTypes if issubclass(o, QgsProcessingOutputDefinition) ], dataTypes) def resolveValueDescription(self, value): if isinstance(value, QgsProcessingModelChildParameterSource): if value.source( ) == QgsProcessingModelChildParameterSource.StaticValue: return value.staticValue() elif value.source( ) == QgsProcessingModelChildParameterSource.ModelParameter: return self.model.parameterDefinition( value.parameterName()).description() elif value.source( ) == QgsProcessingModelChildParameterSource.ChildOutput: alg = self.model.childAlgorithm(value.outputChildId()) return self.tr("'{0}' from algorithm '{1}'").format( alg.algorithm().outputDefinition( value.outputName()).description(), alg.description()) return value def setPreviousValues(self): if self.childId is not None: alg = self.model.childAlgorithm(self.childId) self.descriptionBox.setText(alg.description()) for param in alg.algorithm().parameterDefinitions(): if param.isDestination() or param.flags( ) & QgsProcessingParameterDefinition.FlagHidden: continue value = None if param.name() in alg.parameterSources(): value = alg.parameterSources()[param.name()] if isinstance(value, list) and len(value) == 1: value = value[0] elif isinstance(value, list) and len(value) == 0: value = None if value is None: value = param.defaultValue() if isinstance( value, QgsProcessingModelChildParameterSource ) and value.source( ) == QgsProcessingModelChildParameterSource.StaticValue: value = value.staticValue() self.wrappers[param.name()].setValue(value) for name, out in list(alg.modelOutputs().items()): if out.childOutputName() in self.valueItems: self.valueItems[out.childOutputName()].setText(out.name()) selected = [] dependencies = self.getAvailableDependencies() # spellok for idx, dependency in enumerate(dependencies): if dependency.childId() in alg.dependencies(): selected.append(idx) self.dependenciesPanel.setSelectedItems(selected) def createAlgorithm(self): alg = QgsProcessingModelChildAlgorithm(self._alg.id()) if not self.childId: alg.generateChildId(self.model) else: alg.setChildId(self.childId) alg.setDescription(self.descriptionBox.text()) if self.algorithmItem: alg.setConfiguration(self.algorithmItem.configuration()) self._alg = alg.algorithm().create( self.algorithmItem.configuration()) for param in self._alg.parameterDefinitions(): if param.isDestination( ) or param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue try: val = self.wrappers[param.name()].value() except InvalidParameterValue: self.bar.pushMessage( self.tr("Error"), self.tr( "Wrong or missing value for parameter '{}'").format( param.description()), level=Qgis.Warning) return None if isinstance(val, QgsProcessingModelChildParameterSource): val = [val] elif not (isinstance(val, list) and all([ isinstance(subval, QgsProcessingModelChildParameterSource) for subval in val ])): val = [ QgsProcessingModelChildParameterSource.fromStaticValue(val) ] for subval in val: if (isinstance(subval, QgsProcessingModelChildParameterSource) and subval.source() == QgsProcessingModelChildParameterSource.StaticValue and not param.checkValueIsAcceptable(subval.staticValue())) \ or (subval is None and not param.flags() & QgsProcessingParameterDefinition.FlagOptional): self.bar.pushMessage( self.tr("Error"), self.tr("Wrong or missing value for parameter '{}'" ).format(param.description()), level=Qgis.Warning) return None alg.addParameterSources(param.name(), val) outputs = {} for dest in self._alg.destinationParameterDefinitions(): if not dest.flags() & QgsProcessingParameterDefinition.FlagHidden: name = self.valueItems[dest.name()].text() if name.strip() != '': output = QgsProcessingModelOutput(name, name) output.setChildId(alg.childId()) output.setChildOutputName(dest.name()) outputs[name] = output if dest.flags( ) & QgsProcessingParameterDefinition.FlagIsModelOutput: if dest.name() not in outputs: output = QgsProcessingModelOutput(dest.name(), dest.name()) output.setChildId(alg.childId()) output.setChildOutputName(dest.name()) outputs[dest.name()] = output alg.setModelOutputs(outputs) selectedOptions = self.dependenciesPanel.selectedoptions availableDependencies = self.getAvailableDependencies() # spellok dep_ids = [] for selected in selectedOptions: dep_ids.append( availableDependencies[selected].childId()) # spellok alg.setDependencies(dep_ids) #try: # self._alg.processBeforeAddingToModeler(alg, self.model) #except: # pass return alg def okPressed(self): alg = self.createAlgorithm() if alg is not None: self.accept() def cancelPressed(self): self.reject() def openHelp(self): algHelp = self._alg.helpUrl() if not algHelp: algHelp = QgsHelp.helpUrl("processing_algs/{}/{}.html#{}".format( self._alg.provider().helpId(), self._alg.groupId(), "{}{}".format(self._alg.provider().helpId(), self._alg.name()))).toString() if algHelp not in [None, ""]: webbrowser.open(algHelp)
class ModelerDialog(BASE, WIDGET): ALG_ITEM = 'ALG_ITEM' PROVIDER_ITEM = 'PROVIDER_ITEM' GROUP_ITEM = 'GROUP_ITEM' NAME_ROLE = Qt.UserRole TAG_ROLE = Qt.UserRole + 1 TYPE_ROLE = Qt.UserRole + 2 CANVAS_SIZE = 4000 update_model = pyqtSignal() def __init__(self, model=None): super().__init__(None) self.setAttribute(Qt.WA_DeleteOnClose) self.setupUi(self) # LOTS of bug reports when we include the dock creation in the UI file # see e.g. #16428, #19068 # So just roll it all by hand......! self.propertiesDock = QgsDockWidget(self) self.propertiesDock.setFeatures( QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) self.propertiesDock.setObjectName("propertiesDock") propertiesDockContents = QWidget() self.verticalDockLayout_1 = QVBoxLayout(propertiesDockContents) self.verticalDockLayout_1.setContentsMargins(0, 0, 0, 0) self.verticalDockLayout_1.setSpacing(0) self.scrollArea_1 = QgsScrollArea(propertiesDockContents) sizePolicy = QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.scrollArea_1.sizePolicy().hasHeightForWidth()) self.scrollArea_1.setSizePolicy(sizePolicy) self.scrollArea_1.setFocusPolicy(Qt.WheelFocus) self.scrollArea_1.setFrameShape(QFrame.NoFrame) self.scrollArea_1.setFrameShadow(QFrame.Plain) self.scrollArea_1.setWidgetResizable(True) self.scrollAreaWidgetContents_1 = QWidget() self.gridLayout = QGridLayout(self.scrollAreaWidgetContents_1) self.gridLayout.setContentsMargins(6, 6, 6, 6) self.gridLayout.setSpacing(4) self.label_1 = QLabel(self.scrollAreaWidgetContents_1) self.gridLayout.addWidget(self.label_1, 0, 0, 1, 1) self.textName = QLineEdit(self.scrollAreaWidgetContents_1) self.gridLayout.addWidget(self.textName, 0, 1, 1, 1) self.label_2 = QLabel(self.scrollAreaWidgetContents_1) self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1) self.textGroup = QLineEdit(self.scrollAreaWidgetContents_1) self.gridLayout.addWidget(self.textGroup, 1, 1, 1, 1) self.label_1.setText(self.tr("Name")) self.textName.setToolTip(self.tr("Enter model name here")) self.label_2.setText(self.tr("Group")) self.textGroup.setToolTip(self.tr("Enter group name here")) self.scrollArea_1.setWidget(self.scrollAreaWidgetContents_1) self.verticalDockLayout_1.addWidget(self.scrollArea_1) self.propertiesDock.setWidget(propertiesDockContents) self.addDockWidget(Qt.DockWidgetArea(1), self.propertiesDock) self.propertiesDock.setWindowTitle(self.tr("Model properties")) self.inputsDock = QgsDockWidget(self) self.inputsDock.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) self.inputsDock.setObjectName("inputsDock") self.inputsDockContents = QWidget() self.verticalLayout_3 = QVBoxLayout(self.inputsDockContents) self.verticalLayout_3.setContentsMargins(0, 0, 0, 0) self.scrollArea_2 = QgsScrollArea(self.inputsDockContents) sizePolicy.setHeightForWidth(self.scrollArea_2.sizePolicy().hasHeightForWidth()) self.scrollArea_2.setSizePolicy(sizePolicy) self.scrollArea_2.setFocusPolicy(Qt.WheelFocus) self.scrollArea_2.setFrameShape(QFrame.NoFrame) self.scrollArea_2.setFrameShadow(QFrame.Plain) self.scrollArea_2.setWidgetResizable(True) self.scrollAreaWidgetContents_2 = QWidget() self.verticalLayout = QVBoxLayout(self.scrollAreaWidgetContents_2) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setSpacing(0) self.inputsTree = QTreeWidget(self.scrollAreaWidgetContents_2) self.inputsTree.setAlternatingRowColors(True) self.inputsTree.header().setVisible(False) self.verticalLayout.addWidget(self.inputsTree) self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2) self.verticalLayout_3.addWidget(self.scrollArea_2) self.inputsDock.setWidget(self.inputsDockContents) self.addDockWidget(Qt.DockWidgetArea(1), self.inputsDock) self.inputsDock.setWindowTitle(self.tr("Inputs")) self.algorithmsDock = QgsDockWidget(self) self.algorithmsDock.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) self.algorithmsDock.setObjectName("algorithmsDock") self.algorithmsDockContents = QWidget() self.verticalLayout_4 = QVBoxLayout(self.algorithmsDockContents) self.verticalLayout_4.setContentsMargins(0, 0, 0, 0) self.scrollArea_3 = QgsScrollArea(self.algorithmsDockContents) sizePolicy.setHeightForWidth(self.scrollArea_3.sizePolicy().hasHeightForWidth()) self.scrollArea_3.setSizePolicy(sizePolicy) self.scrollArea_3.setFocusPolicy(Qt.WheelFocus) self.scrollArea_3.setFrameShape(QFrame.NoFrame) self.scrollArea_3.setFrameShadow(QFrame.Plain) self.scrollArea_3.setWidgetResizable(True) self.scrollAreaWidgetContents_3 = QWidget() self.verticalLayout_2 = QVBoxLayout(self.scrollAreaWidgetContents_3) self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.verticalLayout_2.setSpacing(4) self.searchBox = QgsFilterLineEdit(self.scrollAreaWidgetContents_3) self.verticalLayout_2.addWidget(self.searchBox) self.algorithmTree = QgsProcessingToolboxTreeView(None, QgsApplication.processingRegistry()) self.algorithmTree.setAlternatingRowColors(True) self.algorithmTree.header().setVisible(False) self.verticalLayout_2.addWidget(self.algorithmTree) self.scrollArea_3.setWidget(self.scrollAreaWidgetContents_3) self.verticalLayout_4.addWidget(self.scrollArea_3) self.algorithmsDock.setWidget(self.algorithmsDockContents) self.addDockWidget(Qt.DockWidgetArea(1), self.algorithmsDock) self.algorithmsDock.setWindowTitle(self.tr("Algorithms")) self.searchBox.setToolTip(self.tr("Enter algorithm name to filter list")) self.searchBox.setShowSearchIcon(True) self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.centralWidget().layout().insertWidget(0, self.bar) try: self.setDockOptions(self.dockOptions() | QMainWindow.GroupedDragging) except: pass if iface is not None: self.mToolbar.setIconSize(iface.iconSize()) self.setStyleSheet(iface.mainWindow().styleSheet()) self.mActionOpen.setIcon( QgsApplication.getThemeIcon('/mActionFileOpen.svg')) self.mActionSave.setIcon( QgsApplication.getThemeIcon('/mActionFileSave.svg')) self.mActionSaveAs.setIcon( QgsApplication.getThemeIcon('/mActionFileSaveAs.svg')) self.mActionSaveInProject.setIcon( QgsApplication.getThemeIcon('/mAddToProject.svg')) self.mActionZoomActual.setIcon( QgsApplication.getThemeIcon('/mActionZoomActual.svg')) self.mActionZoomIn.setIcon( QgsApplication.getThemeIcon('/mActionZoomIn.svg')) self.mActionZoomOut.setIcon( QgsApplication.getThemeIcon('/mActionZoomOut.svg')) self.mActionExportImage.setIcon( QgsApplication.getThemeIcon('/mActionSaveMapAsImage.svg')) self.mActionZoomToItems.setIcon( QgsApplication.getThemeIcon('/mActionZoomFullExtent.svg')) self.mActionExportPdf.setIcon( QgsApplication.getThemeIcon('/mActionSaveAsPDF.svg')) self.mActionExportSvg.setIcon( QgsApplication.getThemeIcon('/mActionSaveAsSVG.svg')) #self.mActionExportPython.setIcon( # QgsApplication.getThemeIcon('/mActionSaveAsPython.svg')) self.mActionEditHelp.setIcon( QgsApplication.getThemeIcon('/mActionEditHelpContent.svg')) self.mActionRun.setIcon( QgsApplication.getThemeIcon('/mActionStart.svg')) self.addDockWidget(Qt.LeftDockWidgetArea, self.propertiesDock) self.addDockWidget(Qt.LeftDockWidgetArea, self.inputsDock) self.addDockWidget(Qt.LeftDockWidgetArea, self.algorithmsDock) self.tabifyDockWidget(self.inputsDock, self.algorithmsDock) self.inputsDock.raise_() self.zoom = 1 self.setWindowFlags(Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint | Qt.WindowCloseButtonHint) settings = QgsSettings() self.restoreState(settings.value("/Processing/stateModeler", QByteArray())) self.restoreGeometry(settings.value("/Processing/geometryModeler", QByteArray())) self.scene = ModelerScene(self, dialog=self) self.scene.setSceneRect(QRectF(0, 0, self.CANVAS_SIZE, self.CANVAS_SIZE)) self.view.setScene(self.scene) self.view.setAcceptDrops(True) self.view.ensureVisible(0, 0, 10, 10) def _dragEnterEvent(event): if event.mimeData().hasText() or event.mimeData().hasFormat('application/x-vnd.qgis.qgis.algorithmid'): event.acceptProposedAction() else: event.ignore() def _dropEvent(event): if event.mimeData().hasFormat('application/x-vnd.qgis.qgis.algorithmid'): data = event.mimeData().data('application/x-vnd.qgis.qgis.algorithmid') stream = QDataStream(data, QIODevice.ReadOnly) algorithm_id = stream.readQString() alg = QgsApplication.processingRegistry().createAlgorithmById(algorithm_id) if alg is not None: self._addAlgorithm(alg, event.pos()) else: assert False, algorithm_id elif event.mimeData().hasText(): itemId = event.mimeData().text() if itemId in [param.id() for param in QgsApplication.instance().processingRegistry().parameterTypes()]: self.addInputOfType(itemId, event.pos()) event.accept() else: event.ignore() def _dragMoveEvent(event): if event.mimeData().hasText() or event.mimeData().hasFormat('application/x-vnd.qgis.qgis.algorithmid'): event.accept() else: event.ignore() def _wheelEvent(event): self.view.setTransformationAnchor(QGraphicsView.AnchorUnderMouse) settings = QgsSettings() factor = settings.value('/qgis/zoom_favor', 2.0) # "Normal" mouse has an angle delta of 120, precision mouses provide data # faster, in smaller steps factor = 1.0 + (factor - 1.0) / 120.0 * abs(event.angleDelta().y()) if (event.modifiers() == Qt.ControlModifier): factor = 1.0 + (factor - 1.0) / 20.0 if event.angleDelta().y() < 0: factor = 1 / factor self.view.scale(factor, factor) def _enterEvent(e): QGraphicsView.enterEvent(self.view, e) self.view.viewport().setCursor(Qt.ArrowCursor) def _mouseReleaseEvent(e): QGraphicsView.mouseReleaseEvent(self.view, e) self.view.viewport().setCursor(Qt.ArrowCursor) def _mousePressEvent(e): if e.button() == Qt.MidButton: self.previousMousePos = e.pos() else: QGraphicsView.mousePressEvent(self.view, e) def _mouseMoveEvent(e): if e.buttons() == Qt.MidButton: offset = self.previousMousePos - e.pos() self.previousMousePos = e.pos() self.view.verticalScrollBar().setValue(self.view.verticalScrollBar().value() + offset.y()) self.view.horizontalScrollBar().setValue(self.view.horizontalScrollBar().value() + offset.x()) else: QGraphicsView.mouseMoveEvent(self.view, e) self.view.setDragMode(QGraphicsView.ScrollHandDrag) self.view.dragEnterEvent = _dragEnterEvent self.view.dropEvent = _dropEvent self.view.dragMoveEvent = _dragMoveEvent self.view.wheelEvent = _wheelEvent self.view.enterEvent = _enterEvent self.view.mousePressEvent = _mousePressEvent self.view.mouseMoveEvent = _mouseMoveEvent def _mimeDataInput(items): mimeData = QMimeData() text = items[0].data(0, Qt.UserRole) mimeData.setText(text) return mimeData self.inputsTree.mimeData = _mimeDataInput self.inputsTree.setDragDropMode(QTreeWidget.DragOnly) self.inputsTree.setDropIndicatorShown(True) self.algorithms_model = ModelerToolboxModel(self, QgsApplication.processingRegistry()) self.algorithmTree.setToolboxProxyModel(self.algorithms_model) self.algorithmTree.setDragDropMode(QTreeWidget.DragOnly) self.algorithmTree.setDropIndicatorShown(True) self.algorithmTree.setFilters(QgsProcessingToolboxProxyModel.FilterModeler) if hasattr(self.searchBox, 'setPlaceholderText'): self.searchBox.setPlaceholderText(QCoreApplication.translate('ModelerDialog', 'Search…')) if hasattr(self.textName, 'setPlaceholderText'): self.textName.setPlaceholderText(self.tr('Enter model name here')) if hasattr(self.textGroup, 'setPlaceholderText'): self.textGroup.setPlaceholderText(self.tr('Enter group name here')) # Connect signals and slots self.inputsTree.doubleClicked.connect(self.addInput) self.searchBox.textChanged.connect(self.algorithmTree.setFilterString) self.algorithmTree.doubleClicked.connect(self.addAlgorithm) # Ctrl+= should also trigger a zoom in action ctrlEquals = QShortcut(QKeySequence("Ctrl+="), self) ctrlEquals.activated.connect(self.zoomIn) self.mActionOpen.triggered.connect(self.openModel) self.mActionSave.triggered.connect(self.save) self.mActionSaveAs.triggered.connect(self.saveAs) self.mActionSaveInProject.triggered.connect(self.saveInProject) self.mActionZoomIn.triggered.connect(self.zoomIn) self.mActionZoomOut.triggered.connect(self.zoomOut) self.mActionZoomActual.triggered.connect(self.zoomActual) self.mActionZoomToItems.triggered.connect(self.zoomToItems) self.mActionExportImage.triggered.connect(self.exportAsImage) self.mActionExportPdf.triggered.connect(self.exportAsPdf) self.mActionExportSvg.triggered.connect(self.exportAsSvg) #self.mActionExportPython.triggered.connect(self.exportAsPython) self.mActionEditHelp.triggered.connect(self.editHelp) self.mActionRun.triggered.connect(self.runModel) if model is not None: self.model = model.create() self.model.setSourceFilePath(model.sourceFilePath()) self.textGroup.setText(self.model.group()) self.textName.setText(self.model.displayName()) self.repaintModel() else: self.model = QgsProcessingModelAlgorithm() self.model.setProvider(QgsApplication.processingRegistry().providerById('model')) self.fillInputsTree() self.view.centerOn(0, 0) self.help = None self.hasChanged = False def closeEvent(self, evt): settings = QgsSettings() settings.setValue("/Processing/stateModeler", self.saveState()) settings.setValue("/Processing/geometryModeler", self.saveGeometry()) if self.hasChanged: ret = QMessageBox.question( self, self.tr('Save Model?'), self.tr('There are unsaved changes in this model. Do you want to keep those?'), QMessageBox.Save | QMessageBox.Cancel | QMessageBox.Discard, QMessageBox.Cancel) if ret == QMessageBox.Save: self.saveModel(False) evt.accept() elif ret == QMessageBox.Discard: evt.accept() else: evt.ignore() else: evt.accept() def editHelp(self): alg = self.model dlg = HelpEditionDialog(alg) dlg.exec_() if dlg.descriptions: self.model.setHelpContent(dlg.descriptions) self.hasChanged = True def runModel(self): if len(self.model.childAlgorithms()) == 0: self.bar.pushMessage("", self.tr("Model doesn't contain any algorithm and/or parameter and can't be executed"), level=Qgis.Warning, duration=5) return dlg = AlgorithmDialog(self.model) dlg.exec_() def save(self): self.saveModel(False) def saveAs(self): self.saveModel(True) def saveInProject(self): if not self.can_save(): return self.model.setName(str(self.textName.text())) self.model.setGroup(str(self.textGroup.text())) self.model.setSourceFilePath(None) project_provider = QgsApplication.processingRegistry().providerById(PROJECT_PROVIDER_ID) project_provider.add_model(self.model) self.update_model.emit() self.bar.pushMessage("", self.tr("Model was saved inside current project"), level=Qgis.Success, duration=5) self.hasChanged = False QgsProject.instance().setDirty(True) def zoomIn(self): self.view.setTransformationAnchor(QGraphicsView.NoAnchor) point = self.view.mapToScene(QPoint(self.view.viewport().width() / 2, self.view.viewport().height() / 2)) settings = QgsSettings() factor = settings.value('/qgis/zoom_favor', 2.0) self.view.scale(factor, factor) self.view.centerOn(point) self.repaintModel() def zoomOut(self): self.view.setTransformationAnchor(QGraphicsView.NoAnchor) point = self.view.mapToScene(QPoint(self.view.viewport().width() / 2, self.view.viewport().height() / 2)) settings = QgsSettings() factor = settings.value('/qgis/zoom_favor', 2.0) factor = 1 / factor self.view.scale(factor, factor) self.view.centerOn(point) self.repaintModel() def zoomActual(self): point = self.view.mapToScene(QPoint(self.view.viewport().width() / 2, self.view.viewport().height() / 2)) self.view.resetTransform() self.view.centerOn(point) def zoomToItems(self): totalRect = self.scene.itemsBoundingRect() totalRect.adjust(-10, -10, 10, 10) self.view.fitInView(totalRect, Qt.KeepAspectRatio) def exportAsImage(self): self.repaintModel(controls=False) filename, fileFilter = QFileDialog.getSaveFileName(self, self.tr('Save Model As Image'), '', self.tr('PNG files (*.png *.PNG)')) if not filename: return if not filename.lower().endswith('.png'): filename += '.png' totalRect = self.scene.itemsBoundingRect() totalRect.adjust(-10, -10, 10, 10) imgRect = QRectF(0, 0, totalRect.width(), totalRect.height()) img = QImage(totalRect.width(), totalRect.height(), QImage.Format_ARGB32_Premultiplied) img.fill(Qt.white) painter = QPainter() painter.setRenderHint(QPainter.Antialiasing) painter.begin(img) self.scene.render(painter, imgRect, totalRect) painter.end() img.save(filename) self.bar.pushMessage("", self.tr("Successfully exported model as image to <a href=\"{}\">{}</a>").format(QUrl.fromLocalFile(filename).toString(), QDir.toNativeSeparators(filename)), level=Qgis.Success, duration=5) self.repaintModel(controls=True) def exportAsPdf(self): self.repaintModel(controls=False) filename, fileFilter = QFileDialog.getSaveFileName(self, self.tr('Save Model As PDF'), '', self.tr('PDF files (*.pdf *.PDF)')) if not filename: return if not filename.lower().endswith('.pdf'): filename += '.pdf' totalRect = self.scene.itemsBoundingRect() totalRect.adjust(-10, -10, 10, 10) printerRect = QRectF(0, 0, totalRect.width(), totalRect.height()) printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(filename) printer.setPaperSize(QSizeF(printerRect.width(), printerRect.height()), QPrinter.DevicePixel) printer.setFullPage(True) painter = QPainter(printer) self.scene.render(painter, printerRect, totalRect) painter.end() self.bar.pushMessage("", self.tr("Successfully exported model as PDF to <a href=\"{}\">{}</a>").format(QUrl.fromLocalFile(filename).toString(), QDir.toNativeSeparators(filename)), level=Qgis.Success, duration=5) self.repaintModel(controls=True) def exportAsSvg(self): self.repaintModel(controls=False) filename, fileFilter = QFileDialog.getSaveFileName(self, self.tr('Save Model As SVG'), '', self.tr('SVG files (*.svg *.SVG)')) if not filename: return if not filename.lower().endswith('.svg'): filename += '.svg' totalRect = self.scene.itemsBoundingRect() totalRect.adjust(-10, -10, 10, 10) svgRect = QRectF(0, 0, totalRect.width(), totalRect.height()) svg = QSvgGenerator() svg.setFileName(filename) svg.setSize(QSize(totalRect.width(), totalRect.height())) svg.setViewBox(svgRect) svg.setTitle(self.model.displayName()) painter = QPainter(svg) self.scene.render(painter, svgRect, totalRect) painter.end() self.bar.pushMessage("", self.tr("Successfully exported model as SVG to <a href=\"{}\">{}</a>").format(QUrl.fromLocalFile(filename).toString(), QDir.toNativeSeparators(filename)), level=Qgis.Success, duration=5) self.repaintModel(controls=True) def exportAsPython(self): filename, filter = QFileDialog.getSaveFileName(self, self.tr('Save Model As Python Script'), '', self.tr('Processing scripts (*.py *.PY)')) if not filename: return if not filename.lower().endswith('.py'): filename += '.py' text = self.model.asPythonCode() with codecs.open(filename, 'w', encoding='utf-8') as fout: fout.write(text) self.bar.pushMessage("", self.tr("Successfully exported model as python script to <a href=\"{}\">{}</a>").format(QUrl.fromLocalFile(filename).toString(), QDir.toNativeSeparators(filename)), level=Qgis.Success, duration=5) def can_save(self): """ Tests whether a model can be saved, or if it is not yet valid :return: bool """ if str(self.textName.text()).strip() == '': self.bar.pushWarning( "", self.tr('Please a enter model name before saving') ) return False return True def saveModel(self, saveAs): if not self.can_save(): return self.model.setName(str(self.textName.text())) self.model.setGroup(str(self.textGroup.text())) if self.model.sourceFilePath() and not saveAs: filename = self.model.sourceFilePath() else: filename, filter = QFileDialog.getSaveFileName(self, self.tr('Save Model'), ModelerUtils.modelsFolders()[0], self.tr('Processing models (*.model3 *.MODEL3)')) if filename: if not filename.endswith('.model3'): filename += '.model3' self.model.setSourceFilePath(filename) if filename: if not self.model.toFile(filename): if saveAs: QMessageBox.warning(self, self.tr('I/O error'), self.tr('Unable to save edits. Reason:\n {0}').format(str(sys.exc_info()[1]))) else: QMessageBox.warning(self, self.tr("Can't save model"), QCoreApplication.translate('QgsPluginInstallerInstallingDialog', ( "This model can't be saved in its original location (probably you do not " "have permission to do it). Please, use the 'Save as…' option.")) ) return self.update_model.emit() if saveAs: self.bar.pushMessage("", self.tr("Model was correctly saved to <a href=\"{}\">{}</a>").format(QUrl.fromLocalFile(filename).toString(), QDir.toNativeSeparators(filename)), level=Qgis.Success, duration=5) else: self.bar.pushMessage("", self.tr("Model was correctly saved"), level=Qgis.Success, duration=5) self.hasChanged = False def openModel(self): filename, selected_filter = QFileDialog.getOpenFileName(self, self.tr('Open Model'), ModelerUtils.modelsFolders()[0], self.tr('Processing models (*.model3 *.MODEL3)')) if filename: self.loadModel(filename) def loadModel(self, filename): alg = QgsProcessingModelAlgorithm() if alg.fromFile(filename): self.model = alg self.model.setProvider(QgsApplication.processingRegistry().providerById('model')) self.textGroup.setText(alg.group()) self.textName.setText(alg.name()) self.repaintModel() self.view.centerOn(0, 0) self.hasChanged = False else: QgsMessageLog.logMessage(self.tr('Could not load model {0}').format(filename), self.tr('Processing'), Qgis.Critical) QMessageBox.critical(self, self.tr('Open Model'), self.tr('The selected model could not be loaded.\n' 'See the log for more information.')) def repaintModel(self, controls=True): self.scene = ModelerScene(self, dialog=self) self.scene.setSceneRect(QRectF(0, 0, self.CANVAS_SIZE, self.CANVAS_SIZE)) self.scene.paintModel(self.model, controls) self.view.setScene(self.scene) def addInput(self): item = self.inputsTree.currentItem() param = item.data(0, Qt.UserRole) self.addInputOfType(param) def addInputOfType(self, paramType, pos=None): dlg = ModelerParameterDefinitionDialog(self.model, paramType) dlg.exec_() if dlg.param is not None: if pos is None: pos = self.getPositionForParameterItem() if isinstance(pos, QPoint): pos = QPointF(pos) component = QgsProcessingModelParameter(dlg.param.name()) component.setDescription(dlg.param.name()) component.setPosition(pos) self.model.addModelParameter(dlg.param, component) self.repaintModel() # self.view.ensureVisible(self.scene.getLastParameterItem()) self.hasChanged = True def getPositionForParameterItem(self): MARGIN = 20 BOX_WIDTH = 200 BOX_HEIGHT = 80 if len(self.model.parameterComponents()) > 0: maxX = max([i.position().x() for i in list(self.model.parameterComponents().values())]) newX = min(MARGIN + BOX_WIDTH + maxX, self.CANVAS_SIZE - BOX_WIDTH) else: newX = MARGIN + BOX_WIDTH / 2 return QPointF(newX, MARGIN + BOX_HEIGHT / 2) def fillInputsTree(self): icon = QIcon(os.path.join(pluginPath, 'images', 'input.svg')) parametersItem = QTreeWidgetItem() parametersItem.setText(0, self.tr('Parameters')) sortedParams = sorted(QgsApplication.instance().processingRegistry().parameterTypes(), key=lambda pt: pt.name()) for param in sortedParams: if param.flags() & QgsProcessingParameterType.ExposeToModeler: paramItem = QTreeWidgetItem() paramItem.setText(0, param.name()) paramItem.setData(0, Qt.UserRole, param.id()) paramItem.setIcon(0, icon) paramItem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled) paramItem.setToolTip(0, param.description()) parametersItem.addChild(paramItem) self.inputsTree.addTopLevelItem(parametersItem) parametersItem.setExpanded(True) def addAlgorithm(self): algorithm = self.algorithmTree.selectedAlgorithm() if algorithm is not None: alg = QgsApplication.processingRegistry().createAlgorithmById(algorithm.id()) self._addAlgorithm(alg) def _addAlgorithm(self, alg, pos=None): dlg = ModelerParametersDialog(alg, self.model) if dlg.exec_(): alg = dlg.createAlgorithm() if pos is None: alg.setPosition(self.getPositionForAlgorithmItem()) else: alg.setPosition(pos) from processing.modeler.ModelerGraphicItem import ModelerGraphicItem for i, out in enumerate(alg.modelOutputs()): alg.modelOutput(out).setPosition(alg.position() + QPointF(ModelerGraphicItem.BOX_WIDTH, (i + 1.5) * ModelerGraphicItem.BOX_HEIGHT)) self.model.addChildAlgorithm(alg) self.repaintModel() self.hasChanged = True def getPositionForAlgorithmItem(self): MARGIN = 20 BOX_WIDTH = 200 BOX_HEIGHT = 80 if self.model.childAlgorithms(): maxX = max([alg.position().x() for alg in list(self.model.childAlgorithms().values())]) maxY = max([alg.position().y() for alg in list(self.model.childAlgorithms().values())]) newX = min(MARGIN + BOX_WIDTH + maxX, self.CANVAS_SIZE - BOX_WIDTH) newY = min(MARGIN + BOX_HEIGHT + maxY, self.CANVAS_SIZE - BOX_HEIGHT) else: newX = MARGIN + BOX_WIDTH / 2 newY = MARGIN * 2 + BOX_HEIGHT + BOX_HEIGHT / 2 return QPointF(newX, newY)
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()
class ConfigDialog(QDialog): def __init__(self, namespace): self.settings = pluginSettings(namespace) self.namespace = namespace QDialog.__init__(self, iface.mainWindow()) self.setupUi() if hasattr(self.searchBox, 'setPlaceholderText'): self.searchBox.setPlaceholderText(self.tr("Search...")) self.searchBox.textChanged.connect(self.filterTree) self.fillTree() self.tree.expandAll() 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.searchBox = QgsFilterLineEdit(self) self.verticalLayout.addWidget(self.searchBox) self.tree = QTreeWidget(self) self.tree.setAlternatingRowColors(True) self.verticalLayout.addWidget(self.tree) self.horizontalLayout = QHBoxLayout(self) self.resetButton = QPushButton("Reset default values") self.resetButton.clicked.connect(self.resetDefault) self.horizontalLayout.addWidget(self.resetButton) 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.searchBox.setToolTip("Enter setting name to filter list") self.tree.headerItem().setText(0, "Setting") self.tree.headerItem().setText(1, "Value") def saveValues(): iterator = QTreeWidgetItemIterator(self.tree) value = iterator.value() while value: if hasattr(value, 'saveValue'): try: value.saveValue() except WrongValueException: return iterator += 1 value = iterator.value() QDialog.accept(self) self.close() self.buttonBox.accepted.connect(saveValues) self.buttonBox.rejected.connect(self.reject) def resetDefault(self): root = self.tree.invisibleRootItem() for i in range(root.childCount()): item = root.child(i) for j in range(item.childCount()): subitem = item.child(j) subitem.resetDefault() def filterTree(self): text = unicode(self.searchBox.text()) for i in range(self.tree.topLevelItemCount()): item = self.tree.topLevelItem(i) visible = False for j in range(item.childCount()): subitem = item.child(j) itemText = subitem.text(0) if (text.strip() == ""): subitem.setHidden(False) visible = True else: hidden = text not in itemText item.setHidden(hidden) visible = visible or not hidden item.setHidden(not visible) item.setExpanded(visible and text.strip() != "") def fillTree(self): self.items = {} self.tree.clear() grouped = defaultdict(list) for setting in self.settings: grouped[setting["group"]].append(setting) for groupName, group in grouped.items(): item = self._getGroupItem(groupName, group) self.tree.addTopLevelItem(item) self.tree.setColumnWidth(0, 400) def _getGroupItem(self, groupName, params): item = QTreeWidgetItem() item.setText(0, groupName) icon = QIcon(os.path.join(os.path.dirname(__file__), "setting.png")) item.setIcon(0, icon) for param in params: value = pluginSetting(param["name"], self.namespace) subItem = TreeSettingItem(item, self.tree, param, self.namespace, value) item.addChild(subItem) return item
def __init__(self): super(NavigatorDialog, self).__init__(None) self.currentRepo = None self.reposItem = None self.setupUi(self) self.filterWidget.hide() self.leFilter.setPlaceholderText( self.tr("Type here to filter repositories...")) self.actionAddGeoGigServer.setIcon(icon('geogig_server.svg')) self.actionCreateRepository.setIcon(icon('new-repo.png')) self.actionAddLayer.setIcon(icon('layer_group.svg')) self.actionManageRemotes.setIcon(icon('geogig.png')) self.actionEdit.setIcon(icon('edit.svg')) self.actionRefresh.setIcon( QgsApplication.getThemeIcon('/mActionDraw.svg')) self.actionShowFilter.setIcon( QgsApplication.getThemeIcon('/mActionFilter2.svg')) self.actionDelete.setIcon( QgsApplication.getThemeIcon('/mActionDeleteSelected.svg')) self.actionHelp.setIcon( QgsApplication.getThemeIcon('/mActionHelpContents.svg')) self.actionPull.setIcon(icon('pull.svg')) self.actionPush.setIcon(icon('push.svg')) self.actionAddGeoGigServer.triggered.connect(self.addGeoGigServer) self.actionCreateRepository.triggered.connect(self.createRepo) self.actionAddLayer.triggered.connect(self.addLayer) self.actionEdit.triggered.connect(self.editGeoGigServer) self.actionRefresh.triggered.connect(self.updateNavigator) self.actionShowFilter.triggered.connect(self.showFilterWidget) self.actionDelete.triggered.connect(self.deleteCurrentElement) self.actionHelp.triggered.connect(self.openHelp) self.actionManageRemotes.triggered.connect(self.manageRemotes) self.actionPull.triggered.connect(self.pull) self.actionPush.triggered.connect(self.push) self.leFilter.returnPressed.connect(self.filterRepos) self.leFilter.cleared.connect(self.filterRepos) self.leFilter.textChanged.connect(self.filterRepos) self.repoTree.itemSelectionChanged.connect(self.selectionChanged) self.repoDescription.anchorClicked.connect(self.descriptionLinkClicked) self.repoDescription.setOpenLinks(False) self.repoTree.setFocusPolicy(Qt.NoFocus) with open(resourceFile("repodescription.css")) as f: sheet = "".join(f.readlines()) self.repoDescription.document().setDefaultStyleSheet(sheet) if qtVersion < 5: self.repoTree.header().setResizeMode(0, QHeaderView.Stretch) self.repoTree.header().setResizeMode(1, QHeaderView.ResizeToContents) self.versionsTree = HistoryViewer() layout = QVBoxLayout() layout.setSpacing(0) layout.setMargin(0) layout.addWidget(self.versionsTree) self.versionsWidget.setLayout(layout) def _repoChanged(repo): if self.currentRepo is not None and repo.url == self.currentRepo.url: self.updateCurrentRepo(repo) for i in range(self.reposItem.childCount()): item = self.reposItem.child(i) for j in range(item.childCount()): subitem = item.child(j) if subitem.repo == repo: subitem.refreshContent() repoWatcher.repoChanged.connect(_repoChanged) self.updateNavigator() self.repoTree.itemExpanded.connect(self._itemExpanded)
class QvFormNovaMapificacio(QvFormBaseMapificacio): def __init__(self, llegenda, amplada=500, mapificacio=None, simple=True): super().__init__(llegenda, amplada) self.fCSV = mapificacio self.simple = simple self.taulaMostra = None self.setWindowTitle('Afegir capa amb mapa simbòlic') self.layout = QVBoxLayout() self.layout.setSpacing(14) self.setLayout(self.layout) if self.fCSV is None: self.arxiu = QgsFileWidget() self.arxiu.setStorageMode(QgsFileWidget.GetFile) self.arxiu.setDialogTitle('Selecciona fitxer de dades…') self.arxiu.setDefaultRoot(RUTA_LOCAL) self.arxiu.setFilter('Arxius CSV (*.csv)') self.arxiu.setSelectedFilter('Arxius CSV (*.csv)') self.arxiu.lineEdit().setReadOnly(True) self.arxiu.fileChanged.connect(self.arxiuSeleccionat) self.zona = QComboBox(self) self.zona.setEditable(False) self.zona.addItem('Selecciona zona…') self.zona.currentIndexChanged.connect(self.canviaZona) self.mapa = QComboBox(self) self.mapa.setEditable(False) self.mapa.setIconSize(QSize(126, 126)) self.mapa.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding) self.mapa.setSizeAdjustPolicy(QComboBox.AdjustToContents) self.mapa.addItem(QIcon(os.path.join(imatgesDir, 'Àrees.PNG')), 'Àrees') self.mapa.addItem(QIcon(os.path.join(imatgesDir, 'Cercles.PNG')), 'Cercles') self.capa = QLineEdit(self) self.capa.setMaxLength(40) self.tipus = QComboBox(self) self.tipus.setEditable(False) self.tipus.addItem('Selecciona tipus…') self.tipus.addItems(mv.MAP_AGREGACIO.keys()) self.tipus.currentIndexChanged.connect(self.canviaTipus) self.distribucio = QComboBox(self) self.distribucio.setEditable(False) self.distribucio.addItem(next(iter(mv.MAP_DISTRIBUCIO.keys()))) self.calcul = QvComboBoxCamps(self) self.filtre = QvComboBoxCamps(self, multiple=True) self.color = QComboBox(self) self.color.setEditable(False) self.comboColors(self.color) self.metode = QComboBox(self) self.metode.setEditable(False) self.metode.addItems(mv.MAP_METODES.keys()) self.intervals = QSpinBox(self) self.intervals.setMinimum(2) self.intervals.setMaximum(mv.MAP_MAX_CATEGORIES) self.intervals.setSingleStep(1) self.intervals.setValue(4) self.intervals.setSuffix(" (depèn del mètode)") # self.intervals.valueChanged.connect(self.deselectValue) self.bTaula = QPushButton('Veure arxiu') self.bTaula.setEnabled(False) self.bTaula.clicked.connect(self.veureArxiu) self.buttons = QDialogButtonBox() self.buttons.addButton(QDialogButtonBox.Ok) self.buttons.accepted.connect(self.accept) self.buttons.addButton(QDialogButtonBox.Cancel) self.buttons.rejected.connect(self.cancel) self.buttons.addButton(self.bTaula, QDialogButtonBox.ResetRole) self.gDades = QGroupBox('Agregació de dades') self.lDades = QFormLayout() self.lDades.setSpacing(14) self.gDades.setLayout(self.lDades) if self.fCSV is None: self.lDades.addRow('Arxiu de dades:', self.arxiu) self.lDades.addRow('Zona:', self.zona) self.lDades.addRow("Tipus d'agregació:", self.tipus) self.lDades.addRow('Camp de càlcul:', self.calcul) if self.simple: self.filtre.setVisible(False) self.distribucio.setVisible(False) else: self.lDades.addRow('Filtre:', self.filtre) self.lDades.addRow('Distribució:', self.distribucio) self.gMapa = QGroupBox('Definició del mapa simbòlic') self.lMapa = QFormLayout() self.lMapa.setSpacing(14) self.gMapa.setLayout(self.lMapa) self.lMapa.addRow('Nom de capa:', self.capa) self.lMapa.addRow('Tipus de mapa:', self.mapa) self.gSimb = QGroupBox('Simbologia del mapa') self.lSimb = QFormLayout() self.lSimb.setSpacing(14) self.gSimb.setLayout(self.lSimb) self.lSimb.addRow('Color base:', self.color) self.lSimb.addRow('Mètode classificació:', self.metode) self.lSimb.addRow("Nombre d'intervals:", self.intervals) self.layout.addWidget(self.gDades) self.layout.addWidget(self.gMapa) if self.simple: self.gSimb.setVisible(False) else: self.layout.addWidget(self.gSimb) self.layout.addWidget(self.buttons) self.adjustSize() self.nouArxiu() def exec(self): # La mapificación solo funciona si está instalado el módulo pandas if PANDAS_ENABLED: return super().exec() else: self.msgError(PANDAS_ERROR) return QDialog.Rejected @pyqtSlot() def veureArxiu(self): if self.taulaMostra is not None: self.taulaMostra.show() self.taulaMostra.activateWindow() def campsDB(self, nom): res = [] if nom != '': fich = RUTA_DADES + mv.MAP_ZONES_DB if os.path.isfile(fich): conn = sqlite3.connect('file:' + fich + '?mode=ro', uri=True) conn.row_factory = sqlite3.Row c = conn.cursor() c.execute('select * from ' + nom) # nom.split('.')[0]) row = c.fetchone() # res = [i[0].upper() for i in c.description] res = [i.upper() for i in row.keys()] conn.close() return res def soloPrimerItem(self, combo): combo.setCurrentIndex(0) ultimo = combo.count() - 1 for n in range(ultimo, 0, -1): combo.removeItem(n) @pyqtSlot() def canviaZona(self): self.distribucio.setCurrentIndex(0) self.soloPrimerItem(self.distribucio) if self.zona.currentIndex() > 0: z = self.zona.currentText() campsZona = self.campsDB(mv.MAP_ZONES[z][1]) # Carga combo con distribuciones si el campo correspondiente está en la BBDD for dist, campo in mv.MAP_DISTRIBUCIO.items(): if campo != '' and campo in campsZona: self.distribucio.addItem(dist) @pyqtSlot() def canviaTipus(self): if self.tipus.currentText() == 'Recompte': self.calcul.setCurrentIndex(-1) self.calcul.setEnabled(False) else: self.calcul.setEnabled(True) def borrarArxiu(self): if self.taulaMostra is not None: self.taulaMostra.hide() self.taulaMostra = None self.bTaula.setEnabled(False) self.tipus.setCurrentIndex(0) self.soloPrimerItem(self.zona) self.calcul.clear() self.filtre.clear() def nouArxiu(self): if self.fCSV is None: return # Carga combo con zonas si el campo correspondiente está en el fichero CSV num = 0 for zona, val in mv.MAP_ZONES.items(): if val[1] != '' and self.fCSV.prefixe + QvSqlite.getAlias(val[0]) in self.fCSV.camps: self.zona.addItem(zona) num = num + 1 # Comprobar si la extensión del mapa está limitada if num > 0: extensio = self.fCSV.testExtensioArxiu(mv.MAP_EXTENSIO) if extensio: # Mapa limitado self.comboDelete(self.zona, mv.MAP_TRUE_EXTENSIO) else: # Mapa completo self.comboDelete(self.zona, mv.MAP_FALSE_EXTENSIO) # Ajustar combo de zonas if num == 0: self.msgInfo("El fitxer " + self.fCSV.fZones + " no té cap camp de zona") if hasattr(self, 'arxiu'): self.arxiu.lineEdit().clear() self.arxiu.setFocus() return if num == 1: self.zona.setCurrentIndex(1) self.capa.setFocus() else: self.zona.setFocus() self.taulaMostra = QvEditorCsv(self.fCSV.fZones, [], 'utf-8', self.fCSV.separador, self) self.taulaMostra.setWindowTitle("Vista prèvia d'arxiu geocodificat") self.taulaMostra.setReadOnly(True) self.bTaula.setEnabled(True) self.calcul.setItems(self.fCSV.camps, primer='') self.filtre.setItems(self.fCSV.camps) @pyqtSlot(str) def arxiuSeleccionat(self, nom): if nom == '': return self.borrarArxiu() self.fCSV = QvMapificacio(nom) self.nouArxiu() def validaSortida(self, nom): fSalida = self.fCSV.nomArxiuSortida(self.fCSV.netejaString(nom, True)) return self.msgSobreescriure(fSalida) def valida(self): ok = False if hasattr(self, 'arxiu') and self.arxiu.filePath() == '': self.msgInfo("S'ha de seleccionar un arxiu de dades") self.arxiu.setFocus() elif self.zona.currentIndex() <= 0: self.msgInfo("S'ha de seleccionar una zona") self.zona.setFocus() elif self.capa.text().strip() == '': self.msgInfo("S'ha de introduir un nom de capa") self.capa.setFocus() elif self.tipus.currentIndex() <= 0: self.msgInfo("S'ha de seleccionar un tipus d'agregació") self.tipus.setFocus() elif self.calcul.currentText().strip() == '' and self.tipus.currentText() != 'Recompte': self.msgInfo("S'ha de introduir un cálcul per fer l'agregació") self.calcul.setFocus() elif self.fCSV is None: return self.msgInfo("No hi ha cap fitxer seleccionat") elif not self.validaSortida(self.capa.text().strip()): self.capa.setFocus() else: ok = True return ok def setRenderParams(self): self.renderParams = QvMapRendererParams(self.mapa.currentText()) if self.simple: self.renderParams.colorBase = mv.MAP_COLORS[self.renderParams.colorBase] else: self.renderParams.colorBase = mv.MAP_COLORS[self.color.currentText()] if self.renderParams.colorContorn is None or self.renderParams.colorContorn == 'Base': self.renderParams.colorContorn = self.renderParams.colorBase else: self.renderParams.colorContorn = mv.MAP_CONTORNS[self.renderParams.colorContorn] if self.tipus.currentText().startswith('Recompte') and \ self.distribucio.currentText() == "Total": self.renderParams.numDecimals = 0 else: self.renderParams.numDecimals = 2 if self.renderParams.tipusMapa == 'Àrees': self.renderParams.modeCategories = mv.MAP_METODES[self.metode.currentText()] self.renderParams.numCategories = self.intervals.value() if self.renderParams.tipusMapa == 'Cercles': zona = self.zona.currentText() if zona == 'Districte': self.renderParams.increase = 8 elif zona == 'Barri': self.renderParams.increase = 4 elif zona == 'Àrea estadística bàsica': self.renderParams.increase = 3 elif zona == 'Secció censal': self.renderParams.increase = 2 else: self.renderParams.increase = 1 def procesa(self): if self.taulaMostra is not None: self.taulaMostra.hide() self.setRenderParams() ok = self.fCSV.agregacio(self.llegenda, self.capa.text().strip(), self.zona.currentText(), self.tipus.currentText(), self.renderParams, campAgregat=self.calcul.currentText().strip(), simple=self.simple, filtre=self.filtre.currentText().strip(), tipusDistribucio=self.distribucio.currentText(), form=self) if ok: return '' else: return self.fCSV.msgError
class CalculatorModelerParametersDialog(ModelerParametersDialog): def setupUi(self): self.valueItems = {} self.dependentItems = {} self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.infoText = QTextEdit() numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) text = self.tr( 'You can refer to model values in your formula, using ' 'single-letter variables, as follows:\n', 'CalculatorModelerParametersDialog') ichar = 97 if numbers: for number in numbers: text += chr(ichar) + '->' + self.resolveValueDescription( number) + '\n' ichar += 1 else: text += self.tr('\n - No numerical variables are available.', 'CalculatorModelerParametersDialog') self.infoText.setText(text) self.infoText.setEnabled(False) self.formulaText = QLineEdit() if hasattr(self.formulaText, 'setPlaceholderText'): self.formulaText.setPlaceholderText( self.tr('[Enter your formula here]', 'CalculatorModelerParametersDialog')) if self._algName is not None: alg = self.model.algs[self._algName] self.formulaText.setText(alg.params[FORMULA]) self.setWindowTitle( self.tr('Calculator', 'CalculatorModelerParametersDialog')) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(2) self.verticalLayout.setMargin(0) self.verticalLayout.addWidget(self.infoText) self.verticalLayout.addWidget(self.formulaText) self.verticalLayout.addWidget(self.buttonBox) self.setLayout(self.verticalLayout) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) QMetaObject.connectSlotsByName(self) def createAlgorithm(self): alg = Algorithm('modelertools:calculator') alg.setName(self.model) alg.description = self.tr('Calculator', 'CalculatorModelerParametersDialog') formula = self.formulaText.text() alg.params[FORMULA] = formula for i in xrange(AVAILABLE_VARIABLES): paramname = NUMBER + unicode(i) alg.params[paramname] = None numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) used = [] for i in range(len(numbers)): if unicode(chr(i + 97)) in formula: used.append(numbers[i]) for i, variable in enumerate(used): paramname = NUMBER + unicode(i) alg.params[paramname] = variable # TODO check formula is correct return alg
def __init__(self, parent, alg): ParametersPanel.__init__(self, parent, alg) ## Création le l'interface Qt pour les paramètres ## Add console command w = QWidget() # New Qt Windows layout = QVBoxLayout() # New Qt vertical Layout layout.setMargin(0) layout.setSpacing(6) label = QLabel() # New Qt label (text) label.setText(self.tr("Chloe/Java console call")) layout.addWidget(label) # Add label in layout self.text = QPlainTextEdit() # New Qt champs de text in/out self.text.setReadOnly(True) # Read only layout.addWidget(self.text) # Add in layout w.setLayout(layout) # layout -in-> Windows self.layoutMain.addWidget(w) # windows -in-> Windows system self.types_of_metrics = {} for output in self.alg.outputs: if isinstance(output, (OutputRaster, OutputVector, OutputTable)): self.checkBoxes[output.name].setText(self.tr('Open output file after running algorithm')) self.connectParameterSignals() self.parametersHaveChanged() self.changeWindowShapeDependent() # === param:WINDOW_SIZES Widget:IntListSelectionPanel === lineEdit = self.widgets["WINDOW_SIZES"].lineEdit lineEdit.setReadOnly(True) sbInt = self.widgets["WINDOW_SIZES"].sbInt sbInt.setValue(3) # === param:METRICS Widget:ListSelectionPanel === # === Init cbFilter cbFilter = self.widgets["METRICS"].cbFilter cbFilter.addItems(self.alg.types_of_metrics.keys()) # === Init listSrc value = cbFilter.currentText() listSrc = self.widgets["METRICS"].listSrc listSrc.clear() if self.types_of_metrics: if value in self.types_of_metrics.keys(): listSrc.addItems(self.types_of_metrics[value]) # === Init listDest listDest = self.widgets["METRICS"].listDest listDest.clear() self.metrics_selected = set() self.window_sizes_selected = set() lineEdit = self.widgets["METRICS"].lineEdit lineEdit.setReadOnly(True)
def __init__(self, entity, parent=None, notification_bar=None, enable_list=True, can_filter=False, plugin=None): QWidget.__init__(self, parent) self.current_profile = current_profile() self._tbFKEntity = QTableView(self) self._tbFKEntity.setEditTriggers(QAbstractItemView.NoEditTriggers) self._tbFKEntity.setAlternatingRowColors(True) self._tbFKEntity.setSelectionBehavior(QAbstractItemView.SelectRows) self.plugin = plugin self._add_entity_btn = QToolButton(self) self._add_entity_btn.setToolTip( QApplication.translate("ForeignKeyMapper", "Add")) self._add_entity_btn.setIcon(GuiUtils.get_icon("add.png")) self._add_entity_btn.clicked.connect(self.onAddEntity) self._edit_entity_btn = QToolButton(self) self._edit_entity_btn.setVisible(False) self._edit_entity_btn.setToolTip( QApplication.translate("ForeignKeyMapper", "Edit")) self._edit_entity_btn.setIcon(GuiUtils.get_icon("edit.png")) self._filter_entity_btn = QToolButton(self) self._filter_entity_btn.setVisible(False) self._filter_entity_btn.setToolTip( QApplication.translate("ForeignKeyMapper", "Select by expression")) self._filter_entity_btn.setIcon(GuiUtils.get_icon("filter.png")) self._filter_entity_btn.clicked.connect(self.onFilterEntity) self._delete_entity_btn = QToolButton(self) self._delete_entity_btn.setToolTip( QApplication.translate("ForeignKeyMapper", "Remove")) self._delete_entity_btn.setIcon(GuiUtils.get_icon("remove.png")) self._delete_entity_btn.clicked.connect(self.onRemoveEntity) layout = QVBoxLayout(self) layout.setSpacing(4) layout.setMargin(5) self.grid_layout = QGridLayout() self.grid_layout.setHorizontalSpacing(5) self.grid_layout.addWidget(self._add_entity_btn, 0, 0, 1, 1) self.grid_layout.addWidget(self._filter_entity_btn, 0, 1, 1, 1) self.grid_layout.addWidget(self._edit_entity_btn, 0, 2, 1, 1) self.grid_layout.addWidget(self._delete_entity_btn, 0, 3, 1, 1) self.grid_layout.setColumnStretch(4, 5) layout.addLayout(self.grid_layout) layout.addWidget(self._tbFKEntity) self.social_tenure = self.current_profile.social_tenure self._tableModel = None self._notifBar = notification_bar self._headers = [] self._entity_attrs = [] self._cell_formatters = {} self._searchable_columns = OrderedDict() self._supportsLists = enable_list self._deleteOnRemove = False self._uniqueValueColIndices = OrderedDict() self.global_id = None self._deferred_objects = {} self._use_expression_builder = can_filter if self._use_expression_builder: self._filter_entity_btn.setVisible(True) self._edit_entity_btn.setVisible(False) self.set_entity(entity)
class CalculatorModelerParametersDialog(ModelerParametersDialog): def setupUi(self): self.valueItems = {} self.dependentItems = {} self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.infoText = QTextEdit() numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) text = self.tr('You can refer to model values in your formula, using ' 'single-letter variables, as follows:\n', 'CalculatorModelerParametersDialog') ichar = 97 if numbers: for number in numbers: text += chr(ichar) + '->' + self.resolveValueDescription(number) + '\n' ichar += 1 else: text += self.tr('\n - No numerical variables are available.', 'CalculatorModelerParametersDialog') self.infoText.setText(text) self.infoText.setEnabled(False) self.formulaText = QLineEdit() if hasattr(self.formulaText, 'setPlaceholderText'): self.formulaText.setPlaceholderText(self.tr('[Enter your formula here]', 'CalculatorModelerParametersDialog')) if self._algName is not None: alg = self.model.algs[self._algName] self.formulaText.setText(alg.params[FORMULA]) self.setWindowTitle(self.tr('Calculator', 'CalculatorModelerParametersDialog')) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(2) self.verticalLayout.setMargin(0) self.verticalLayout.addWidget(self.infoText) self.verticalLayout.addWidget(self.formulaText) self.verticalLayout.addWidget(self.buttonBox) self.setLayout(self.verticalLayout) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) QMetaObject.connectSlotsByName(self) def createAlgorithm(self): alg = Algorithm('modelertools:calculator') alg.setName(self.model) alg.description = self.tr('Calculator', 'CalculatorModelerParametersDialog') formula = self.formulaText.text() alg.params[FORMULA] = formula for i in range(AVAILABLE_VARIABLES): paramname = NUMBER + str(i) alg.params[paramname] = None numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) used = [] for i in range(len(numbers)): if str(chr(i + 97)) in formula: used.append(numbers[i]) for i, variable in enumerate(used): paramname = NUMBER + str(i) alg.params[paramname] = variable # TODO check formula is correct return alg
def populate_details(self): self.bundleWidgets = [] permissions = [img[PERMISSIONS] for img in self.images] item_bundles = order_bundles.bundles_for_item_type( self.item_type, permissions=permissions) default = order_bundles.item_default_bundle_name(self.item_type) def _center(obj): hlayout = QHBoxLayout() hlayout.addStretch() hlayout.addWidget(obj) hlayout.addStretch() return hlayout layout = QVBoxLayout() layout.setMargin(0) layout.setSpacing(20) layout.addLayout(_center(QLabel("<b>RECTIFIED ASSETS</b>"))) gridlayout = QGridLayout() gridlayout.setMargin(0) i = 0 for bundle in item_bundles: bundleid = bundle["id"] if bundle["rectification"] == "orthorectified": name = bundle["name"] description = bundle["description"] udm = bundle.get("auxiliaryFiles", "").lower().startswith("udm2") w = PlanetOrderBundleWidget(bundleid, name, description, udm, True) gridlayout.addWidget(w, i // 2, i % 2) w.setSelected(bundleid == default) w.selectionChanged.connect( partial(self._bundle_selection_changed, w)) self.bundleWidgets.append(w) i += 1 layout.addLayout(gridlayout) self.labelUnrectified = QLabel("<b>UNRECTIFIED ASSETS</b>") layout.addLayout(_center(self.labelUnrectified)) self.widgetUnrectified = QWidget() gridlayoutUnrect = QGridLayout() gridlayoutUnrect.setMargin(0) i = 0 for bundle in item_bundles: bundleid = bundle["id"] if bundle["rectification"] != "orthorectified": name = bundle["name"] description = bundle["description"] udm = bundle.get("auxiliaryFiles", "").lower().startswith("udm2") w = PlanetOrderBundleWidget(bundleid, name, description, udm, False) gridlayoutUnrect.addWidget(w, i // 2, i % 2) w.selectionChanged.connect( partial(self._bundle_selection_changed, w)) self.bundleWidgets.append(w) i += 1 self.widgetUnrectified.setLayout(gridlayoutUnrect) layout.addWidget(self.widgetUnrectified) self.labelMore = QLabel('<a href="#">+ Show More</a>') self.labelMore.setOpenExternalLinks(False) self.labelMore.setTextInteractionFlags(Qt.LinksAccessibleByMouse) self.labelMore.linkActivated.connect(self._showMoreClicked) layout.addLayout(_center(self.labelMore)) self.widgetUnrectified.hide() self.labelUnrectified.hide() self.widgetDetails.setLayout(layout)
class ConfigDialog(QDialog): versioIcon = QIcon( os.path.dirname(__file__) + "/../../ui/resources/geogig-16.png") def __init__(self): QDialog.__init__(self) self.setupUi() if hasattr(self.searchBox, 'setPlaceholderText'): self.searchBox.setPlaceholderText(self.tr("Search...")) self.searchBox.textChanged.connect(self.filterTree) self.fillTree() def setupUi(self): self.resize(640, 450) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(2) self.verticalLayout.setMargin(0) self.searchBox = QgsFilterLineEdit(self) self.verticalLayout.addWidget(self.searchBox) self.tree = QTreeWidget(self) self.tree.setAlternatingRowColors(True) self.verticalLayout.addWidget(self.tree) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) self.verticalLayout.addWidget(self.buttonBox) self.setWindowTitle("Configuration options") self.searchBox.setToolTip("Enter setting name to filter list") self.tree.headerItem().setText(0, "Setting") self.tree.headerItem().setText(1, "Value") self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.setLayout(self.verticalLayout) def filterTree(self): text = str(self.searchBox.text()) for i in range(self.tree.topLevelItemCount()): item = self.tree.topLevelItem(i) visible = False for j in range(item.childCount()): subitem = item.child(j) itemText = subitem.text(0) if (text.strip() == ""): subitem.setHidden(False) visible = True else: hidden = text not in itemText item.setHidden(hidden) visible = visible or not hidden item.setHidden(not visible) item.setExpanded(visible and text.strip() != "") def fillTree(self): self.items = {} self.tree.clear() generalItem = self._getItem(config.GENERAL, self.versioIcon, config.generalParams) self.tree.addTopLevelItem(generalItem) self.tree.setColumnWidth(0, 400) def _getItem(self, name, icon, params): item = QTreeWidgetItem() item.setText(0, name) item.setIcon(0, icon) for param in params: paramName = "/GeoGig/Settings/" + name + "/" + param[0] subItem = TreeSettingItem(self.tree, item, paramName, *param[1:]) item.addChild(subItem) return item def accept(self): iterator = QTreeWidgetItemIterator(self.tree) value = iterator.value() while value: if hasattr(value, 'checkValue'): if value.checkValue(): value.setBackgroundColor(1, Qt.white) else: value.setBackgroundColor(1, Qt.yellow) return iterator += 1 value = iterator.value() iterator = QTreeWidgetItemIterator(self.tree) value = iterator.value() while value: if hasattr(value, 'saveValue'): value.saveValue() iterator += 1 value = iterator.value() QDialog.accept(self)
class ModelerDialog(BASE, WIDGET): ALG_ITEM = 'ALG_ITEM' PROVIDER_ITEM = 'PROVIDER_ITEM' GROUP_ITEM = 'GROUP_ITEM' NAME_ROLE = Qt.UserRole TAG_ROLE = Qt.UserRole + 1 TYPE_ROLE = Qt.UserRole + 2 CANVAS_SIZE = 4000 update_model = pyqtSignal() def __init__(self, model=None): super().__init__(None) self.setAttribute(Qt.WA_DeleteOnClose) self.setupUi(self) self._variables_scope = None # LOTS of bug reports when we include the dock creation in the UI file # see e.g. #16428, #19068 # So just roll it all by hand......! self.propertiesDock = QgsDockWidget(self) self.propertiesDock.setFeatures( QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) self.propertiesDock.setObjectName("propertiesDock") propertiesDockContents = QWidget() self.verticalDockLayout_1 = QVBoxLayout(propertiesDockContents) self.verticalDockLayout_1.setContentsMargins(0, 0, 0, 0) self.verticalDockLayout_1.setSpacing(0) self.scrollArea_1 = QgsScrollArea(propertiesDockContents) sizePolicy = QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.scrollArea_1.sizePolicy().hasHeightForWidth()) self.scrollArea_1.setSizePolicy(sizePolicy) self.scrollArea_1.setFocusPolicy(Qt.WheelFocus) self.scrollArea_1.setFrameShape(QFrame.NoFrame) self.scrollArea_1.setFrameShadow(QFrame.Plain) self.scrollArea_1.setWidgetResizable(True) self.scrollAreaWidgetContents_1 = QWidget() self.gridLayout = QGridLayout(self.scrollAreaWidgetContents_1) self.gridLayout.setContentsMargins(6, 6, 6, 6) self.gridLayout.setSpacing(4) self.label_1 = QLabel(self.scrollAreaWidgetContents_1) self.gridLayout.addWidget(self.label_1, 0, 0, 1, 1) self.textName = QLineEdit(self.scrollAreaWidgetContents_1) self.gridLayout.addWidget(self.textName, 0, 1, 1, 1) self.label_2 = QLabel(self.scrollAreaWidgetContents_1) self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1) self.textGroup = QLineEdit(self.scrollAreaWidgetContents_1) self.gridLayout.addWidget(self.textGroup, 1, 1, 1, 1) self.label_1.setText(self.tr("Name")) self.textName.setToolTip(self.tr("Enter model name here")) self.label_2.setText(self.tr("Group")) self.textGroup.setToolTip(self.tr("Enter group name here")) self.scrollArea_1.setWidget(self.scrollAreaWidgetContents_1) self.verticalDockLayout_1.addWidget(self.scrollArea_1) self.propertiesDock.setWidget(propertiesDockContents) self.propertiesDock.setWindowTitle(self.tr("Model Properties")) self.inputsDock = QgsDockWidget(self) self.inputsDock.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) self.inputsDock.setObjectName("inputsDock") self.inputsDockContents = QWidget() self.verticalLayout_3 = QVBoxLayout(self.inputsDockContents) self.verticalLayout_3.setContentsMargins(0, 0, 0, 0) self.scrollArea_2 = QgsScrollArea(self.inputsDockContents) sizePolicy.setHeightForWidth(self.scrollArea_2.sizePolicy().hasHeightForWidth()) self.scrollArea_2.setSizePolicy(sizePolicy) self.scrollArea_2.setFocusPolicy(Qt.WheelFocus) self.scrollArea_2.setFrameShape(QFrame.NoFrame) self.scrollArea_2.setFrameShadow(QFrame.Plain) self.scrollArea_2.setWidgetResizable(True) self.scrollAreaWidgetContents_2 = QWidget() self.verticalLayout = QVBoxLayout(self.scrollAreaWidgetContents_2) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setSpacing(0) self.inputsTree = QTreeWidget(self.scrollAreaWidgetContents_2) self.inputsTree.setAlternatingRowColors(True) self.inputsTree.header().setVisible(False) self.verticalLayout.addWidget(self.inputsTree) self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2) self.verticalLayout_3.addWidget(self.scrollArea_2) self.inputsDock.setWidget(self.inputsDockContents) self.addDockWidget(Qt.DockWidgetArea(1), self.inputsDock) self.inputsDock.setWindowTitle(self.tr("Inputs")) self.algorithmsDock = QgsDockWidget(self) self.algorithmsDock.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) self.algorithmsDock.setObjectName("algorithmsDock") self.algorithmsDockContents = QWidget() self.verticalLayout_4 = QVBoxLayout(self.algorithmsDockContents) self.verticalLayout_4.setContentsMargins(0, 0, 0, 0) self.scrollArea_3 = QgsScrollArea(self.algorithmsDockContents) sizePolicy.setHeightForWidth(self.scrollArea_3.sizePolicy().hasHeightForWidth()) self.scrollArea_3.setSizePolicy(sizePolicy) self.scrollArea_3.setFocusPolicy(Qt.WheelFocus) self.scrollArea_3.setFrameShape(QFrame.NoFrame) self.scrollArea_3.setFrameShadow(QFrame.Plain) self.scrollArea_3.setWidgetResizable(True) self.scrollAreaWidgetContents_3 = QWidget() self.verticalLayout_2 = QVBoxLayout(self.scrollAreaWidgetContents_3) self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.verticalLayout_2.setSpacing(4) self.searchBox = QgsFilterLineEdit(self.scrollAreaWidgetContents_3) self.verticalLayout_2.addWidget(self.searchBox) self.algorithmTree = QgsProcessingToolboxTreeView(None, QgsApplication.processingRegistry()) self.algorithmTree.setAlternatingRowColors(True) self.algorithmTree.header().setVisible(False) self.verticalLayout_2.addWidget(self.algorithmTree) self.scrollArea_3.setWidget(self.scrollAreaWidgetContents_3) self.verticalLayout_4.addWidget(self.scrollArea_3) self.algorithmsDock.setWidget(self.algorithmsDockContents) self.addDockWidget(Qt.DockWidgetArea(1), self.algorithmsDock) self.algorithmsDock.setWindowTitle(self.tr("Algorithms")) self.searchBox.setToolTip(self.tr("Enter algorithm name to filter list")) self.searchBox.setShowSearchIcon(True) self.variables_dock = QgsDockWidget(self) self.variables_dock.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) self.variables_dock.setObjectName("variablesDock") self.variables_dock_contents = QWidget() vl_v = QVBoxLayout() vl_v.setContentsMargins(0, 0, 0, 0) self.variables_editor = QgsVariableEditorWidget() vl_v.addWidget(self.variables_editor) self.variables_dock_contents.setLayout(vl_v) self.variables_dock.setWidget(self.variables_dock_contents) self.addDockWidget(Qt.DockWidgetArea(1), self.variables_dock) self.variables_dock.setWindowTitle(self.tr("Variables")) self.addDockWidget(Qt.DockWidgetArea(1), self.propertiesDock) self.tabifyDockWidget(self.propertiesDock, self.variables_dock) self.variables_editor.scopeChanged.connect(self.variables_changed) self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.centralWidget().layout().insertWidget(0, self.bar) try: self.setDockOptions(self.dockOptions() | QMainWindow.GroupedDragging) except: pass if iface is not None: self.mToolbar.setIconSize(iface.iconSize()) self.setStyleSheet(iface.mainWindow().styleSheet()) self.toolbutton_export_to_script = QToolButton() self.toolbutton_export_to_script.setPopupMode(QToolButton.InstantPopup) self.export_to_script_algorithm_action = QAction(QCoreApplication.translate('ModelerDialog', 'Export as Script Algorithm…')) self.toolbutton_export_to_script.addActions([self.export_to_script_algorithm_action]) self.mToolbar.insertWidget(self.mActionExportImage, self.toolbutton_export_to_script) self.export_to_script_algorithm_action.triggered.connect(self.export_as_script_algorithm) self.mActionOpen.setIcon( QgsApplication.getThemeIcon('/mActionFileOpen.svg')) self.mActionSave.setIcon( QgsApplication.getThemeIcon('/mActionFileSave.svg')) self.mActionSaveAs.setIcon( QgsApplication.getThemeIcon('/mActionFileSaveAs.svg')) self.mActionSaveInProject.setIcon( QgsApplication.getThemeIcon('/mAddToProject.svg')) self.mActionZoomActual.setIcon( QgsApplication.getThemeIcon('/mActionZoomActual.svg')) self.mActionZoomIn.setIcon( QgsApplication.getThemeIcon('/mActionZoomIn.svg')) self.mActionZoomOut.setIcon( QgsApplication.getThemeIcon('/mActionZoomOut.svg')) self.mActionExportImage.setIcon( QgsApplication.getThemeIcon('/mActionSaveMapAsImage.svg')) self.mActionZoomToItems.setIcon( QgsApplication.getThemeIcon('/mActionZoomFullExtent.svg')) self.mActionExportPdf.setIcon( QgsApplication.getThemeIcon('/mActionSaveAsPDF.svg')) self.mActionExportSvg.setIcon( QgsApplication.getThemeIcon('/mActionSaveAsSVG.svg')) self.toolbutton_export_to_script.setIcon( QgsApplication.getThemeIcon('/mActionSaveAsPython.svg')) self.mActionEditHelp.setIcon( QgsApplication.getThemeIcon('/mActionEditHelpContent.svg')) self.mActionRun.setIcon( QgsApplication.getThemeIcon('/mActionStart.svg')) self.addDockWidget(Qt.LeftDockWidgetArea, self.propertiesDock) self.addDockWidget(Qt.LeftDockWidgetArea, self.inputsDock) self.addDockWidget(Qt.LeftDockWidgetArea, self.algorithmsDock) self.tabifyDockWidget(self.inputsDock, self.algorithmsDock) self.inputsDock.raise_() self.setWindowFlags(Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint | Qt.WindowCloseButtonHint) settings = QgsSettings() self.restoreState(settings.value("/Processing/stateModeler", QByteArray())) self.restoreGeometry(settings.value("/Processing/geometryModeler", QByteArray())) self.scene = ModelerScene(self, dialog=self) self.scene.setSceneRect(QRectF(0, 0, self.CANVAS_SIZE, self.CANVAS_SIZE)) self.view.setScene(self.scene) self.view.setAcceptDrops(True) self.view.ensureVisible(0, 0, 10, 10) self.view.scale(QgsApplication.desktop().logicalDpiX() / 96, QgsApplication.desktop().logicalDpiX() / 96) def _dragEnterEvent(event): if event.mimeData().hasText() or event.mimeData().hasFormat('application/x-vnd.qgis.qgis.algorithmid'): event.acceptProposedAction() else: event.ignore() def _dropEvent(event): def alg_dropped(algorithm_id, pos): alg = QgsApplication.processingRegistry().createAlgorithmById(algorithm_id) if alg is not None: self._addAlgorithm(alg, pos) else: assert False, algorithm_id def input_dropped(id, pos): if id in [param.id() for param in QgsApplication.instance().processingRegistry().parameterTypes()]: self.addInputOfType(itemId, pos) if event.mimeData().hasFormat('application/x-vnd.qgis.qgis.algorithmid'): data = event.mimeData().data('application/x-vnd.qgis.qgis.algorithmid') stream = QDataStream(data, QIODevice.ReadOnly) algorithm_id = stream.readQString() QTimer.singleShot(0, lambda id=algorithm_id, pos=self.view.mapToScene(event.pos()): alg_dropped(id, pos)) event.accept() elif event.mimeData().hasText(): itemId = event.mimeData().text() QTimer.singleShot(0, lambda id=itemId, pos=self.view.mapToScene(event.pos()): input_dropped(id, pos)) event.accept() else: event.ignore() def _dragMoveEvent(event): if event.mimeData().hasText() or event.mimeData().hasFormat('application/x-vnd.qgis.qgis.algorithmid'): event.accept() else: event.ignore() def _wheelEvent(event): self.view.setTransformationAnchor(QGraphicsView.AnchorUnderMouse) settings = QgsSettings() factor = settings.value('/qgis/zoom_favor', 2.0) # "Normal" mouse has an angle delta of 120, precision mouses provide data # faster, in smaller steps factor = 1.0 + (factor - 1.0) / 120.0 * abs(event.angleDelta().y()) if (event.modifiers() == Qt.ControlModifier): factor = 1.0 + (factor - 1.0) / 20.0 if event.angleDelta().y() < 0: factor = 1 / factor self.view.scale(factor, factor) def _enterEvent(e): QGraphicsView.enterEvent(self.view, e) self.view.viewport().setCursor(Qt.ArrowCursor) def _mouseReleaseEvent(e): QGraphicsView.mouseReleaseEvent(self.view, e) self.view.viewport().setCursor(Qt.ArrowCursor) def _mousePressEvent(e): if e.button() == Qt.MidButton: self.previousMousePos = e.pos() else: QGraphicsView.mousePressEvent(self.view, e) def _mouseMoveEvent(e): if e.buttons() == Qt.MidButton: offset = self.previousMousePos - e.pos() self.previousMousePos = e.pos() self.view.verticalScrollBar().setValue(self.view.verticalScrollBar().value() + offset.y()) self.view.horizontalScrollBar().setValue(self.view.horizontalScrollBar().value() + offset.x()) else: QGraphicsView.mouseMoveEvent(self.view, e) self.view.setDragMode(QGraphicsView.ScrollHandDrag) self.view.dragEnterEvent = _dragEnterEvent self.view.dropEvent = _dropEvent self.view.dragMoveEvent = _dragMoveEvent self.view.wheelEvent = _wheelEvent self.view.enterEvent = _enterEvent self.view.mousePressEvent = _mousePressEvent self.view.mouseMoveEvent = _mouseMoveEvent def _mimeDataInput(items): mimeData = QMimeData() text = items[0].data(0, Qt.UserRole) mimeData.setText(text) return mimeData self.inputsTree.mimeData = _mimeDataInput self.inputsTree.setDragDropMode(QTreeWidget.DragOnly) self.inputsTree.setDropIndicatorShown(True) self.algorithms_model = ModelerToolboxModel(self, QgsApplication.processingRegistry()) self.algorithmTree.setToolboxProxyModel(self.algorithms_model) self.algorithmTree.setDragDropMode(QTreeWidget.DragOnly) self.algorithmTree.setDropIndicatorShown(True) filters = QgsProcessingToolboxProxyModel.Filters(QgsProcessingToolboxProxyModel.FilterModeler) if ProcessingConfig.getSetting(ProcessingConfig.SHOW_ALGORITHMS_KNOWN_ISSUES): filters |= QgsProcessingToolboxProxyModel.FilterShowKnownIssues self.algorithmTree.setFilters(filters) if hasattr(self.searchBox, 'setPlaceholderText'): self.searchBox.setPlaceholderText(QCoreApplication.translate('ModelerDialog', 'Search…')) if hasattr(self.textName, 'setPlaceholderText'): self.textName.setPlaceholderText(self.tr('Enter model name here')) if hasattr(self.textGroup, 'setPlaceholderText'): self.textGroup.setPlaceholderText(self.tr('Enter group name here')) # Connect signals and slots self.inputsTree.doubleClicked.connect(self.addInput) self.searchBox.textChanged.connect(self.algorithmTree.setFilterString) self.algorithmTree.doubleClicked.connect(self.addAlgorithm) # Ctrl+= should also trigger a zoom in action ctrlEquals = QShortcut(QKeySequence("Ctrl+="), self) ctrlEquals.activated.connect(self.zoomIn) self.mActionOpen.triggered.connect(self.openModel) self.mActionSave.triggered.connect(self.save) self.mActionSaveAs.triggered.connect(self.saveAs) self.mActionSaveInProject.triggered.connect(self.saveInProject) self.mActionZoomIn.triggered.connect(self.zoomIn) self.mActionZoomOut.triggered.connect(self.zoomOut) self.mActionZoomActual.triggered.connect(self.zoomActual) self.mActionZoomToItems.triggered.connect(self.zoomToItems) self.mActionExportImage.triggered.connect(self.exportAsImage) self.mActionExportPdf.triggered.connect(self.exportAsPdf) self.mActionExportSvg.triggered.connect(self.exportAsSvg) #self.mActionExportPython.triggered.connect(self.exportAsPython) self.mActionEditHelp.triggered.connect(self.editHelp) self.mActionRun.triggered.connect(self.runModel) if model is not None: self.model = model.create() self.model.setSourceFilePath(model.sourceFilePath()) self.textGroup.setText(self.model.group()) self.textName.setText(self.model.displayName()) self.repaintModel() else: self.model = QgsProcessingModelAlgorithm() self.model.setProvider(QgsApplication.processingRegistry().providerById('model')) self.update_variables_gui() self.fillInputsTree() self.view.centerOn(0, 0) self.help = None self.hasChanged = False def closeEvent(self, evt): settings = QgsSettings() settings.setValue("/Processing/stateModeler", self.saveState()) settings.setValue("/Processing/geometryModeler", self.saveGeometry()) if self.hasChanged: ret = QMessageBox.question( self, self.tr('Save Model?'), self.tr('There are unsaved changes in this model. Do you want to keep those?'), QMessageBox.Save | QMessageBox.Cancel | QMessageBox.Discard, QMessageBox.Cancel) if ret == QMessageBox.Save: self.saveModel(False) evt.accept() elif ret == QMessageBox.Discard: evt.accept() else: evt.ignore() else: evt.accept() def editHelp(self): alg = self.model dlg = HelpEditionDialog(alg) dlg.exec_() if dlg.descriptions: self.model.setHelpContent(dlg.descriptions) self.hasChanged = True def update_variables_gui(self): variables_scope = QgsExpressionContextScope(self.tr('Model Variables')) for k, v in self.model.variables().items(): variables_scope.setVariable(k, v) variables_context = QgsExpressionContext() variables_context.appendScope(variables_scope) self.variables_editor.setContext(variables_context) self.variables_editor.setEditableScopeIndex(0) def variables_changed(self): self.model.setVariables(self.variables_editor.variablesInActiveScope()) def runModel(self): if len(self.model.childAlgorithms()) == 0: self.bar.pushMessage("", self.tr("Model doesn't contain any algorithm and/or parameter and can't be executed"), level=Qgis.Warning, duration=5) return dlg = AlgorithmDialog(self.model.create(), parent=iface.mainWindow()) dlg.exec_() def save(self): self.saveModel(False) def saveAs(self): self.saveModel(True) def saveInProject(self): if not self.can_save(): return self.model.setName(str(self.textName.text())) self.model.setGroup(str(self.textGroup.text())) self.model.setSourceFilePath(None) project_provider = QgsApplication.processingRegistry().providerById(PROJECT_PROVIDER_ID) project_provider.add_model(self.model) self.update_model.emit() self.bar.pushMessage("", self.tr("Model was saved inside current project"), level=Qgis.Success, duration=5) self.hasChanged = False QgsProject.instance().setDirty(True) def zoomIn(self): self.view.setTransformationAnchor(QGraphicsView.NoAnchor) point = self.view.mapToScene(QPoint(self.view.viewport().width() / 2, self.view.viewport().height() / 2)) settings = QgsSettings() factor = settings.value('/qgis/zoom_favor', 2.0) self.view.scale(factor, factor) self.view.centerOn(point) self.repaintModel() def zoomOut(self): self.view.setTransformationAnchor(QGraphicsView.NoAnchor) point = self.view.mapToScene(QPoint(self.view.viewport().width() / 2, self.view.viewport().height() / 2)) settings = QgsSettings() factor = settings.value('/qgis/zoom_favor', 2.0) factor = 1 / factor self.view.scale(factor, factor) self.view.centerOn(point) self.repaintModel() def zoomActual(self): point = self.view.mapToScene(QPoint(self.view.viewport().width() / 2, self.view.viewport().height() / 2)) self.view.resetTransform() self.view.scale(QgsApplication.desktop().logicalDpiX() / 96, QgsApplication.desktop().logicalDpiX() / 96) self.view.centerOn(point) def zoomToItems(self): totalRect = self.scene.itemsBoundingRect() totalRect.adjust(-10, -10, 10, 10) self.view.fitInView(totalRect, Qt.KeepAspectRatio) def exportAsImage(self): self.repaintModel(controls=False) filename, fileFilter = QFileDialog.getSaveFileName(self, self.tr('Save Model As Image'), '', self.tr('PNG files (*.png *.PNG)')) if not filename: return if not filename.lower().endswith('.png'): filename += '.png' totalRect = self.scene.itemsBoundingRect() totalRect.adjust(-10, -10, 10, 10) imgRect = QRectF(0, 0, totalRect.width(), totalRect.height()) img = QImage(totalRect.width(), totalRect.height(), QImage.Format_ARGB32_Premultiplied) img.fill(Qt.white) painter = QPainter() painter.setRenderHint(QPainter.Antialiasing) painter.begin(img) self.scene.render(painter, imgRect, totalRect) painter.end() img.save(filename) self.bar.pushMessage("", self.tr("Successfully exported model as image to <a href=\"{}\">{}</a>").format(QUrl.fromLocalFile(filename).toString(), QDir.toNativeSeparators(filename)), level=Qgis.Success, duration=5) self.repaintModel(controls=True) def exportAsPdf(self): self.repaintModel(controls=False) filename, fileFilter = QFileDialog.getSaveFileName(self, self.tr('Save Model As PDF'), '', self.tr('PDF files (*.pdf *.PDF)')) if not filename: return if not filename.lower().endswith('.pdf'): filename += '.pdf' totalRect = self.scene.itemsBoundingRect() totalRect.adjust(-10, -10, 10, 10) printerRect = QRectF(0, 0, totalRect.width(), totalRect.height()) printer = QPrinter() printer.setOutputFormat(QPrinter.PdfFormat) printer.setOutputFileName(filename) printer.setPaperSize(QSizeF(printerRect.width(), printerRect.height()), QPrinter.DevicePixel) printer.setFullPage(True) painter = QPainter(printer) self.scene.render(painter, printerRect, totalRect) painter.end() self.bar.pushMessage("", self.tr("Successfully exported model as PDF to <a href=\"{}\">{}</a>").format(QUrl.fromLocalFile(filename).toString(), QDir.toNativeSeparators(filename)), level=Qgis.Success, duration=5) self.repaintModel(controls=True) def exportAsSvg(self): self.repaintModel(controls=False) filename, fileFilter = QFileDialog.getSaveFileName(self, self.tr('Save Model As SVG'), '', self.tr('SVG files (*.svg *.SVG)')) if not filename: return if not filename.lower().endswith('.svg'): filename += '.svg' totalRect = self.scene.itemsBoundingRect() totalRect.adjust(-10, -10, 10, 10) svgRect = QRectF(0, 0, totalRect.width(), totalRect.height()) svg = QSvgGenerator() svg.setFileName(filename) svg.setSize(QSize(totalRect.width(), totalRect.height())) svg.setViewBox(svgRect) svg.setTitle(self.model.displayName()) painter = QPainter(svg) self.scene.render(painter, svgRect, totalRect) painter.end() self.bar.pushMessage("", self.tr("Successfully exported model as SVG to <a href=\"{}\">{}</a>").format(QUrl.fromLocalFile(filename).toString(), QDir.toNativeSeparators(filename)), level=Qgis.Success, duration=5) self.repaintModel(controls=True) def exportAsPython(self): filename, filter = QFileDialog.getSaveFileName(self, self.tr('Save Model As Python Script'), '', self.tr('Processing scripts (*.py *.PY)')) if not filename: return if not filename.lower().endswith('.py'): filename += '.py' text = self.model.asPythonCode() with codecs.open(filename, 'w', encoding='utf-8') as fout: fout.write(text) self.bar.pushMessage("", self.tr("Successfully exported model as python script to <a href=\"{}\">{}</a>").format(QUrl.fromLocalFile(filename).toString(), QDir.toNativeSeparators(filename)), level=Qgis.Success, duration=5) def can_save(self): """ Tests whether a model can be saved, or if it is not yet valid :return: bool """ if str(self.textName.text()).strip() == '': self.bar.pushWarning( "", self.tr('Please a enter model name before saving') ) return False return True def saveModel(self, saveAs): if not self.can_save(): return self.model.setName(str(self.textName.text())) self.model.setGroup(str(self.textGroup.text())) if self.model.sourceFilePath() and not saveAs: filename = self.model.sourceFilePath() else: filename, filter = QFileDialog.getSaveFileName(self, self.tr('Save Model'), ModelerUtils.modelsFolders()[0], self.tr('Processing models (*.model3 *.MODEL3)')) if filename: if not filename.endswith('.model3'): filename += '.model3' self.model.setSourceFilePath(filename) if filename: if not self.model.toFile(filename): if saveAs: QMessageBox.warning(self, self.tr('I/O error'), self.tr('Unable to save edits. Reason:\n {0}').format(str(sys.exc_info()[1]))) else: QMessageBox.warning(self, self.tr("Can't save model"), QCoreApplication.translate('QgsPluginInstallerInstallingDialog', ( "This model can't be saved in its original location (probably you do not " "have permission to do it). Please, use the 'Save as…' option.")) ) return self.update_model.emit() if saveAs: self.bar.pushMessage("", self.tr("Model was correctly saved to <a href=\"{}\">{}</a>").format(QUrl.fromLocalFile(filename).toString(), QDir.toNativeSeparators(filename)), level=Qgis.Success, duration=5) else: self.bar.pushMessage("", self.tr("Model was correctly saved"), level=Qgis.Success, duration=5) self.hasChanged = False def openModel(self): filename, selected_filter = QFileDialog.getOpenFileName(self, self.tr('Open Model'), ModelerUtils.modelsFolders()[0], self.tr('Processing models (*.model3 *.MODEL3)')) if filename: self.loadModel(filename) def loadModel(self, filename): alg = QgsProcessingModelAlgorithm() if alg.fromFile(filename): self.model = alg self.model.setProvider(QgsApplication.processingRegistry().providerById('model')) self.textGroup.setText(alg.group()) self.textName.setText(alg.name()) self.repaintModel() self.update_variables_gui() self.view.centerOn(0, 0) self.hasChanged = False else: QgsMessageLog.logMessage(self.tr('Could not load model {0}').format(filename), self.tr('Processing'), Qgis.Critical) QMessageBox.critical(self, self.tr('Open Model'), self.tr('The selected model could not be loaded.\n' 'See the log for more information.')) def repaintModel(self, controls=True): self.scene = ModelerScene(self, dialog=self) self.scene.setSceneRect(QRectF(0, 0, self.CANVAS_SIZE, self.CANVAS_SIZE)) self.scene.paintModel(self.model, controls) self.view.setScene(self.scene) def addInput(self): item = self.inputsTree.currentItem() param = item.data(0, Qt.UserRole) self.addInputOfType(param) def addInputOfType(self, paramType, pos=None): dlg = ModelerParameterDefinitionDialog(self.model, paramType) dlg.exec_() if dlg.param is not None: if pos is None: pos = self.getPositionForParameterItem() if isinstance(pos, QPoint): pos = QPointF(pos) component = QgsProcessingModelParameter(dlg.param.name()) component.setDescription(dlg.param.name()) component.setPosition(pos) self.model.addModelParameter(dlg.param, component) self.repaintModel() # self.view.ensureVisible(self.scene.getLastParameterItem()) self.hasChanged = True def getPositionForParameterItem(self): MARGIN = 20 BOX_WIDTH = 200 BOX_HEIGHT = 80 if len(self.model.parameterComponents()) > 0: maxX = max([i.position().x() for i in list(self.model.parameterComponents().values())]) newX = min(MARGIN + BOX_WIDTH + maxX, self.CANVAS_SIZE - BOX_WIDTH) else: newX = MARGIN + BOX_WIDTH / 2 return QPointF(newX, MARGIN + BOX_HEIGHT / 2) def fillInputsTree(self): icon = QIcon(os.path.join(pluginPath, 'images', 'input.svg')) parametersItem = QTreeWidgetItem() parametersItem.setText(0, self.tr('Parameters')) sortedParams = sorted(QgsApplication.instance().processingRegistry().parameterTypes(), key=lambda pt: pt.name()) for param in sortedParams: if param.flags() & QgsProcessingParameterType.ExposeToModeler: paramItem = QTreeWidgetItem() paramItem.setText(0, param.name()) paramItem.setData(0, Qt.UserRole, param.id()) paramItem.setIcon(0, icon) paramItem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled) paramItem.setToolTip(0, param.description()) parametersItem.addChild(paramItem) self.inputsTree.addTopLevelItem(parametersItem) parametersItem.setExpanded(True) def addAlgorithm(self): algorithm = self.algorithmTree.selectedAlgorithm() if algorithm is not None: alg = QgsApplication.processingRegistry().createAlgorithmById(algorithm.id()) self._addAlgorithm(alg) def _addAlgorithm(self, alg, pos=None): dlg = ModelerParametersDialog(alg, self.model) if dlg.exec_(): alg = dlg.createAlgorithm() if pos is None: alg.setPosition(self.getPositionForAlgorithmItem()) else: alg.setPosition(pos) from processing.modeler.ModelerGraphicItem import ModelerGraphicItem for i, out in enumerate(alg.modelOutputs()): alg.modelOutput(out).setPosition(alg.position() + QPointF(ModelerGraphicItem.BOX_WIDTH, (i + 1.5) * ModelerGraphicItem.BOX_HEIGHT)) self.model.addChildAlgorithm(alg) self.repaintModel() self.hasChanged = True def getPositionForAlgorithmItem(self): MARGIN = 20 BOX_WIDTH = 200 BOX_HEIGHT = 80 if self.model.childAlgorithms(): maxX = max([alg.position().x() for alg in list(self.model.childAlgorithms().values())]) maxY = max([alg.position().y() for alg in list(self.model.childAlgorithms().values())]) newX = min(MARGIN + BOX_WIDTH + maxX, self.CANVAS_SIZE - BOX_WIDTH) newY = min(MARGIN + BOX_HEIGHT + maxY, self.CANVAS_SIZE - BOX_HEIGHT) else: newX = MARGIN + BOX_WIDTH / 2 newY = MARGIN * 2 + BOX_HEIGHT + BOX_HEIGHT / 2 return QPointF(newX, newY) def export_as_script_algorithm(self): dlg = ScriptEditorDialog(None) dlg.editor.setText('\n'.join(self.model.asPythonCode(QgsProcessing.PythonQgsProcessingAlgorithmSubclass, 4))) dlg.show()
class ModelerParametersDialog(QDialog): def __init__(self, alg, model, algName=None, configuration=None): QDialog.__init__(self) self.setModal(True) self._alg = alg # The algorithm to define in this dialog. It is an instance of QgsProcessingAlgorithm self.model = model # The model this algorithm is going to be added to. It is an instance of QgsProcessingModelAlgorithm self.childId = algName # The name of the algorithm in the model, in case we are editing it and not defining it for the first time self.configuration = configuration self.context = createContext() self.widget_labels = {} class ContextGenerator(QgsProcessingContextGenerator): def __init__(self, context): super().__init__() self.processing_context = context def processingContext(self): return self.processing_context self.context_generator = ContextGenerator(self.context) self.setupUi() self.params = None settings = QgsSettings() self.restoreGeometry(settings.value("/Processing/modelParametersDialogGeometry", QByteArray())) def closeEvent(self, event): settings = QgsSettings() settings.setValue("/Processing/modelParametersDialogGeometry", self.saveGeometry()) super(ModelerParametersDialog, self).closeEvent(event) 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 getAvailableDependencies(self): # spellok if self.childId is None: dependent = [] else: dependent = list(self.model.dependentChildAlgorithms(self.childId)) dependent.append(self.childId) opts = [] for alg in list(self.model.childAlgorithms().values()): if alg.childId() not in dependent: opts.append(alg) return opts def getDependenciesPanel(self): return MultipleInputPanel([alg.description() for alg in self.getAvailableDependencies()]) # spellok def showAdvancedParametersClicked(self): self.showAdvanced = not self.showAdvanced if self.showAdvanced: self.advancedButton.setText(self.tr('Hide advanced parameters')) else: self.advancedButton.setText(self.tr('Show advanced parameters')) for param in self._alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: wrapper = self.wrappers[param.name()] if issubclass(wrapper.__class__, QgsProcessingModelerParameterWidget): wrapper.setVisible(self.showAdvanced) else: wrapper.widget.setVisible(self.showAdvanced) self.widget_labels[param.name()].setVisible(self.showAdvanced) def getAvailableValuesOfType(self, paramType, outTypes=[], dataTypes=[]): # upgrade paramType to list if paramType is None: paramType = [] elif not isinstance(paramType, (tuple, list)): paramType = [paramType] if outTypes is None: outTypes = [] elif not isinstance(outTypes, (tuple, list)): outTypes = [outTypes] return self.model.availableSourcesForChild(self.childId, [p.typeName() for p in paramType if issubclass(p, QgsProcessingParameterDefinition)], [o.typeName() for o in outTypes if issubclass(o, QgsProcessingOutputDefinition)], dataTypes) def resolveValueDescription(self, value): if isinstance(value, QgsProcessingModelChildParameterSource): if value.source() == QgsProcessingModelChildParameterSource.StaticValue: return value.staticValue() elif value.source() == QgsProcessingModelChildParameterSource.ModelParameter: return self.model.parameterDefinition(value.parameterName()).description() elif value.source() == QgsProcessingModelChildParameterSource.ChildOutput: alg = self.model.childAlgorithm(value.outputChildId()) return self.tr("'{0}' from algorithm '{1}'").format( alg.algorithm().outputDefinition(value.outputName()).description(), alg.description()) return value def setPreviousValues(self): if self.childId is not None: alg = self.model.childAlgorithm(self.childId) self.descriptionBox.setText(alg.description()) for param in alg.algorithm().parameterDefinitions(): if param.isDestination() or param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue value = None if param.name() in alg.parameterSources(): value = alg.parameterSources()[param.name()] if isinstance(value, list) and len(value) == 1: value = value[0] elif isinstance(value, list) and len(value) == 0: value = None wrapper = self.wrappers[param.name()] if issubclass(wrapper.__class__, QgsProcessingModelerParameterWidget): if value is None: value = QgsProcessingModelChildParameterSource.fromStaticValue(param.defaultValue()) wrapper.setWidgetValue(value) else: if value is None: value = param.defaultValue() if isinstance(value, QgsProcessingModelChildParameterSource) and value.source() == QgsProcessingModelChildParameterSource.StaticValue: value = value.staticValue() wrapper.setValue(value) for name, out in alg.modelOutputs().items(): if out.childOutputName() in self.valueItems: self.valueItems[out.childOutputName()].setText(out.name()) selected = [] dependencies = self.getAvailableDependencies() # spellok for idx, dependency in enumerate(dependencies): if dependency.childId() in alg.dependencies(): selected.append(idx) self.dependenciesPanel.setSelectedItems(selected) def createAlgorithm(self): alg = QgsProcessingModelChildAlgorithm(self._alg.id()) if not self.childId: alg.generateChildId(self.model) else: alg.setChildId(self.childId) alg.setDescription(self.descriptionBox.text()) if self.algorithmItem: alg.setConfiguration(self.algorithmItem.configuration()) self._alg = alg.algorithm().create(self.algorithmItem.configuration()) for param in self._alg.parameterDefinitions(): if param.isDestination() or param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue try: wrapper = self.wrappers[param.name()] if issubclass(wrapper.__class__, WidgetWrapper): val = wrapper.value() elif issubclass(wrapper.__class__, QgsProcessingModelerParameterWidget): val = wrapper.value() else: val = wrapper.parameterValue() except InvalidParameterValue: self.bar.pushMessage(self.tr("Error"), self.tr("Wrong or missing value for parameter '{}'").format(param.description()), level=Qgis.Warning) return None if isinstance(val, QgsProcessingModelChildParameterSource): val = [val] elif not (isinstance(val, list) and all( [isinstance(subval, QgsProcessingModelChildParameterSource) for subval in val])): val = [QgsProcessingModelChildParameterSource.fromStaticValue(val)] for subval in val: if (isinstance(subval, QgsProcessingModelChildParameterSource) and subval.source() == QgsProcessingModelChildParameterSource.StaticValue and not param.checkValueIsAcceptable(subval.staticValue())) \ or (subval is None and not param.flags() & QgsProcessingParameterDefinition.FlagOptional): self.bar.pushMessage(self.tr("Error"), self.tr("Wrong or missing value for parameter '{}'").format( param.description()), level=Qgis.Warning) return None alg.addParameterSources(param.name(), val) outputs = {} for dest in self._alg.destinationParameterDefinitions(): if not dest.flags() & QgsProcessingParameterDefinition.FlagHidden: name = self.valueItems[dest.name()].text() if name.strip() != '': output = QgsProcessingModelOutput(name, name) output.setChildId(alg.childId()) output.setChildOutputName(dest.name()) outputs[name] = output if dest.flags() & QgsProcessingParameterDefinition.FlagIsModelOutput: if dest.name() not in outputs: output = QgsProcessingModelOutput(dest.name(), dest.name()) output.setChildId(alg.childId()) output.setChildOutputName(dest.name()) outputs[dest.name()] = output alg.setModelOutputs(outputs) selectedOptions = self.dependenciesPanel.selectedoptions availableDependencies = self.getAvailableDependencies() # spellok dep_ids = [] for selected in selectedOptions: dep_ids.append(availableDependencies[selected].childId()) # spellok alg.setDependencies(dep_ids) #try: # self._alg.processBeforeAddingToModeler(alg, self.model) #except: # pass return alg def okPressed(self): alg = self.createAlgorithm() if alg is not None: self.accept() def cancelPressed(self): self.reject() def openHelp(self): algHelp = self._alg.helpUrl() if not algHelp: algHelp = QgsHelp.helpUrl("processing_algs/{}/{}.html#{}".format( self._alg.provider().helpId(), self._alg.groupId(), "{}{}".format(self._alg.provider().helpId(), self._alg.name()))).toString() if algHelp not in [None, ""]: webbrowser.open(algHelp)
class QvFormSimbMapificacio(QvFormBaseMapificacio): def __init__(self, llegenda, capa=None, amplada=500): super().__init__(llegenda, amplada) if capa is None: self.capa = llegenda.currentLayer() else: self.capa = capa self.info = None if not self.iniParams(): return self.setWindowTitle('Modificar mapa simbòlic ' + self.renderParams.tipusMapa.lower()) self.layout = QVBoxLayout() self.layout.setSpacing(14) self.setLayout(self.layout) self.color = QComboBox(self) self.color.setEditable(False) self.comboColors(self.color) self.contorn = QComboBox(self) self.contorn.setEditable(False) self.comboColors(self.contorn, mv.MAP_CONTORNS) self.color.currentIndexChanged.connect(self.canviaContorns) self.metode = QComboBox(self) self.metode.setEditable(False) if self.renderParams.numCategories > 1: self.metode.addItems(mv.MAP_METODES_MODIF.keys()) else: self.metode.addItems(mv.MAP_METODES.keys()) self.metode.setCurrentIndex(-1) self.metode.currentIndexChanged.connect(self.canviaMetode) self.nomIntervals = QLabel("Nombre d'intervals:", self) self.intervals = QSpinBox(self) self.intervals.setMinimum(min(2, self.renderParams.numCategories)) self.intervals.setMaximum(max(mv.MAP_MAX_CATEGORIES, self.renderParams.numCategories)) self.intervals.setSingleStep(1) self.intervals.setValue(4) if self.renderParams.tipusMapa == 'Àrees': self.intervals.setSuffix(" (depèn del mètode)") # self.intervals.valueChanged.connect(self.deselectValue) self.nomTamany = QLabel("Tamany cercle:", self) self.tamany = QSpinBox(self) self.tamany.setMinimum(1) self.tamany.setMaximum(12) self.tamany.setSingleStep(1) self.tamany.setValue(4) self.bInfo = QPushButton('Info') self.bInfo.clicked.connect(self.veureInfo) self.buttons = QDialogButtonBox() self.buttons.addButton(QDialogButtonBox.Ok) self.buttons.accepted.connect(self.accept) self.buttons.addButton(QDialogButtonBox.Cancel) self.buttons.rejected.connect(self.cancel) self.buttons.addButton(self.bInfo, QDialogButtonBox.ResetRole) self.gSimb = QGroupBox('Simbologia del mapa') self.lSimb = QFormLayout() self.lSimb.setSpacing(14) self.gSimb.setLayout(self.lSimb) self.lSimb.addRow('Color base:', self.color) self.lSimb.addRow('Color contorn:', self.contorn) if self.renderParams.tipusMapa == 'Àrees': self.lSimb.addRow('Mètode classificació:', self.metode) self.lSimb.addRow(self.nomIntervals, self.intervals) self.nomTamany.setVisible(False) self.tamany.setVisible(False) else: self.metode.setVisible(False) self.nomIntervals.setVisible(False) self.intervals.setVisible(False) self.lSimb.addRow(self.nomTamany, self.tamany) self.wInterval = [] for w in self.iniIntervals(): self.wInterval.append(w) self.gInter = self.grupIntervals() self.layout.addWidget(self.gSimb) if self.renderParams.tipusMapa == 'Àrees': self.layout.addWidget(self.gInter) self.layout.addWidget(self.buttons) self.valorsInicials() def iniParams(self): self.info = QgsExpressionContextUtils.layerScope(self.capa).variable(mv.MAP_ID) if self.info is None: return False self.renderParams = QvMapRendererParams.fromLayer(self.capa) if self.renderParams.msgError == '': self.custom = (self.renderParams.modeCategories == 'Personalitzat') return True else: self.msgInfo("No s'han pogut recuperar els paràmetres del mapa simbòlic\n\n" + "Error: " + self.renderParams.msgError) return False @pyqtSlot() def veureInfo(self): if self.info is not None: box = QMessageBox(self) box.setWindowTitle('Info del mapa simbòlic') txt = '<table width="600">' params = self.info.split('\n') for param in params: linea = param.strip() if linea.endswith(':'): linea += ' ---' txt += '<tr><td><nobr>· {}</nobr></td></tr>'.format(linea) txt += '</table>' box.setTextFormat(Qt.RichText) box.setText("Paràmetres d'agregació de dades:") box.setInformativeText(txt) box.setIcon(QMessageBox.Information) box.setStandardButtons(QMessageBox.Ok) box.setDefaultButton(QMessageBox.Ok) box.exec() def valorsInicials(self): self.color.setCurrentIndex(self.color.findText(self.renderParams.colorBase)) self.contorn.setCurrentIndex(self.contorn.findText(self.renderParams.colorContorn)) self.intervals.setValue(self.renderParams.numCategories) self.tamany.setValue(self.renderParams.increase) self.metode.setCurrentIndex(self.metode.findText(self.renderParams.modeCategories)) def valorsFinals(self): self.renderParams.colorBase = self.color.currentText() self.renderParams.colorContorn = self.contorn.currentText() self.renderParams.modeCategories = self.metode.currentText() self.renderParams.numCategories = self.intervals.value() self.renderParams.increase = self.tamany.value() if self.custom: self.renderParams.rangsCategories = [] for fila in self.wInterval: self.renderParams.rangsCategories.append((fila[0].text(), fila[2].text())) self.renderParams.numCategories = len(self.renderParams.rangsCategories) def txtRang(self, num): if type(num) == str: return num return QvApp().locale.toString(num, 'f', self.renderParams.numDecimals) def iniFilaInterval(self, iniValor, finValor): maxSizeB = 27 # validator = QDoubleValidator(self) # validator.setLocale(QvApp().locale) # validator.setNotation(QDoubleValidator.StandardNotation) # validator.setDecimals(5) validator = QvVerifNumero(self) ini = QLineEdit(self) ini.setText(self.txtRang(iniValor)) ini.setValidator(validator) sep = QLabel('-', self) fin = QLineEdit(self) fin.setText(self.txtRang(finValor)) fin.setValidator(validator) fin.editingFinished.connect(self.nouTall) add = QPushButton('+', self) add.setMaximumSize(maxSizeB, maxSizeB) add.setToolTip('Afegeix nou interval') add.clicked.connect(self.afegirFila) add.setFocusPolicy(Qt.NoFocus) rem = QPushButton('-', self) rem.setMaximumSize(maxSizeB, maxSizeB) rem.setToolTip('Esborra interval') rem.clicked.connect(self.eliminarFila) rem.setFocusPolicy(Qt.NoFocus) return [ini, sep, fin, add, rem] def iniIntervals(self): for cat in self.renderParams.rangsCategories: yield self.iniFilaInterval(cat.lowerValue(), cat.upperValue()) def grupIntervals(self): group = QGroupBox('Definició dels intervals') # group.setMinimumWidth(400) layout = QGridLayout() layout.setSpacing(10) # layout.setColumnMinimumWidth(4, 40) numFilas = len(self.wInterval) for fila, widgets in enumerate(self.wInterval): for col, w in enumerate(widgets): # Primera fila: solo + if fila == 0 and col > 3: w.setVisible(False) # # Ultima fila: no hay + ni - elif fila > 0 and fila == (numFilas - 1) and col > 2: w.setVisible(False) else: w.setVisible(True) # Valor inicial deshabilitado (menos 1a fila) if col == 0 and fila != 0: w.setDisabled(True) w.setProperty('Fila', fila) layout.addWidget(w, fila, col) group.setLayout(layout) return group def actGrupIntervals(self): self.intervals.setValue(len(self.wInterval)) self.setUpdatesEnabled(False) self.buttons.setVisible(False) self.gInter.setVisible(False) self.layout.removeWidget(self.buttons) self.layout.removeWidget(self.gInter) self.gInter.deleteLater() self.gInter = self.grupIntervals() self.layout.addWidget(self.gInter) self.layout.addWidget(self.buttons) self.gInter.setVisible(True) self.buttons.setVisible(True) self.adjustSize() self.setUpdatesEnabled(True) @pyqtSlot() def afegirFila(self): masFilas = (len(self.wInterval) < mv.MAP_MAX_CATEGORIES) if masFilas: f = self.sender().property('Fila') + 1 ini = self.wInterval[f][0] val = ini.text() ini.setText('') w = self.iniFilaInterval(val, '') self.wInterval.insert(f, w) self.actGrupIntervals() self.wInterval[f][2].setFocus() else: self.msgInfo("S'ha arribat al màxim d'intervals possibles") @pyqtSlot() def eliminarFila(self): f = self.sender().property('Fila') ini = self.wInterval[f][0] val = ini.text() del self.wInterval[f] ini = self.wInterval[f][0] ini.setText(val) self.actGrupIntervals() @pyqtSlot() def nouTall(self): w = self.sender() if w.isModified(): f = w.property('Fila') + 1 if f < len(self.wInterval): ini = self.wInterval[f][0] ini.setText(w.text()) w.setModified(False) @pyqtSlot() def canviaMetode(self): self.custom = (self.metode.currentText() == 'Personalitzat') if self.custom: self.intervals.setValue(len(self.wInterval)) self.intervals.setEnabled(not self.custom) self.gInter.setVisible(self.custom) self.adjustSize() # print('GSIMB -> Ancho:', self.gSimb.size().width(), '- Alto:', self.gSimb.size().height()) # print('FORM -> Ancho:', self.size().width(), '- Alto:', self.size().height()) @pyqtSlot() def canviaContorns(self): self.comboColors(self.contorn, mv.MAP_CONTORNS, mv.MAP_COLORS[self.color.currentText()], True) def leSelectFocus(self, wLineEdit): lon = len(wLineEdit.text()) if lon > 0: wLineEdit.setSelection(0, lon) wLineEdit.setFocus() def validaNum(self, wLineEdit): val = wLineEdit.validator() if val is None: return True res = val.validate(wLineEdit.text(), 0) if res[0] == QValidator.Acceptable: return True else: self.msgInfo("Cal introduir un nombre enter o amb decimals.\n" "Es farà servir la coma (,) per separar els decimals.\n" "I pels milers, opcionalment, el punt (.)") self.leSelectFocus(wLineEdit) return False def validaInterval(self, wLineEdit1, wLineEdit2): num1, _ = QvApp().locale.toFloat(wLineEdit1.text()) num2, _ = QvApp().locale.toFloat(wLineEdit2.text()) if num2 >= num1: return True else: self.msgInfo("El segon nombre de l'interval ha de ser major que el primer") self.leSelectFocus(wLineEdit2) return False def validaFila(self, fila): wLineEdit1 = fila[0] wLineEdit2 = fila[2] if not self.validaNum(wLineEdit1): return False if not self.validaNum(wLineEdit2): return False if not self.validaInterval(wLineEdit1, wLineEdit2): return False return True def valida(self): if self.custom: for fila in self.wInterval: if not self.validaFila(fila): return False return True def procesa(self): self.valorsFinals() try: mapRenderer = self.renderParams.mapRenderer(self.llegenda) if self.custom: self.renderParams.colorBase = mv.MAP_COLORS[self.renderParams.colorBase] self.renderParams.colorContorn = mv.MAP_CONTORNS[self.renderParams.colorContorn] self.renderer = mapRenderer.customRender(self.capa) else: self.renderParams.colorBase = mv.MAP_COLORS[self.renderParams.colorBase] if self.renderParams.colorContorn == 'Base': self.renderParams.colorContorn = self.renderParams.colorBase else: self.renderParams.colorContorn = mv.MAP_CONTORNS[self.renderParams.colorContorn] self.renderParams.modeCategories = \ mv.MAP_METODES_MODIF[self.renderParams.modeCategories] self.renderer = mapRenderer.calcRender(self.capa) if self.renderer is None: return "No s'ha pogut elaborar el mapa simbòlic" err = self.llegenda.saveStyleToGeoPackage(self.capa, mv.MAP_ID) if err != '': return "Hi ha hagut problemes al desar la simbologia\n({})".format(err) # self.llegenda.modificacioProjecte('mapModified') return '' except Exception as e: return "No s'ha pogut modificar el mapa simbòlic\n({})".format(str(e))
class ModelerParametersDialog(QDialog): ENTER_NAME = '[Enter name if this is a final result]' NOT_SELECTED = '[Not selected]' USE_MIN_COVERING_EXTENT = '[Use min covering extent]' def __init__(self, alg, model, algName=None): QDialog.__init__(self) self.setModal(True) #The algorithm to define in this dialog. It is an instance of GeoAlgorithm self._alg = alg #The resulting algorithm after the user clicks on OK. it is an instance of the container Algorithm class self.alg = None #The model this algorithm is going to be added to self.model = model #The name of the algorithm in the model, in case we are editing it and not defining it for the first time self._algName = algName self.setupUi() self.params = None def setupUi(self): self.labels = {} self.widgets = {} self.checkBoxes = {} self.showAdvanced = False self.valueItems = {} self.dependentItems = {} self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) tooltips = self._alg.getParameterDescriptions() self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(5) self.verticalLayout.setMargin(20) hLayout = QHBoxLayout() hLayout.setSpacing(5) hLayout.setMargin(0) descriptionLabel = QLabel(self.tr("Description")) self.descriptionBox = QLineEdit() self.descriptionBox.setText(self._alg.name) hLayout.addWidget(descriptionLabel) hLayout.addWidget(self.descriptionBox) self.verticalLayout.addLayout(hLayout) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.verticalLayout.addWidget(line) for param in self._alg.parameters: if param.isAdvanced: self.advancedButton = QPushButton() self.advancedButton.setText( self.tr('Show advanced parameters')) self.advancedButton.clicked.connect( self.showAdvancedParametersClicked) advancedButtonHLayout = QHBoxLayout() advancedButtonHLayout.addWidget(self.advancedButton) advancedButtonHLayout.addStretch() self.verticalLayout.addLayout(advancedButtonHLayout) break for param in self._alg.parameters: if param.hidden: continue desc = param.description if isinstance(param, ParameterExtent): desc += self.tr('(xmin, xmax, ymin, ymax)') if isinstance(param, ParameterPoint): desc += self.tr('(x, y)') label = QLabel(desc) self.labels[param.name] = label widget = self.getWidgetFromParameter(param) self.valueItems[param.name] = widget if param.name in tooltips.keys(): tooltip = tooltips[param.name] else: tooltip = param.description label.setToolTip(tooltip) widget.setToolTip(tooltip) if param.isAdvanced: label.setVisible(self.showAdvanced) widget.setVisible(self.showAdvanced) self.widgets[param.name] = widget self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(widget) for output in self._alg.outputs: if output.hidden: continue if isinstance(output, (OutputRaster, OutputVector, OutputTable, OutputHTML, OutputFile, OutputDirectory)): label = QLabel(output.description + '<' + output.__class__.__name__ + '>') item = QLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(item) self.valueItems[output.name] = item label = QLabel(' ') self.verticalLayout.addWidget(label) label = QLabel(self.tr('Parent algorithms')) self.dependenciesPanel = self.getDependenciesPanel() self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(self.dependenciesPanel) self.verticalLayout.addStretch(1000) self.setLayout(self.verticalLayout) self.setPreviousValues() self.setWindowTitle(self._alg.name) self.verticalLayout2 = QVBoxLayout() self.verticalLayout2.setSpacing(2) self.verticalLayout2.setMargin(0) self.tabWidget = QTabWidget() self.tabWidget.setMinimumWidth(300) self.paramPanel = QWidget() self.paramPanel.setLayout(self.verticalLayout) self.scrollArea = QScrollArea() self.scrollArea.setWidget(self.paramPanel) self.scrollArea.setWidgetResizable(True) self.tabWidget.addTab(self.scrollArea, self.tr('Parameters')) self.webView = QWebView() html = None url = None isText, help = self._alg.help() if help is not None: if isText: html = help else: url = QUrl(help) else: html = self.tr('<h2>Sorry, no help is available for this ' 'algorithm.</h2>') try: if html: self.webView.setHtml(html) elif url: self.webView.load(url) except: self.webView.setHtml( self.tr('<h2>Could not open help file :-( </h2>')) self.tabWidget.addTab(self.webView, 'Help') self.verticalLayout2.addWidget(self.tabWidget) self.verticalLayout2.addWidget(self.buttonBox) self.setLayout(self.verticalLayout2) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) QMetaObject.connectSlotsByName(self) def getAvailableDependencies(self): if self._algName is None: dependent = [] else: dependent = self.model.getDependentAlgorithms(self._algName) opts = [] for alg in self.model.algs.values(): if alg.name not in dependent: opts.append(alg) return opts def getDependenciesPanel(self): return MultipleInputPanel( [alg.algorithm.name for alg in self.getAvailableDependencies()]) def showAdvancedParametersClicked(self): self.showAdvanced = not self.showAdvanced if self.showAdvanced: self.advancedButton.setText(self.tr('Hide advanced parameters')) else: self.advancedButton.setText(self.tr('Show advanced parameters')) for param in self._alg.parameters: if param.isAdvanced: self.labels[param.name].setVisible(self.showAdvanced) self.widgets[param.name].setVisible(self.showAdvanced) def getAvailableValuesOfType(self, paramType, outType=None): values = [] inputs = self.model.inputs for i in inputs.values(): param = i.param if isinstance(param, paramType): values.append(ValueFromInput(param.name)) if outType is None: return values if self._algName is None: dependent = [] else: dependent = self.model.getDependentAlgorithms(self._algName) for alg in self.model.algs.values(): if alg.name not in dependent: for out in alg.algorithm.outputs: if isinstance(out, outType): values.append(ValueFromOutput(alg.name, out.name)) return values def resolveValueDescription(self, value): if isinstance(value, ValueFromInput): return self.model.inputs[value.name].param.description else: alg = self.model.algs[value.alg] return self.tr("'%s' from algorithm '%s'") % ( alg.algorithm.getOutputFromName( value.output).description, alg.description) def getWidgetFromParameter(self, param): if isinstance(param, ParameterRaster): item = QComboBox() layers = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) if param.optional: item.addItem(self.NOT_SELECTED, None) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterVector): item = QComboBox() layers = self.getAvailableValuesOfType(ParameterVector, OutputVector) if param.optional: item.addItem(self.NOT_SELECTED, None) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterTable): item = QComboBox() tables = self.getAvailableValuesOfType(ParameterTable, OutputTable) layers = self.getAvailableValuesOfType(ParameterVector, OutputVector) if param.optional: item.addItem(self.NOT_SELECTED, None) for table in tables: item.addItem(self.resolveValueDescription(table), table) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterBoolean): item = QComboBox() item.addItem('Yes') item.addItem('No') bools = self.getAvailableValuesOfType(ParameterBoolean, None) for b in bools: item.addItem(self.resolveValueDescription(b), b) if param.default: item.setCurrentIndex(0) else: item.setCurrentIndex(1) elif isinstance(param, ParameterSelection): item = QComboBox() item.addItems(param.options) item.setCurrentIndex(param.default or 0) elif isinstance(param, ParameterFixedTable): item = FixedTablePanel(param) elif isinstance(param, ParameterRange): item = RangePanel(param) elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType( ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType( ParameterRaster, OutputRaster) opts = [] for opt in options: opts.append(self.resolveValueDescription(opt)) item = MultipleInputPanel(opts) elif isinstance(param, ParameterString): strings = self.getAvailableValuesOfType(ParameterString, OutputString) options = [(self.resolveValueDescription(s), s) for s in strings] if param.multiline: item = MultilineTextPanel(options) item.setText(unicode(param.default or "")) else: item = QComboBox() item.setEditable(True) for desc, val in options: item.addItem(desc, val) item.setEditText(unicode(param.default or "")) elif isinstance(param, ParameterTableField): item = QComboBox() item.setEditable(True) fields = self.getAvailableValuesOfType(ParameterTableField, None) for f in fields: item.addItem(self.resolveValueDescription(f), f) elif isinstance(param, ParameterNumber): item = QComboBox() item.setEditable(True) numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) for n in numbers: item.addItem(self.resolveValueDescription(n), n) item.setEditText(unicode(param.default)) elif isinstance(param, ParameterCrs): item = CrsSelectionPanel(param.default) elif isinstance(param, ParameterExtent): item = QComboBox() item.setEditable(True) extents = self.getAvailableValuesOfType(ParameterExtent, OutputExtent) if self.canUseAutoExtent(): item.addItem(self.USE_MIN_COVERING_EXTENT, None) for ex in extents: item.addItem(self.resolveValueDescription(ex), ex) if not self.canUseAutoExtent(): item.setEditText(unicode(param.default)) elif isinstance(param, ParameterPoint): item = QComboBox() item.setEditable(True) points = self.getAvailableValuesOfType(ParameterPoint) for p in points: item.addItem(self.resolveValueDescription(p), p) item.setEditText(unicode(param.default)) elif isinstance(param, ParameterFile): item = QComboBox() item.setEditable(True) files = self.getAvailableValuesOfType(ParameterFile, OutputFile) for f in files: item.addItem(self.resolveValueDescription(f), f) elif isinstance(param, ParameterGeometryPredicate): item = GeometryPredicateSelectionPanel(param.enabledPredicates) else: item = QLineEdit() try: item.setText(unicode(param.default)) except: pass return item def canUseAutoExtent(self): for param in self._alg.parameters: if isinstance( param, (ParameterRaster, ParameterVector, ParameterMultipleInput)): return True return False def setTableContent(self): params = self._alg.parameters outputs = self._alg.outputs visibleParams = [p for p in params if not p.hidden] visibleOutputs = [p for o in outputs if not o.hidden] self.tableWidget.setRowCount(len(visibleParams) + len(visibleOutputs)) for i, param in visibleParams: item = QTableWidgetItem(param.description) item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setItem(i, 0, item) item = self.getWidgetFromParameter(param) self.valueItems[param.name] = item self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22) for i, output in visibleOutputs: item = QTableWidgetItem(output.description + '<' + output.__module__.split('.')[-1] + '>') item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setItem(i, 0, item) item = QLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.valueItems[output.name] = item self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22) def setComboBoxValue(self, combo, value, param): if isinstance(value, list): value = value[0] items = [combo.itemData(i) for i in range(combo.count())] try: idx = items.index(value) combo.setCurrentIndex(idx) return except ValueError: pass if combo.isEditable(): if value is not None: combo.setEditText(unicode(value)) elif isinstance(param, ParameterSelection): combo.setCurrentIndex(int(value)) elif isinstance(param, ParameterBoolean): if value: combo.setCurrentIndex(0) else: combo.setCurrentIndex(1) def setPreviousValues(self): if self._algName is not None: alg = self.model.algs[self._algName] self.descriptionBox.setText(alg.description) for param in alg.algorithm.parameters: if param.hidden: continue widget = self.valueItems[param.name] if param.name in alg.params: value = alg.params[param.name] else: value = param.default if isinstance( param, (ParameterRaster, ParameterVector, ParameterTable, ParameterTableField, ParameterSelection, ParameterNumber, ParameterBoolean, ParameterExtent, ParameterFile, ParameterPoint)): self.setComboBoxValue(widget, value, param) elif isinstance(param, ParameterString): if param.multiline: widget.setValue(value) else: self.setComboBoxValue(widget, value, param) elif isinstance(param, ParameterCrs): widget.setAuthId(value) elif isinstance(param, ParameterFixedTable): pass # TODO! elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType( ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType( ParameterRaster, OutputRaster) selected = [] for i, opt in enumerate(options): if opt in value: selected.append(i) widget.setSelectedItems(selected) elif isinstance(param, ParameterGeometryPredicate): widget.setValue(value) for name, out in alg.outputs.iteritems(): widget = self.valueItems[name].setText(out.description) selected = [] dependencies = self.getAvailableDependencies() for idx, dependency in enumerate(dependencies): if dependency.name in alg.dependencies: selected.append(idx) self.dependenciesPanel.setSelectedItems(selected) def createAlgorithm(self): alg = Algorithm(self._alg.commandLineName()) alg.setName(self.model) alg.description = self.descriptionBox.text() params = self._alg.parameters outputs = self._alg.outputs for param in params: if param.hidden: continue if not self.setParamValue(alg, param, self.valueItems[param.name]): return None for output in outputs: if not output.hidden: name = unicode(self.valueItems[output.name].text()) if name.strip( ) != '' and name != ModelerParametersDialog.ENTER_NAME: alg.outputs[output.name] = ModelerOutput(name) selectedOptions = self.dependenciesPanel.selectedoptions availableDependencies = self.getAvailableDependencies() for selected in selectedOptions: alg.dependencies.append(availableDependencies[selected].name) return alg def setParamValueLayerOrTable(self, alg, param, widget): idx = widget.currentIndex() if idx < 0: return False else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamTableFieldValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = unicode(widget.currentText()).strip() if s == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = s return True else: alg.params[param.name] = widget.itemData(widget.currentIndex()) return True def setParamStringValue(self, alg, param, widget): if param.multiline: value = widget.getValue() option = widget.getOption() if option == MultilineTextPanel.USE_TEXT: if value == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = value else: alg.params[param.name] = value else: idx = widget.findText(widget.currentText()) if idx < 0: value = widget.currentText().strip() if value == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = value else: alg.params[param.name] = widget.itemData(widget.currentIndex()) return True def setParamFileValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: value = widget.currentText() else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamNumberValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = widget.currentText().strip() if s: try: value = float(s) except: return False elif param.optional: value = None else: return False else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamExtentValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = unicode(widget.currentText()).strip() if s: try: tokens = s.split(',') if len(tokens) != 4: return False for token in tokens: float(token) except: return False elif param.optional: s = None else: return False alg.params[param.name] = [s] else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamPointValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = unicode(widget.currentText()).strip() if s: try: tokens = s.split(',') if len(tokens) != 2: return False for token in tokens: float(token) except: return False elif param.optional: s = None else: return False alg.params[param.name] = [s] else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamValue(self, alg, param, widget): if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable)): return self.setParamValueLayerOrTable(alg, param, widget) elif isinstance(param, ParameterBoolean): if widget.currentIndex() < 2: value = widget.currentIndex() == 0 else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True elif isinstance(param, ParameterString): return self.setParamStringValue(alg, param, widget) elif isinstance(param, ParameterNumber): return self.setParamNumberValue(alg, param, widget) elif isinstance(param, ParameterExtent): return self.setParamExtentValue(alg, param, widget) elif isinstance(param, ParameterPoint): return self.setParamPointValue(alg, param, widget) elif isinstance(param, ParameterFile): return self.setParamFileValue(alg, param, widget) elif isinstance(param, ParameterSelection): alg.params[param.name] = widget.currentIndex() return True elif isinstance(param, ParameterRange): alg.params[param.name] = widget.getValue() return True elif isinstance(param, ParameterCrs): authid = widget.getValue() if authid is None and not param.optional: return False alg.params[param.name] = authid return True elif isinstance(param, ParameterFixedTable): table = widget.table if not bool(table) and not param.optional: return False alg.params[param.name] = ParameterFixedTable.tableToString(table) return True elif isinstance(param, ParameterTableField): return self.setParamTableFieldValue(alg, param, widget) elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType( ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType( ParameterRaster, OutputRaster) values = [options[i] for i in widget.selectedoptions] if len(values) == 0 and not param.optional: return False alg.params[param.name] = values return True elif isinstance(param, ParameterGeometryPredicate): alg.params[param.name] = widget.value() return True else: alg.params[param.name] = unicode(widget.text()) return True def okPressed(self): self.alg = self.createAlgorithm() if self.alg is not None: self.close() else: QMessageBox.warning(self, self.tr('Unable to add algorithm'), self.tr('Wrong or missing parameter values')) def cancelPressed(self): self.alg = None self.close()
class Params(QObject): ''' collection of parameters, single parameters can be added by setting them as attributes. supports dict-like access of the parameters by name Attributes ---------- changed : pyqtSignal fired on change of any parameter in collection ''' changed = pyqtSignal() HELP_PATH = os.path.join(settings.HELP_PATH, 'params') def __init__(self, parent: QObject = None, button_label: str = 'Editieren', editable: bool = True, help_text: str = '', help_file: str = None): ''' Parameters ---------- parent : QObject, optional ui element to draw the parameters in, can't be drawn if parent is None, defaults to no parent button_label : parent, optional label of the edit button in the parameter preview, defaults to 'Editieren' editable : bool, optional parameters are editable. if not, no edit button will be shown in the preview, defaults to editable parameters help_file : str, optional json-style text file containing help texts for each parameter, will be automatically created if not existing, defaults to no help file help_text : str, optional the general help displayed in the parameter dialog, overrides the description in the help file if given, defaults no help text ''' super().__init__() self._params = OrderedDict() self._elements = [] self.button_label = button_label #self._dependencies = [] self.parent = parent self.dialog = None self.editable = editable self.layout = QVBoxLayout() self.layout.setSpacing(5) self.help_dict = { 'tooltip': 'Parameter editieren' } if help_file: self.help_file = help_file if os.path.exists(help_file) else \ os.path.join(self.HELP_PATH, help_file) if os.path.exists(self.help_file): with open(self.help_file) as json_file: self.help_dict = yaml.safe_load(json_file) # passed help text overrides the one from file if help_text or 'beschreibung' not in self.help_dict: self.help_dict['beschreibung'] = help_text def add(self, element: Union[Param, Seperator, Title, QLayoutItem], name: str = ''): ''' add an element (parameter or style element) elements will be rendered in order of addition Parameters ---------- element : object parameter or style element to add name : str, optional name of parameter to add, parameter can be adressed by that name. ignored when element is not a parameter, defaults to no name ''' self._elements.append(element) if name and isinstance(element, Param): self._params[name] = element if element.input: if element.help_text or name not in self.help_dict: self.help_dict[name] = element.help_text else: element.help_text = self.help_dict[name] @property def params(self) -> List[Param]: ''' Returns ------- list a list of all parameters ''' return self._params.values() def show(self, *args, title: str = 'Parameter einstellen', scrollable: bool = False): ''' render parameters and elements in parent Parameters ---------- args : optional arguments for appending parameter layout to parent (like x, y if parent is grid layout) title : str, optional title of the parameter dialog, defaults to 'Parameter einstellen' scrollable : bool, optional a scrollbar will be added to both preview and dialog if True, recommended if there are a lot of parameters, defaults to not scrollable ''' if self.parent is None: raise Exception("can't render Params object with no parent set") # Debug: function to automatically write a help file with all params # with empty texts, should be removed in production if (settings.DEBUG and getattr(self, 'help_file', None) and not os.path.exists(self.help_file)): if not os.path.exists(self.HELP_PATH): os.mkdir(self.HELP_PATH) with open(self.help_file, 'w') as json_file: json.dump(self.help_dict, json_file, indent=4) self.dialog = ParamsDialog(parent=None, help_text=self.help_dict['beschreibung'], title=title) self.parent.addLayout(self.layout, *args) if scrollable: frame = QFrame() scroll_area = QScrollArea() layout = QVBoxLayout() layout.setSpacing(5) frame.setLayout(layout) scroll_area.setWidget(frame) scroll_area.setWidgetResizable(True) scroll_area.setFixedHeight(400) self.layout.addWidget(scroll_area) else: layout = self.layout for element in self._elements: if isinstance(element, QLayoutItem): layout.addItem(element) # overview elif not getattr(element, 'hide_in_overview', None): element.draw(layout) self.dialog.draw(element) if not self.editable: return row = QHBoxLayout() button = QPushButton(self.button_label) icon = QIcon(os.path.join(settings.IMAGE_PATH, 'iconset_mob', '20190619_iconset_mob_edit_1.png')) button.setIcon(icon) tool_tip = self.help_dict.get('tooltip', None) button.setToolTip(tool_tip) row.addItem( QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum)) row.addWidget(button) self.layout.addItem( QSpacerItem(10, 10, QSizePolicy.Fixed, QSizePolicy.Minimum)) self.layout.addLayout(row) button.clicked.connect(self.show_dialog) def get(self, name: str) -> Param: ''' get a parameter by name Returns ------- Param the parameter matching the name or None if not found ''' return self._params.get(name, None) def close(self): ''' close rendered parameters ''' if self.dialog: clear_layout(self.dialog.layout) del(self.dialog) clear_layout(self.layout) def show_dialog(self): ''' show the dialog to edit parameters ''' confirmed = self.dialog.exec_() if confirmed: has_changed = False for param in self.params: if not param.input or param.value == param.input.value: continue param.value = param.input.value has_changed = True if has_changed: self.changed.emit() else: # reset inputs for param in self.params: if param.input: param.input.value = param.value def __getattr__(self, name): param = self._params.get(name, None) if param: return param return self.__dict__.get(name, None) def __setattr__(self, name, value): if isinstance(value, Param): self.add(value, name) else: self.__dict__[name] = value def __getitem__(self, key): return self._params.get(key, None) def __setitem__(self, key, value): self.add(value, key)
def show(self, *args, title: str = 'Parameter einstellen', scrollable: bool = False): ''' render parameters and elements in parent Parameters ---------- args : optional arguments for appending parameter layout to parent (like x, y if parent is grid layout) title : str, optional title of the parameter dialog, defaults to 'Parameter einstellen' scrollable : bool, optional a scrollbar will be added to both preview and dialog if True, recommended if there are a lot of parameters, defaults to not scrollable ''' if self.parent is None: raise Exception("can't render Params object with no parent set") # Debug: function to automatically write a help file with all params # with empty texts, should be removed in production if (settings.DEBUG and getattr(self, 'help_file', None) and not os.path.exists(self.help_file)): if not os.path.exists(self.HELP_PATH): os.mkdir(self.HELP_PATH) with open(self.help_file, 'w') as json_file: json.dump(self.help_dict, json_file, indent=4) self.dialog = ParamsDialog(parent=None, help_text=self.help_dict['beschreibung'], title=title) self.parent.addLayout(self.layout, *args) if scrollable: frame = QFrame() scroll_area = QScrollArea() layout = QVBoxLayout() layout.setSpacing(5) frame.setLayout(layout) scroll_area.setWidget(frame) scroll_area.setWidgetResizable(True) scroll_area.setFixedHeight(400) self.layout.addWidget(scroll_area) else: layout = self.layout for element in self._elements: if isinstance(element, QLayoutItem): layout.addItem(element) # overview elif not getattr(element, 'hide_in_overview', None): element.draw(layout) self.dialog.draw(element) if not self.editable: return row = QHBoxLayout() button = QPushButton(self.button_label) icon = QIcon(os.path.join(settings.IMAGE_PATH, 'iconset_mob', '20190619_iconset_mob_edit_1.png')) button.setIcon(icon) tool_tip = self.help_dict.get('tooltip', None) button.setToolTip(tool_tip) row.addItem( QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum)) row.addWidget(button) self.layout.addItem( QSpacerItem(10, 10, QSizePolicy.Fixed, QSizePolicy.Minimum)) self.layout.addLayout(row) button.clicked.connect(self.show_dialog)
class QvPrint(QWidget): """Una classe del tipus QWidget que servirà per imprimir un area determinada. El widget conté un botó per imprimir, un per tornar a posicionar l'area d'impresió, i un comboBox per escollir l'escala. """ def __init__(self, project, canvas, poligon, parent=None): """Inicialització de la clase: Arguments: project {QgsProject().instance()} -- El projecte actiu canvas {QgsVectorLayer} -- El canvas sobre el que es coloca la rubberband. poligon {QgsPoligon} -- Poligon inicial. A revisar. """ # We inherit our parent's properties and methods. QWidget.__init__(self, parent) self.parent = parent # Creating a memory layer to draw later the rubberband. estatDirtybit = self.parent.canvisPendents self.layer = QgsVectorLayer('Point?crs=epsg:23031', "Capa temporal d'impressió", "memory") project.addMapLayer(self.layer, False) # We store safely the parameters as class variables. self.canvas = canvas self.project = project self.poligon = poligon # Offset inicial del rectangle d'impressió- TODO self.incX = 100 self.incY = 150 # Semafor per deixar fix el rectangle un cop fet click. self.pucMoure = True # Diccionari d'escales i proporcions que fixen el tamany del rectangle en pantalla. # Podria fer-se millor, pero Practicality beats Purity... self.dictEscales = { '100': 20, '200': 40, '250': 45, '500': 100, '1000': 200, '2000': 400, '2500': 450, '5000': 1000, '10000': 2000, '20000': 4000, '25000': 4500, '50000': 10000 } # We instanciate de PointTool tool, to wait for clicks # After that, we assign the tool to the canvas. rp = PointTool(self, self.canvas) canvas.setMapTool(rp) self.setupUI() self.rubberband = QgsRubberBand(self.canvas) self.rubberband.setColor(QColor(0, 0, 0, 50)) self.rubberband.setWidth(4) self.canvas.xyCoordinates.connect(self.mocMouse) self.pintarRectangle(self.poligon) self.rubberband.hide() self.parent.setDirtyBit(estatDirtybit) def setupUI(self): self.layout = QVBoxLayout(self) self.setLayout(self.layout) self.layout.setContentsMargins(10, 20, 10, 20) self.layout.setSpacing(14) # self.layout.setAlignment(Qt.AlignTop) self.layoutTitol = QHBoxLayout() self.lblTitol = QLabel("Títol: ") self.leTitol = QLineEdit(self) self.leTitol.setText(self.parent.titolProjecte) self.layoutTitol.addWidget(self.lblTitol) self.layoutTitol.addWidget(self.leTitol) self.cbOrientacio = QComboBox(self) self.cbOrientacio.addItems(['Vertical', 'Horitzontal']) self.cbOrientacio.SelectedItem = "Vertical" self.cbOrientacio.setCurrentIndex(1) self.cbOrientacio.currentTextChanged.connect(self.canviOrientacio) self.lblCBOrientacio = QLabel("Orientació: ") self.layoutCBOrientacio = QHBoxLayout() self.layoutCBOrientacio.addWidget(self.lblCBOrientacio) self.layoutCBOrientacio.addWidget(self.cbOrientacio) self.combo = QComboBox(self) llistaEscales = [key for key in self.dictEscales] self.combo.addItems(llistaEscales) self.combo.currentTextChanged.connect(self.canviEscala) self.lblEscales = QLabel("Escales") self.layEscales = QHBoxLayout() self.layEscales.addWidget(self.lblEscales) self.layEscales.addWidget(self.combo) self.cbMida = QComboBox(self) self.cbMida.addItems(['A0', 'A1', 'A2', 'A3', 'A4']) self.cbMida.currentTextChanged.connect(self.canviEscala) self.cbMida.setCurrentIndex(4) self.lblCBmida = QLabel("Paper: ") self.layoutCBmida = QHBoxLayout() self.layoutCBmida.addWidget(self.lblCBmida) self.layoutCBmida.addWidget(self.cbMida) self.boto = QvPushButton(text='Generar PDF', destacat=True, parent=self) self.boto.clicked.connect(self.printPlanol) self.boto.setFixedWidth(220) self.boto2 = QvPushButton(text='Emmarcar zona a imprimir', parent=self) self.boto2.clicked.connect(self.potsMoure) self.boto2.setFixedWidth(220) self.nota = QLabel( "NOTA: Alguns navegadors web alteren l'escala d'impressió dels PDFs. Per màxima exactitud imprimiu des de l'Adobe Acrobat." ) styleheetLabel = ''' QLabel { color: grey; }''' self.nota.setStyleSheet(styleheetLabel) self.nota.setMaximumWidth(200) self.nota.setWordWrap(True) self.layout.addLayout(self.layoutTitol) self.layout.addLayout(self.layEscales) self.layout.addLayout(self.layoutCBmida) self.layout.addLayout(self.layoutCBOrientacio) self.layout.addWidget(self.boto2) self.layout.addWidget(self.boto) self.layout.addWidget(self.nota) # self.layout.addWidget(self.wFormat) # self.layout.addWidget(self.rbVertical) # self.layout.addWidget(self.rbHoritzontal) self.layout.addStretch() def potsMoure(self): # self.canvas.scene().removeItem(self.rubberband) self.pucMoure = True def canviEscala(self): self.pucMoure = True escala = int(self.dictEscales[self.combo.currentText()]) mida = self.cbMida.currentText() if mida == 'A3': escala *= math.sqrt(2) elif mida == 'A2': escala *= math.sqrt(2) * 2 elif mida == 'A1': escala *= math.sqrt(2) * 3 elif mida == 'A0': escala *= math.sqrt(2) * 4 if self.cbOrientacio.SelectedItem == "Horitzontal": self.incX = escala self.incY = escala * 1.5 else: self.incX = escala * 1.5 self.incY = escala def canviOrientacio(self): self.pucMoure = True if self.cbOrientacio.SelectedItem == "Vertical": self.cbOrientacio.SelectedItem = "Horitzontal" else: self.cbOrientacio.SelectedItem = "Vertical" self.incX, self.incY = self.incY, self.incX def canvasClickat(self): #??? print('Clickat, si') def mocMouse(self, p): if not self.isVisible(): self.rubberband.hide() self.pucMoure elif self.pucMoure: if self.canvas.rotation() == 0: self.posXY = [p.x() + self.incX / 2, p.y() + self.incY / 2] self.rubberband.movePoint( 0, QgsPointXY(p.x() + self.incX, p.y() + self.incY), 0) self.rubberband.movePoint(1, QgsPointXY(p.x() + self.incX, p.y()), 0) self.rubberband.movePoint(2, QgsPointXY(p.x(), p.y()), 0) self.rubberband.movePoint(3, QgsPointXY(p.x(), p.y() + self.incY), 0) self.rubberband.movePoint( 4, QgsPointXY(p.x() + self.incX, p.y() + self.incY), 0) else: alpha = math.radians(self.canvas.rotation()) beta = math.atan(self.incY / self.incX) d = math.sqrt(self.incX**2 + self.incY**2) self.posXY = [(2 * p.x() + d * math.cos(alpha + beta)) / 2, (2 * p.y() + d * math.sin(alpha + beta)) / 2] self.rubberband.movePoint( 0, QgsPointXY(p.x() + d * math.cos(alpha + beta), p.y() + d * math.sin(alpha + beta)), 0) self.rubberband.movePoint( 1, QgsPointXY(p.x() + self.incX * math.cos(alpha), p.y() + self.incX * math.sin(alpha)), 0) self.rubberband.movePoint(2, QgsPointXY(p.x(), p.y()), 0) self.rubberband.movePoint( 3, QgsPointXY( p.x() + self.incY * math.cos(math.radians(90 + 45)), p.y() + self.incY * math.sin(math.radians(90 + 45))), 0) self.rubberband.movePoint( 4, QgsPointXY(p.x() + d * math.cos(alpha + beta), p.y() + d * math.sin(alpha + beta)), 0) self.rubberband.show() def pintarRectangle(self, poligon): points = [ QgsPointXY(0, 0), QgsPointXY(0, 10), QgsPointXY(10, 10), QgsPointXY(0, 10), QgsPointXY(0, 0) ] poligono = QgsGeometry.fromRect(self.poligon) self.rubberband.setToGeometry(poligono, self.layer) def printPlanol(self): # # if self.checkRotacio.checkState(): # rotacio=44.75 # else: # rotacio=0 rotacio = self.canvas.rotation() if self.cbOrientacio.currentText() == "Vertical": if self.cbMida.currentText() == "A4": self.plantillaMapa = pathPlantilles + 'plantillaMapa.qpt' elif self.cbMida.currentText() == "A3": self.plantillaMapa = pathPlantilles + 'plantillaMapaA3.qpt' elif self.cbMida.currentText() == "A2": self.plantillaMapa = pathPlantilles + 'plantillaMapaA2.qpt' elif self.cbMida.currentText() == "A1": self.plantillaMapa = pathPlantilles + 'plantillaMapaA1.qpt' elif self.cbMida.currentText() == "A0": self.plantillaMapa = pathPlantilles + 'plantillaMapaA0.qpt' else: if self.cbMida.currentText() == "A4": self.plantillaMapa = pathPlantilles + 'plantillaMapaH.qpt' elif self.cbMida.currentText() == "A3": self.plantillaMapa = pathPlantilles + 'plantillaMapaA3H.qpt' elif self.cbMida.currentText() == "A2": self.plantillaMapa = pathPlantilles + 'plantillaMapaA2H.qpt' elif self.cbMida.currentText() == "A1": self.plantillaMapa = pathPlantilles + 'plantillaMapaA1H.qpt' elif self.cbMida.currentText() == "A0": self.plantillaMapa = pathPlantilles + 'plantillaMapaA0H.qpt' t = time.localtime() timestamp = time.strftime('%d-%b-%Y_%H%M%S', t) sortida = tempdir + 'sortida_' + timestamp self.imprimirPlanol(self.posXY[0], self.posXY[1], int(self.combo.currentText()), rotacio, self.cbMida.currentText(), self.plantillaMapa, sortida, 'PDF') QvApp().logRegistre('Impressió: ' + self.combo.currentText()) def imprimirPlanol(self, x, y, escala, rotacion, midaPagina, templateFile, fitxerSortida, tipusSortida): tInicial = time.time() template = QFile(templateFile) doc = QDomDocument() doc.setContent(template, False) layout = QgsLayout(self.project) # page=QgsLayoutItemPage(layout) # page.setPageSize(midaPagina) # layout.pageCollection().addPage(page) # layout.initializeDefaults() # p=layout.pageCollection().pages()[0] # p.setPageSize(midaPagina) context = QgsReadWriteContext() [items, ok] = layout.loadFromTemplate(doc, context) # p=layout.pageCollection().pages()[0] # p.setPageSize(midaPagina) if ok: refMap = layout.referenceMap() titol = layout.itemById('idNomMapa') dataMapa = layout.itemById('idData') if self.leTitol.text() != '': titol.setText(self.leTitol.text()) #comentat pk peta else: titol.setText('') try: t = time.localtime() dataMapa.setText(strftime('%b-%d-%Y %H:%M', t)) except: pass rect = refMap.extent() vector = QgsVector(x - rect.center().x(), y - rect.center().y()) rect += vector refMap.setExtent(rect) refMap.setScale(escala) refMap.setMapRotation(rotacion) #Depenent del tipus de sortida... exporter = QgsLayoutExporter(layout) # image_settings = exporter.ImageExportSettings() # image_settings.dpi = 30 # result = exporter.exportToImage('d:/dropbox/qpic/preview.png', image_settings) # imatge = QPixmap('d:/dropbox/qpic/preview.png') # self.ui.lblImatgeResultat.setPixmap(imatge) if tipusSortida == 'PDF': settings = QgsLayoutExporter.PdfExportSettings() settings.dpi = 300 settings.exportMetadata = False # fitxerSortida='d:/sortida_'+timestamp+'.PDF' fitxerSortida += '.PDF' result = exporter.exportToPdf( fitxerSortida, settings) #Cal desar el resultat (???) print(fitxerSortida) if tipusSortida == 'PNG': settings = QgsLayoutExporter.ImageExportSettings() settings.dpi = 300 # fitxerSortida='d:/sortida_'+timestamp+'.PNG' fitxerSortida += '.PNG' result = exporter.exportToImage( fitxerSortida, settings) #Cal desar el resultat (???) #Obra el document si està marcat checkObrirResultat QDesktopServices().openUrl(QUrl(fitxerSortida)) segonsEmprats = round(time.time() - tInicial, 1) #??? layersTemporals = self.project.mapLayersByName( "Capa temporal d'impressió") estatDirtybit = self.parent.canvisPendents for layer in layersTemporals: self.project.removeMapLayer(layer.id()) self.parent.setDirtyBit(estatDirtybit) def oculta(self): #Eliminem la capa temporal estatDirtybit = self.parent.canvisPendents layersTemporals = self.project.mapLayersByName( "Capa temporal d'impressió") for layer in layersTemporals: self.project.removeMapLayer(layer.id()) self.parent.setDirtyBit(estatDirtybit)
class QvDocumentacio(QDialog): comencaCarrega = pyqtSignal() acabaCarrega = pyqtSignal() '''Diàleg que mostra la documentació de la carpeta de documentació definida a configuracioQvista Mostra una TreeView amb els documents, i delega en el sistema la tasca d'obrir-los''' def __init__(self, parent: QWidget = None): super().__init__(parent) self.setMinimumSize(750, 500) #Layout principal. Tot aquí self.layout = QVBoxLayout(self) #Layout de la capçalera self.layoutCapcalera = QHBoxLayout() self.lblTitol = QLabel(' Documentació') self.layoutCapcalera.addWidget(self.lblTitol) self.qModel = ElMeuModel(self) self.lblExplicacio = QLabel() if os.path.isdir(carpetaDocuments): self.lblExplicacio.setText( 'Esteu visualitzant la documentació corporativa completa') rootPath = self.qModel.setRootPath(carpetaDocuments) else: self.lblExplicacio.setText( 'No teniu accés a la documentació corporativa. Esteu visualitzant una còpia local que pot no estar actualitzada.' ) rootPath = self.qModel.setRootPath(carpetaDocumentsLocal) self.treeView = QTreeView(self) self.treeView.setModel(self.qModel) self.treeView.setRootIndex(rootPath) self.treeView.clicked.connect(self.clicat) self.treeView.doubleClicked.connect(self.obrir) self.layoutBotonera = QHBoxLayout() self.layoutBotonera.addStretch() self.botoObrir = QvPushButton('Obrir', destacat=True) self.botoObrir.setEnabled(False) self.botoObrir.clicked.connect(self.obrir) self.layoutBotonera.addWidget(self.botoObrir) self.botoDescarregar = QvPushButton('Descarregar') self.botoDescarregar.setEnabled(False) self.botoDescarregar.clicked.connect(self.desar) self.layoutBotonera.addWidget(self.botoDescarregar) self.botoSortir = QvPushButton('Sortir') self.botoSortir.clicked.connect(self.close) self.layoutBotonera.addWidget(self.botoSortir) self.layout.addLayout(self.layoutCapcalera) self.layout.addWidget(self.lblExplicacio) self.layout.addWidget(self.treeView) self.layout.addLayout(self.layoutBotonera) self.formata() def formata(self): self.setWindowFlags(Qt.Window | Qt.FramelessWindowHint) self.layout.setAlignment(Qt.AlignCenter) self.lblTitol.setStyleSheet( 'background-color: %s; color: %s; border: 0px' % (QvConstants.COLORFOSCHTML, QvConstants.COLORBLANCHTML)) self.lblTitol.setFont(QvConstants.FONTCAPCALERES) self.lblTitol.setFixedHeight(40) self.lblExplicacio.setWordWrap(True) self.lblExplicacio.setStyleSheet( f'color: {QvConstants.COLORFOSCHTML}; margin: 20px 20px 0px 20px') for i in range(1, 4): self.treeView.header().hideSection(i) self.treeView.setHeaderHidden(True) self.treeView.adjustSize() self.treeView.setAnimated(True) self.treeView.setStyleSheet( 'QTreeView{margin: 20px 2px 0px 20px; border: none;}') self.layout.setContentsMargins(0, 0, 0, 0) self.layout.setSpacing(0) self.layoutBotonera.setContentsMargins(10, 10, 10, 10) def clicat(self, index: int): path = self.qModel.fileInfo(index).absoluteFilePath() self.index = index if os.path.isfile(path): self.botoObrir.setEnabled(True) self.botoDescarregar.setEnabled(True) else: self.botoObrir.setEnabled(False) self.botoDescarregar.setEnabled(True) def obrir(self): path = self.qModel.fileInfo(self.index).absoluteFilePath() if os.path.isfile(path): self.comencaCarrega.emit() if '.html' in path: self.visor = QvVisorHTML(path, 'Vídeo de documentació') self.visor.setZoomFactor(1) self.visor.show() else: os.startfile(path) time.sleep(1) self.acabaCarrega.emit() def desar(self): path = self.qModel.fileInfo(self.index).absoluteFilePath() if os.path.isfile(path): nfile, _ = QFileDialog.getSaveFileName( None, 'Desar arxiu', os.path.join(QvMemoria().getDirectoriDesar(), Path(path).name)) if nfile != '': shutil.copy(path, nfile) else: nomCarpeta = Path(path).name nfile = str( QFileDialog.getExistingDirectory(self, "Select Directory")) if nfile != '': shutil.copytree(path, os.path.join(nfile, nomCarpeta)) def mousePressEvent(self, event): self.oldPos = event.globalPos() def mouseMoveEvent(self, event): delta = QPoint(event.globalPos() - self.oldPos) self.move(self.x() + delta.x(), self.y() + delta.y()) self.oldPos = event.globalPos() def keyPressEvent(self, event): if event.key() == Qt.Key_Escape: self.close() if event.key() == Qt.Key_Return: self.obrir()
class ModelerParametersDialog(QDialog): ENTER_NAME = '[Enter name if this is a final result]' NOT_SELECTED = '[Not selected]' USE_MIN_COVERING_EXTENT = '[Use min covering extent]' def __init__(self, alg, model, algName=None): QDialog.__init__(self) self.setModal(True) # The algorithm to define in this dialog. It is an instance of GeoAlgorithm self._alg = alg # The resulting algorithm after the user clicks on OK. it is an instance of the container Algorithm class self.alg = None # The model this algorithm is going to be added to self.model = model # The name of the algorithm in the model, in case we are editing it and not defining it for the first time self._algName = algName self.setupUi() self.params = None def setupUi(self): self.labels = {} self.widgets = {} self.checkBoxes = {} self.showAdvanced = False self.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.name) hLayout.addWidget(descriptionLabel) hLayout.addWidget(self.descriptionBox) self.verticalLayout.addLayout(hLayout) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.verticalLayout.addWidget(line) for param in self._alg.parameters: if param.isAdvanced: self.advancedButton = QPushButton() self.advancedButton.setText( self.tr('Show advanced parameters')) self.advancedButton.clicked.connect( self.showAdvancedParametersClicked) advancedButtonHLayout = QHBoxLayout() advancedButtonHLayout.addWidget(self.advancedButton) advancedButtonHLayout.addStretch() self.verticalLayout.addLayout(advancedButtonHLayout) break for param in self._alg.parameters: if param.hidden: continue desc = param.description if isinstance(param, ParameterExtent): desc += self.tr('(xmin, xmax, ymin, ymax)') if isinstance(param, ParameterPoint): desc += self.tr('(x, y)') 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.name) self.verticalLayout2 = QVBoxLayout() self.verticalLayout2.setSpacing(2) self.verticalLayout2.setMargin(0) self.tabWidget = QTabWidget() self.tabWidget.setMinimumWidth(300) self.paramPanel = QWidget() self.paramPanel.setLayout(self.verticalLayout) self.scrollArea = QScrollArea() self.scrollArea.setWidget(self.paramPanel) self.scrollArea.setWidgetResizable(True) self.tabWidget.addTab(self.scrollArea, self.tr('Parameters')) self.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 requestFinished(self): """Change the webview HTML content""" reply = self.sender() if reply.error() != QNetworkReply.NoError: html = self.tr( '<h2>No help available for this algorithm</h2><p>{}</p>'. format(reply.errorString())) else: html = str(reply.readAll()) reply.deleteLater() self.txtHelp.setHtml(html) def getAvailableDependencies(self): # spellok if self._algName is None: dependent = [] else: dependent = self.model.getDependentAlgorithms(self._algName) opts = [] for alg in list(self.model.algs.values()): if alg.name not in dependent: opts.append(alg) return opts def getDependenciesPanel(self): return MultipleInputPanel([ alg.description for alg in self.getAvailableDependencies() ]) # spellok def showAdvancedParametersClicked(self): self.showAdvanced = not self.showAdvanced if self.showAdvanced: self.advancedButton.setText(self.tr('Hide advanced parameters')) else: self.advancedButton.setText(self.tr('Show advanced parameters')) for param in self._alg.parameters: if param.isAdvanced: self.labels[param.name].setVisible(self.showAdvanced) self.widgets[param.name].setVisible(self.showAdvanced) def getAvailableValuesOfType(self, paramType, outType=None, dataType=None): # upgrade paramType to list if type(paramType) is not list: paramType = [paramType] values = [] inputs = self.model.inputs for i in list(inputs.values()): param = i.param for t in paramType: if isinstance(param, t): if dataType is not None: if param.datatype in dataType: values.append(ValueFromInput(param.name)) else: values.append(ValueFromInput(param.name)) break if outType is None: return values if self._algName is None: dependent = [] else: dependent = self.model.getDependentAlgorithms(self._algName) for alg in list(self.model.algs.values()): if alg.name not in dependent: for out in alg.algorithm.outputs: if isinstance(out, outType): if dataType is not None and out.datatype in dataType: values.append(ValueFromOutput(alg.name, out.name)) else: values.append(ValueFromOutput(alg.name, out.name)) return values def resolveValueDescription(self, value): if isinstance(value, ValueFromInput): return self.model.inputs[value.name].param.description else: alg = self.model.algs[value.alg] return self.tr("'%s' from algorithm '%s'") % ( alg.algorithm.getOutputFromName( value.output).description, alg.description) def setPreviousValues(self): if self._algName is not None: alg = self.model.algs[self._algName] self.descriptionBox.setText(alg.description) for param in alg.algorithm.parameters: if param.hidden: continue if param.name in alg.params: value = alg.params[param.name] else: value = param.default self.wrappers[param.name].setValue(value) for name, out in list(alg.outputs.items()): self.valueItems[name].setText(out.description) selected = [] dependencies = self.getAvailableDependencies() # spellok for idx, dependency in enumerate(dependencies): if dependency.name in alg.dependencies: selected.append(idx) self.dependenciesPanel.setSelectedItems(selected) def createAlgorithm(self): alg = Algorithm(self._alg.commandLineName()) alg.setName(self.model) alg.description = self.descriptionBox.text() params = self._alg.parameters outputs = self._alg.outputs for param in params: if param.hidden: continue if not self.setParamValue(alg, param, self.wrappers[param.name]): self.bar.pushMessage( "Error", "Wrong or missing value for parameter '%s'" % param.description, level=QgsMessageBar.WARNING) return None for output in outputs: if not output.hidden: name = str(self.valueItems[output.name].text()) if name.strip( ) != '' and name != ModelerParametersDialog.ENTER_NAME: alg.outputs[output.name] = ModelerOutput(name) selectedOptions = self.dependenciesPanel.selectedoptions availableDependencies = self.getAvailableDependencies() # spellok for selected in selectedOptions: alg.dependencies.append( availableDependencies[selected].name) # spellok self._alg.processBeforeAddingToModeler(alg, self.model) return alg def setParamValue(self, alg, param, wrapper): try: if wrapper.widget: value = wrapper.value() alg.params[param.name] = value return True except InvalidParameterValue: return False def okPressed(self): self.alg = self.createAlgorithm() if self.alg is not None: self.close() def cancelPressed(self): self.alg = None self.close()
def populate_details(self): self.bundleWidgets = [] client = PlanetClient.getInstance() permissions = [img[PERMISSIONS] for img in self.images] item_bundles = client.bundles_for_item_type_and_permissions( self.item_type, permissions=permissions) default = default_bundles.get(self.item_type, []) def _center(obj): hlayout = QHBoxLayout() hlayout.addStretch() hlayout.addWidget(obj) hlayout.addStretch() return hlayout layout = QVBoxLayout() layout.setMargin(0) layout.setSpacing(20) layout.addLayout(_center(QLabel("<b>RECTIFIED ASSETS</b>"))) gridlayout = QGridLayout() gridlayout.setMargin(0) assets = PlanetClient.getInstance().asset_types_for_item_type( self.item_type) assets_and_bands = {} for a in assets: if "bands" in a: assets_and_bands[a["id"]] = len(a["bands"]) widgets = {} i = 0 for bundleid, bundle in item_bundles.items(): if bundle["rectification"] == "orthorectified": w = PlanetOrderBundleWidget(bundleid, bundle, self.item_type) gridlayout.addWidget(w, i // 2, i % 2) w.setSelected(False) widgets[bundleid] = w w.selectionChanged.connect( partial(self._bundle_selection_changed, w)) self.bundleWidgets.append(w) i += 1 selected = False for defaultid in default: for bundleid, w in widgets.items(): if defaultid == bundleid: w.setSelected(True) selected = True break if selected: break layout.addLayout(gridlayout) self.labelUnrectified = QLabel("<b>UNRECTIFIED ASSETS</b>") layout.addLayout(_center(self.labelUnrectified)) self.widgetUnrectified = QWidget() gridlayoutUnrect = QGridLayout() gridlayoutUnrect.setMargin(0) i = 0 for bundleid, bundle in item_bundles.items(): if bundle["rectification"] != "orthorectified": w = PlanetOrderBundleWidget(bundleid, bundle, self.item_type) gridlayoutUnrect.addWidget(w, i // 2, i % 2) w.selectionChanged.connect( partial(self._bundle_selection_changed, w)) self.bundleWidgets.append(w) i += 1 self.widgetUnrectified.setLayout(gridlayoutUnrect) layout.addWidget(self.widgetUnrectified) self.labelMore = QLabel('<a href="#">+ Show More</a>') self.labelMore.setOpenExternalLinks(False) self.labelMore.setTextInteractionFlags(Qt.LinksAccessibleByMouse) self.labelMore.linkActivated.connect(self._showMoreClicked) layout.addLayout(_center(self.labelMore)) self.widgetUnrectified.hide() self.labelUnrectified.hide() self.widgetDetails.setLayout(layout)
class CommitDialog(QDialog): def __init__(self, repo, layername, _message = "", parent = None): super(CommitDialog, self).__init__(parent) self.repo = repo self.branch = None self.layername = layername self._message = _message or suggestedMessage self.message = None self.initGui() def initGui(self): self.setObjectName("CommitDialog") self.resize(600, 250) self.setWindowTitle("Syncronize layer to repository branch") self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(2) self.verticalLayout.setMargin(5) self.branchLabel = QLabel("Branch") self.verticalLayout.addWidget(self.branchLabel) self.branchCombo = QComboBox() self.branches = [] branches = self.repo.branches() for branch in branches: trees = self.repo.trees(branch) if self.layername in trees: self.branches.append(branch) self.branchCombo.addItems(self.branches) try: idx = self.branches.index("master") except: idx = 0 self.branchCombo.setCurrentIndex(idx) self.verticalLayout.addWidget(self.branchCombo) self.msgLabel = QLabel("Message to describe this update") self.verticalLayout.addWidget(self.msgLabel) self.text = QPlainTextEdit() self.text.setPlainText(self._message) self.verticalLayout.addWidget(self.text) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok) self.verticalLayout.addWidget(self.buttonBox) self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(bool(self.branches)) self.setLayout(self.verticalLayout) self.buttonBox.accepted.connect(self.okPressed) self.text.setFocus() def okPressed(self): self.branch = self.branchCombo.currentText() self.message = self.text.toPlainText() or datetime.now().strftime("%Y-%m-%d %H_%M_%S") self.close()
class ModelerParametersDialog(QDialog): ENTER_NAME = '[Enter name if this is a final result]' NOT_SELECTED = '[Not selected]' USE_MIN_COVERING_EXTENT = '[Use min covering extent]' def __init__(self, alg, model, algName=None): QDialog.__init__(self) self.setModal(True) #The algorithm to define in this dialog. It is an instance of GeoAlgorithm self._alg = alg #The resulting algorithm after the user clicks on OK. it is an instance of the container Algorithm class self.alg = None #The model this algorithm is going to be added to self.model = model #The name of the algorithm in the model, in case we are editing it and not defining it for the first time self._algName = algName self.setupUi() self.params = None def setupUi(self): self.labels = {} self.widgets = {} self.checkBoxes = {} self.showAdvanced = False self.valueItems = {} self.dependentItems = {} self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok) tooltips = self._alg.getParameterDescriptions() self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(5) self.verticalLayout.setMargin(20) hLayout = QHBoxLayout() hLayout.setSpacing(5) hLayout.setMargin(0) descriptionLabel = QLabel(self.tr("Description")) self.descriptionBox = QLineEdit() self.descriptionBox.setText(self._alg.name) hLayout.addWidget(descriptionLabel) hLayout.addWidget(self.descriptionBox) self.verticalLayout.addLayout(hLayout) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.verticalLayout.addWidget(line) for param in self._alg.parameters: if param.isAdvanced: self.advancedButton = QPushButton() self.advancedButton.setText(self.tr('Show advanced parameters')) self.advancedButton.clicked.connect( self.showAdvancedParametersClicked) advancedButtonHLayout = QHBoxLayout() advancedButtonHLayout.addWidget(self.advancedButton) advancedButtonHLayout.addStretch() self.verticalLayout.addLayout(advancedButtonHLayout) break for param in self._alg.parameters: if param.hidden: continue desc = param.description if isinstance(param, ParameterExtent): desc += self.tr('(xmin, xmax, ymin, ymax)') if isinstance(param, ParameterPoint): desc += self.tr('(x, y)') label = QLabel(desc) self.labels[param.name] = label widget = self.getWidgetFromParameter(param) self.valueItems[param.name] = widget if param.name in tooltips.keys(): tooltip = tooltips[param.name] else: tooltip = param.description label.setToolTip(tooltip) widget.setToolTip(tooltip) if param.isAdvanced: label.setVisible(self.showAdvanced) widget.setVisible(self.showAdvanced) self.widgets[param.name] = widget self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(widget) for output in self._alg.outputs: if output.hidden: continue if isinstance(output, (OutputRaster, OutputVector, OutputTable, OutputHTML, OutputFile, OutputDirectory)): label = QLabel(output.description + '<' + output.__class__.__name__ + '>') item = QLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(item) self.valueItems[output.name] = item label = QLabel(' ') self.verticalLayout.addWidget(label) label = QLabel(self.tr('Parent algorithms')) self.dependenciesPanel = self.getDependenciesPanel() self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(self.dependenciesPanel) self.verticalLayout.addStretch(1000) self.setLayout(self.verticalLayout) self.setPreviousValues() self.setWindowTitle(self._alg.name) self.verticalLayout2 = QVBoxLayout() self.verticalLayout2.setSpacing(2) self.verticalLayout2.setMargin(0) self.tabWidget = QTabWidget() self.tabWidget.setMinimumWidth(300) self.paramPanel = QWidget() self.paramPanel.setLayout(self.verticalLayout) self.scrollArea = QScrollArea() self.scrollArea.setWidget(self.paramPanel) self.scrollArea.setWidgetResizable(True) self.tabWidget.addTab(self.scrollArea, self.tr('Parameters')) self.webView = QWebView() html = None url = None isText, help = self._alg.help() if help is not None: if isText: html = help else: url = QUrl(help) else: html = self.tr('<h2>Sorry, no help is available for this ' 'algorithm.</h2>') try: if html: self.webView.setHtml(html) elif url: self.webView.load(url) except: self.webView.setHtml(self.tr('<h2>Could not open help file :-( </h2>')) self.tabWidget.addTab(self.webView, 'Help') self.verticalLayout2.addWidget(self.tabWidget) self.verticalLayout2.addWidget(self.buttonBox) self.setLayout(self.verticalLayout2) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) QMetaObject.connectSlotsByName(self) def getAvailableDependencies(self): if self._algName is None: dependent = [] else: dependent = self.model.getDependentAlgorithms(self._algName) opts = [] for alg in self.model.algs.values(): if alg.name not in dependent: opts.append(alg) return opts def getDependenciesPanel(self): return MultipleInputPanel([alg.algorithm.name for alg in self.getAvailableDependencies()]) def showAdvancedParametersClicked(self): self.showAdvanced = not self.showAdvanced if self.showAdvanced: self.advancedButton.setText(self.tr('Hide advanced parameters')) else: self.advancedButton.setText(self.tr('Show advanced parameters')) for param in self._alg.parameters: if param.isAdvanced: self.labels[param.name].setVisible(self.showAdvanced) self.widgets[param.name].setVisible(self.showAdvanced) def getAvailableValuesOfType(self, paramType, outType=None): values = [] inputs = self.model.inputs for i in inputs.values(): param = i.param if isinstance(param, paramType): values.append(ValueFromInput(param.name)) if outType is None: return values if self._algName is None: dependent = [] else: dependent = self.model.getDependentAlgorithms(self._algName) for alg in self.model.algs.values(): if alg.name not in dependent: for out in alg.algorithm.outputs: if isinstance(out, outType): values.append(ValueFromOutput(alg.name, out.name)) return values def resolveValueDescription(self, value): if isinstance(value, ValueFromInput): return self.model.inputs[value.name].param.description else: alg = self.model.algs[value.alg] return self.tr("'%s' from algorithm '%s'") % (alg.algorithm.getOutputFromName(value.output).description, alg.description) def getWidgetFromParameter(self, param): if isinstance(param, ParameterRaster): item = QComboBox() layers = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) if param.optional: item.addItem(self.NOT_SELECTED, None) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterVector): item = QComboBox() layers = self.getAvailableValuesOfType(ParameterVector, OutputVector) if param.optional: item.addItem(self.NOT_SELECTED, None) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterTable): item = QComboBox() tables = self.getAvailableValuesOfType(ParameterTable, OutputTable) layers = self.getAvailableValuesOfType(ParameterVector, OutputVector) if param.optional: item.addItem(self.NOT_SELECTED, None) for table in tables: item.addItem(self.resolveValueDescription(table), table) for layer in layers: item.addItem(self.resolveValueDescription(layer), layer) elif isinstance(param, ParameterBoolean): item = QComboBox() item.addItem('Yes') item.addItem('No') bools = self.getAvailableValuesOfType(ParameterBoolean, None) for b in bools: item.addItem(self.resolveValueDescription(b), b) if param.default: item.setCurrentIndex(0) else: item.setCurrentIndex(1) elif isinstance(param, ParameterSelection): item = QComboBox() item.addItems(param.options) item.setCurrentIndex(param.default or 1) elif isinstance(param, ParameterFixedTable): item = FixedTablePanel(param) elif isinstance(param, ParameterRange): item = RangePanel(param) elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType(ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) opts = [] for opt in options: opts.append(self.resolveValueDescription(opt)) item = MultipleInputPanel(opts) elif isinstance(param, ParameterString): strings = self.getAvailableValuesOfType(ParameterString, OutputString) options = [(self.resolveValueDescription(s), s) for s in strings] if param.multiline: item = MultilineTextPanel(options) item.setText(unicode(param.default or "")) else: item = QComboBox() item.setEditable(True) for desc, val in options: item.addItem(desc, val) item.setEditText(unicode(param.default or "")) elif isinstance(param, ParameterTableField): item = QComboBox() item.setEditable(True) fields = self.getAvailableValuesOfType(ParameterTableField, None) for f in fields: item.addItem(self.resolveValueDescription(f), f) elif isinstance(param, ParameterNumber): item = QComboBox() item.setEditable(True) numbers = self.getAvailableValuesOfType(ParameterNumber, OutputNumber) for n in numbers: item.addItem(self.resolveValueDescription(n), n) item.setEditText(unicode(param.default)) elif isinstance(param, ParameterCrs): item = CrsSelectionPanel(param.default) elif isinstance(param, ParameterExtent): item = QComboBox() item.setEditable(True) extents = self.getAvailableValuesOfType(ParameterExtent, OutputExtent) if self.canUseAutoExtent(): item.addItem(self.USE_MIN_COVERING_EXTENT, None) for ex in extents: item.addItem(self.resolveValueDescription(ex), ex) if not self.canUseAutoExtent(): item.setEditText(unicode(param.default)) elif isinstance(param, ParameterPoint): item = QComboBox() item.setEditable(True) points = self.getAvailableValuesOfType(ParameterPoint) for p in points: item.addItem(self.resolveValueDescription(p), p) item.setEditText(unicode(param.default)) elif isinstance(param, ParameterFile): item = QComboBox() item.setEditable(True) files = self.getAvailableValuesOfType(ParameterFile, OutputFile) for f in files: item.addItem(self.resolveValueDescription(f), f) elif isinstance(param, ParameterGeometryPredicate): item = GeometryPredicateSelectionPanel(param.enabledPredicates) else: item = QLineEdit() try: item.setText(unicode(param.default)) except: pass return item def canUseAutoExtent(self): for param in self._alg.parameters: if isinstance(param, (ParameterRaster, ParameterVector, ParameterMultipleInput)): return True return False def setTableContent(self): params = self._alg.parameters outputs = self._alg.outputs visibleParams = [p for p in params if not p.hidden] visibleOutputs = [p for o in outputs if not o.hidden] self.tableWidget.setRowCount(len(visibleParams) + len(visibleOutputs)) for i, param in visibleParams: item = QTableWidgetItem(param.description) item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setItem(i, 0, item) item = self.getWidgetFromParameter(param) self.valueItems[param.name] = item self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22) for i, output in visibleOutputs: item = QTableWidgetItem(output.description + '<' + output.__module__.split('.')[-1] + '>') item.setFlags(Qt.ItemIsEnabled) self.tableWidget.setItem(i, 0, item) item = QLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(ModelerParametersDialog.ENTER_NAME) self.valueItems[output.name] = item self.tableWidget.setCellWidget(i, 1, item) self.tableWidget.setRowHeight(i, 22) def setComboBoxValue(self, combo, value, param): if isinstance(value, list): value = value[0] items = [combo.itemData(i) for i in range(combo.count())] try: idx = items.index(value) combo.setCurrentIndex(idx) return except ValueError: pass if combo.isEditable(): if value is not None: combo.setEditText(unicode(value)) elif isinstance(param, ParameterSelection): combo.setCurrentIndex(int(value)) elif isinstance(param, ParameterBoolean): if value: combo.setCurrentIndex(0) else: combo.setCurrentIndex(1) def setPreviousValues(self): if self._algName is not None: alg = self.model.algs[self._algName] self.descriptionBox.setText(alg.description) for param in alg.algorithm.parameters: if param.hidden: continue widget = self.valueItems[param.name] if param.name in alg.params: value = alg.params[param.name] else: value = param.default if isinstance(param, ( ParameterRaster, ParameterVector, ParameterTable, ParameterTableField, ParameterSelection, ParameterNumber, ParameterBoolean, ParameterExtent, ParameterFile, ParameterPoint )): self.setComboBoxValue(widget, value, param) elif isinstance(param, ParameterString): if param.multiline: widget.setValue(value) else: self.setComboBoxValue(widget, value, param) elif isinstance(param, ParameterCrs): widget.setAuthId(value) elif isinstance(param, ParameterFixedTable): pass # TODO! elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType(ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) selected = [] for i, opt in enumerate(options): if opt in value: selected.append(i) widget.setSelectedItems(selected) elif isinstance(param, ParameterGeometryPredicate): widget.setValue(value) for name, out in alg.outputs.iteritems(): widget = self.valueItems[name].setText(out.description) selected = [] dependencies = self.getAvailableDependencies() for idx, dependency in enumerate(dependencies): if dependency.name in alg.dependencies: selected.append(idx) self.dependenciesPanel.setSelectedItems(selected) def createAlgorithm(self): alg = Algorithm(self._alg.commandLineName()) alg.setName(self.model) alg.description = self.descriptionBox.text() params = self._alg.parameters outputs = self._alg.outputs for param in params: if param.hidden: continue if not self.setParamValue(alg, param, self.valueItems[param.name]): return None for output in outputs: if not output.hidden: name = unicode(self.valueItems[output.name].text()) if name.strip() != '' and name != ModelerParametersDialog.ENTER_NAME: alg.outputs[output.name] = ModelerOutput(name) selectedOptions = self.dependenciesPanel.selectedoptions availableDependencies = self.getAvailableDependencies() for selected in selectedOptions: alg.dependencies.append(availableDependencies[selected].name) return alg def setParamValueLayerOrTable(self, alg, param, widget): idx = widget.currentIndex() if idx < 0: return False else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamTableFieldValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = unicode(widget.currentText()).strip() if s == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = s return True else: alg.params[param.name] = widget.itemData(widget.currentIndex()) return True def setParamStringValue(self, alg, param, widget): if param.multiline: value = widget.getValue() option = widget.getOption() if option == MultilineTextPanel.USE_TEXT: if value == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = value else: alg.params[param.name] = value else: idx = widget.findText(widget.currentText()) if idx < 0: value = widget.currentText().strip() if value == '': if param.optional: alg.params[param.name] = None return True else: return False else: alg.params[param.name] = value else: alg.params[param.name] = widget.itemData(widget.currentIndex()) return True def setParamFileValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: value = widget.currentText() else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamNumberValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = widget.currentText().strip() if s: try: value = float(s) except: return False elif param.optional: value = None else: return False else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamExtentValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = unicode(widget.currentText()).strip() if s: try: tokens = s.split(',') if len(tokens) != 4: return False for token in tokens: float(token) except: return False elif param.optional: s = None else: return False alg.params[param.name] = [s] else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamPointValue(self, alg, param, widget): idx = widget.findText(widget.currentText()) if idx < 0: s = unicode(widget.currentText()).strip() if s: try: tokens = s.split(',') if len(tokens) != 2: return False for token in tokens: float(token) except: return False elif param.optional: s = None else: return False alg.params[param.name] = [s] else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True def setParamValue(self, alg, param, widget): if isinstance(param, (ParameterRaster, ParameterVector, ParameterTable)): return self.setParamValueLayerOrTable(alg, param, widget) elif isinstance(param, ParameterBoolean): if widget.currentIndex() < 2: value = widget.currentIndex() == 0 else: value = widget.itemData(widget.currentIndex()) alg.params[param.name] = value return True elif isinstance(param, ParameterString): return self.setParamStringValue(alg, param, widget) elif isinstance(param, ParameterNumber): return self.setParamNumberValue(alg, param, widget) elif isinstance(param, ParameterExtent): return self.setParamExtentValue(alg, param, widget) elif isinstance(param, ParameterPoint): return self.setParamPointValue(alg, param, widget) elif isinstance(param, ParameterFile): return self.setParamFileValue(alg, param, widget) elif isinstance(param, ParameterSelection): alg.params[param.name] = widget.currentIndex() return True elif isinstance(param, ParameterRange): alg.params[param.name] = widget.getValue() return True elif isinstance(param, ParameterCrs): authid = widget.getValue() if authid is None and not param.optional: return False alg.params[param.name] = authid return True elif isinstance(param, ParameterFixedTable): table = widget.table if not bool(table) and not param.optional: return False alg.params[param.name] = ParameterFixedTable.tableToString(table) return True elif isinstance(param, ParameterTableField): return self.setParamTableFieldValue(alg, param, widget) elif isinstance(param, ParameterMultipleInput): if param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY: options = self.getAvailableValuesOfType(ParameterVector, OutputVector) else: options = self.getAvailableValuesOfType(ParameterRaster, OutputRaster) values = [options[i] for i in widget.selectedoptions] if len(values) == 0 and not param.optional: return False alg.params[param.name] = values return True elif isinstance(param, ParameterGeometryPredicate): alg.params[param.name] = widget.value() return True else: alg.params[param.name] = unicode(widget.text()) return True def okPressed(self): self.alg = self.createAlgorithm() if self.alg is not None: self.close() else: QMessageBox.warning(self, self.tr('Unable to add algorithm'), self.tr('Wrong or missing parameter values')) def cancelPressed(self): self.alg = None self.close()
class ModelerParametersDialog(QDialog): ENTER_NAME = '[Enter name if this is a final result]' NOT_SELECTED = '[Not selected]' USE_MIN_COVERING_EXTENT = '[Use min covering extent]' def __init__(self, alg, model, algName=None): QDialog.__init__(self) self.setModal(True) # The algorithm to define in this dialog. It is an instance of GeoAlgorithm self._alg = alg # The resulting algorithm after the user clicks on OK. it is an instance of the container Algorithm class self.alg = None # The model this algorithm is going to be added to self.model = model # The name of the algorithm in the model, in case we are editing it and not defining it for the first time self._algName = algName self.setupUi() self.params = None def setupUi(self): self.labels = {} self.widgets = {} self.checkBoxes = {} self.showAdvanced = False self.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.name) hLayout.addWidget(descriptionLabel) hLayout.addWidget(self.descriptionBox) self.verticalLayout.addLayout(hLayout) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.verticalLayout.addWidget(line) for param in self._alg.parameters: if param.isAdvanced: self.advancedButton = QPushButton() self.advancedButton.setText(self.tr('Show advanced parameters')) self.advancedButton.clicked.connect( self.showAdvancedParametersClicked) advancedButtonHLayout = QHBoxLayout() advancedButtonHLayout.addWidget(self.advancedButton) advancedButtonHLayout.addStretch() self.verticalLayout.addLayout(advancedButtonHLayout) break for param in self._alg.parameters: if param.hidden: continue desc = param.description if isinstance(param, ParameterExtent): desc += self.tr('(xmin, xmax, ymin, ymax)') if isinstance(param, ParameterPoint): desc += self.tr('(x, y)') 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: 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.name) self.verticalLayout2 = QVBoxLayout() self.verticalLayout2.setSpacing(2) self.verticalLayout2.setMargin(0) self.tabWidget = QTabWidget() self.tabWidget.setMinimumWidth(300) self.paramPanel = QWidget() self.paramPanel.setLayout(self.verticalLayout) self.scrollArea = QScrollArea() self.scrollArea.setWidget(self.paramPanel) self.scrollArea.setWidgetResizable(True) self.tabWidget.addTab(self.scrollArea, self.tr('Parameters')) self.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 requestFinished(self): """Change the webview HTML content""" reply = self.sender() if reply.error() != QNetworkReply.NoError: html = self.tr('<h2>No help available for this algorithm</h2><p>{}</p>'.format(reply.errorString())) else: html = str(reply.readAll()) reply.deleteLater() self.txtHelp.setHtml(html) def getAvailableDependencies(self): if self._algName is None: dependent = [] else: dependent = self.model.getDependentAlgorithms(self._algName) opts = [] for alg in list(self.model.algs.values()): if alg.name not in dependent: opts.append(alg) return opts def getDependenciesPanel(self): return MultipleInputPanel([alg.description for alg in self.getAvailableDependencies()]) def showAdvancedParametersClicked(self): self.showAdvanced = not self.showAdvanced if self.showAdvanced: self.advancedButton.setText(self.tr('Hide advanced parameters')) else: self.advancedButton.setText(self.tr('Show advanced parameters')) for param in self._alg.parameters: if param.isAdvanced: self.labels[param.name].setVisible(self.showAdvanced) self.widgets[param.name].setVisible(self.showAdvanced) def getAvailableValuesOfType(self, paramType, outType=None, dataType=None): # upgrade paramType to list if type(paramType) is not list: paramType = [paramType] values = [] inputs = self.model.inputs for i in list(inputs.values()): param = i.param for t in paramType: if isinstance(param, t): if dataType is not None: if param.datatype in dataType: values.append(ValueFromInput(param.name)) else: values.append(ValueFromInput(param.name)) break if outType is None: return values if self._algName is None: dependent = [] else: dependent = self.model.getDependentAlgorithms(self._algName) for alg in list(self.model.algs.values()): if alg.name not in dependent: for out in alg.algorithm.outputs: if isinstance(out, outType): if dataType is not None and out.datatype in dataType: values.append(ValueFromOutput(alg.name, out.name)) else: values.append(ValueFromOutput(alg.name, out.name)) return values def resolveValueDescription(self, value): if isinstance(value, ValueFromInput): return self.model.inputs[value.name].param.description else: alg = self.model.algs[value.alg] return self.tr("'%s' from algorithm '%s'") % (alg.algorithm.getOutputFromName(value.output).description, alg.description) def setPreviousValues(self): if self._algName is not None: alg = self.model.algs[self._algName] self.descriptionBox.setText(alg.description) for param in alg.algorithm.parameters: if param.hidden: continue if param.name in alg.params: value = alg.params[param.name] else: value = param.default self.wrappers[param.name].setValue(value) for name, out in list(alg.outputs.items()): self.valueItems[name].setText(out.description) selected = [] dependencies = self.getAvailableDependencies() for idx, dependency in enumerate(dependencies): if dependency.name in alg.dependencies: selected.append(idx) self.dependenciesPanel.setSelectedItems(selected) def createAlgorithm(self): alg = Algorithm(self._alg.commandLineName()) alg.setName(self.model) alg.description = self.descriptionBox.text() params = self._alg.parameters outputs = self._alg.outputs for param in params: if param.hidden: continue if not self.setParamValue(alg, param, self.wrappers[param.name]): self.bar.pushMessage("Error", "Wrong or missing value for parameter '%s'" % param.description, level=QgsMessageBar.WARNING) return None for output in outputs: if not output.hidden: name = str(self.valueItems[output.name].text()) if name.strip() != '' and name != ModelerParametersDialog.ENTER_NAME: alg.outputs[output.name] = ModelerOutput(name) selectedOptions = self.dependenciesPanel.selectedoptions availableDependencies = self.getAvailableDependencies() for selected in selectedOptions: alg.dependencies.append(availableDependencies[selected].name) self._alg.processBeforeAddingToModeler(alg, self.model) return alg def setParamValue(self, alg, param, wrapper): try: if wrapper.widget: value = wrapper.value() alg.params[param.name] = value return True except InvalidParameterValue: return False def okPressed(self): self.alg = self.createAlgorithm() if self.alg is not None: self.close() def cancelPressed(self): self.alg = None self.close()
class ModelerParametersDialog(QDialog): ENTER_NAME = '[Enter name if this is a final result]' NOT_SELECTED = '[Not selected]' USE_MIN_COVERING_EXTENT = '[Use min covering extent]' def __init__(self, alg, model, algName=None): QDialog.__init__(self) self.setModal(True) # The algorithm to define in this dialog. It is an instance of GeoAlgorithm self._alg = alg # The resulting algorithm after the user clicks on OK. it is an instance of the container Algorithm class self.alg = None # The model this algorithm is going to be added to self.model = model # The name of the algorithm in the model, in case we are editing it and not defining it for the first time self._algName = algName self.setupUi() self.params = None def setupUi(self): self.labels = {} self.widgets = {} self.checkBoxes = {} self.showAdvanced = False self.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.parameters: 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.flags() & QgsProcessingParameterDefinition.FlagHidden: 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.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 output in self._alg.outputs: if output.flags() & QgsProcessingParameterDefinition.FlagHidden: 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.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 getAvailableDependencies(self): # spellok if self._algName is None: dependent = [] else: dependent = self.model.getDependentAlgorithms(self._algName) opts = [] for alg in list(self.model.algs.values()): if alg.modeler_name not in dependent: opts.append(alg) return opts def getDependenciesPanel(self): return MultipleInputPanel([alg.description for alg in self.getAvailableDependencies()]) # spellok def showAdvancedParametersClicked(self): self.showAdvanced = not self.showAdvanced if self.showAdvanced: self.advancedButton.setText(self.tr('Hide advanced parameters')) else: self.advancedButton.setText(self.tr('Show advanced parameters')) for param in self._alg.parameters: if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: self.labels[param.name].setVisible(self.showAdvanced) self.widgets[param.name].setVisible(self.showAdvanced) def getAvailableValuesOfType(self, paramType, outType=None, dataType=None): # upgrade paramType to list if type(paramType) is not list: paramType = [paramType] values = [] inputs = self.model.inputs for i in list(inputs.values()): param = i.param for t in paramType: if isinstance(param, t): if dataType is not None: if param.datatype in dataType: values.append(ValueFromInput(param.name)) else: values.append(ValueFromInput(param.name)) break if outType is None: return values if self._algName is None: dependent = [] else: dependent = self.model.getDependentAlgorithms(self._algName) for alg in list(self.model.algs.values()): if alg.modeler_name not in dependent: for out in alg.algorithm.outputs: if isinstance(out, outType): if dataType is not None and out.datatype in dataType: values.append(ValueFromOutput(alg.modeler_name, out.name)) else: values.append(ValueFromOutput(alg.modeler_name, out.name)) return values def resolveValueDescription(self, value): if isinstance(value, ValueFromInput): return self.model.inputs[value.name].param.description() else: alg = self.model.algs[value.alg] return self.tr("'{0}' from algorithm '{1}'").format(alg.algorithm.getOutputFromName(value.output).description(), alg.description) def setPreviousValues(self): if self._algName is not None: alg = self.model.algs[self._algName] self.descriptionBox.setText(alg.description) for param in alg.algorithm.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue if param.name() in alg.params: value = alg.params[param.name()] else: value = param.defaultValue() self.wrappers[param.name()].setValue(value) for name, out in list(alg.outputs.items()): self.valueItems[name].setText(out.description()) selected = [] dependencies = self.getAvailableDependencies() # spellok for idx, dependency in enumerate(dependencies): if dependency.name in alg.dependencies: selected.append(idx) self.dependenciesPanel.setSelectedItems(selected) def createAlgorithm(self): alg = Algorithm(self._alg.id()) alg.setName(self.model) alg.description = self.descriptionBox.text() params = self._alg.parameterDefinitions() outputs = self._alg.outputs for param in params: if param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue if not param.checkValueIsAcceptable(self.wrappers[param.name()].value): self.bar.pushMessage("Error", "Wrong or missing value for parameter '%s'" % param.description(), level=QgsMessageBar.WARNING) return None for output in outputs: if not output.flags() & QgsProcessingParameterDefinition.FlagHidden: name = str(self.valueItems[output.name()].text()) if name.strip() != '' and name != ModelerParametersDialog.ENTER_NAME: alg.outputs[output.name()] = ModelerOutput(name) selectedOptions = self.dependenciesPanel.selectedoptions availableDependencies = self.getAvailableDependencies() # spellok for selected in selectedOptions: alg.dependencies.append(availableDependencies[selected].name) # spellok self._alg.processBeforeAddingToModeler(alg, self.model) return alg def okPressed(self): self.alg = self.createAlgorithm() if self.alg is not None: self.close() def cancelPressed(self): self.alg = None self.close() def openHelp(self): algHelp = self._alg.help() if algHelp is not None: webbrowser.open(algHelp)
class ModelerParametersDialog(QDialog): ENTER_NAME = '[Enter name if this is a final result]' NOT_SELECTED = '[Not selected]' USE_MIN_COVERING_EXTENT = '[Use min covering extent]' def __init__(self, alg, model, algName=None): QDialog.__init__(self) self.setModal(True) # The algorithm to define in this dialog. It is an instance of GeoAlgorithm self._alg = alg # The resulting algorithm after the user clicks on OK. it is an instance of the container Algorithm class self.alg = None # The model this algorithm is going to be added to self.model = model # The name of the algorithm in the model, in case we are editing it and not defining it for the first time self.childId = algName self.setupUi() self.params = None settings = QgsSettings() self.restoreGeometry(settings.value("/Processing/modelParametersDialogGeometry", QByteArray())) def closeEvent(self, event): settings = QgsSettings() settings.setValue("/Processing/modelParametersDialogGeometry", self.saveGeometry()) super(ModelerParametersDialog, self).closeEvent(event) 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 getAvailableDependencies(self): # spellok if self.childId is None: dependent = [] else: dependent = list(self.model.dependentChildAlgorithms(self.childId)) dependent.append(self.childId) opts = [] for alg in list(self.model.childAlgorithms().values()): if alg.childId() not in dependent: opts.append(alg) return opts def getDependenciesPanel(self): return MultipleInputPanel([alg.description() for alg in self.getAvailableDependencies()]) # spellok def showAdvancedParametersClicked(self): self.showAdvanced = not self.showAdvanced if self.showAdvanced: self.advancedButton.setText(self.tr('Hide advanced parameters')) else: self.advancedButton.setText(self.tr('Show advanced parameters')) for param in self._alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: self.labels[param.name()].setVisible(self.showAdvanced) self.widgets[param.name()].setVisible(self.showAdvanced) def getAvailableValuesOfType(self, paramType, outTypes=[], dataTypes=[]): # upgrade paramType to list if paramType is None: paramType = [] elif not isinstance(paramType, list): paramType = [paramType] if outTypes is None: outTypes = [] elif not isinstance(outTypes, list): outTypes = [outTypes] return self.model.availableSourcesForChild(self.childId, [p.typeName() for p in paramType if issubclass(p, QgsProcessingParameterDefinition)], [o.typeName() for o in outTypes if issubclass(o, QgsProcessingOutputDefinition)], dataTypes) def resolveValueDescription(self, value): if isinstance(value, QgsProcessingModelChildParameterSource): if value.source() == QgsProcessingModelChildParameterSource.StaticValue: return value.staticValue() elif value.source() == QgsProcessingModelChildParameterSource.ModelParameter: return self.model.parameterDefinition(value.parameterName()).description() elif value.source() == QgsProcessingModelChildParameterSource.ChildOutput: alg = self.model.childAlgorithm(value.outputChildId()) return self.tr("'{0}' from algorithm '{1}'").format( alg.algorithm().outputDefinition(value.outputName()).description(), alg.description()) return value def setPreviousValues(self): if self.childId is not None: alg = self.model.childAlgorithm(self.childId) self.descriptionBox.setText(alg.description()) for param in alg.algorithm().parameterDefinitions(): if param.isDestination() or param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue value = None if param.name() in alg.parameterSources(): value = alg.parameterSources()[param.name()] if isinstance(value, list) and len(value) == 1: value = value[0] elif isinstance(value, list) and len(value) == 0: value = None if value is None: value = param.defaultValue() if isinstance(value, QgsProcessingModelChildParameterSource) and value.source() == QgsProcessingModelChildParameterSource.StaticValue: value = value.staticValue() self.wrappers[param.name()].setValue(value) for name, out in list(alg.modelOutputs().items()): if out.childOutputName() in self.valueItems: self.valueItems[out.childOutputName()].setText(out.name()) selected = [] dependencies = self.getAvailableDependencies() # spellok for idx, dependency in enumerate(dependencies): if dependency.childId() in alg.dependencies(): selected.append(idx) self.dependenciesPanel.setSelectedItems(selected) def createAlgorithm(self): alg = QgsProcessingModelChildAlgorithm(self._alg.id()) if not self.childId: alg.generateChildId(self.model) else: alg.setChildId(self.childId) alg.setDescription(self.descriptionBox.text()) for param in self._alg.parameterDefinitions(): if param.isDestination() or param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue val = self.wrappers[param.name()].value() if (isinstance(val, QgsProcessingModelChildParameterSource) and val.source() == QgsProcessingModelChildParameterSource.StaticValue and not param.checkValueIsAcceptable( val.staticValue())) \ or (val is None and not param.flags() & QgsProcessingParameterDefinition.FlagOptional): self.bar.pushMessage("Error", "Wrong or missing value for parameter '%s'" % param.description(), level=QgsMessageBar.WARNING) return None if val is None: continue elif isinstance(val, QgsProcessingModelChildParameterSource): alg.addParameterSources(param.name(), [val]) elif isinstance(val, list): alg.addParameterSources(param.name(), val) else: alg.addParameterSources(param.name(), [QgsProcessingModelChildParameterSource.fromStaticValue(val)]) outputs = {} for dest in self._alg.destinationParameterDefinitions(): if not dest.flags() & QgsProcessingParameterDefinition.FlagHidden: name = str(self.valueItems[dest.name()].text()) if name.strip() != '' and name != ModelerParametersDialog.ENTER_NAME: output = QgsProcessingModelOutput(name, name) output.setChildId(alg.childId()) output.setChildOutputName(dest.name()) outputs[name] = output alg.setModelOutputs(outputs) selectedOptions = self.dependenciesPanel.selectedoptions availableDependencies = self.getAvailableDependencies() # spellok dep_ids = [] for selected in selectedOptions: dep_ids.append(availableDependencies[selected].childId()) # spellok alg.setDependencies(dep_ids) try: self._alg.processBeforeAddingToModeler(alg, self.model) except: pass return alg def okPressed(self): self.alg = self.createAlgorithm() if self.alg is not None: self.close() def cancelPressed(self): self.alg = None self.close() def openHelp(self): algHelp = self._alg.help() if algHelp is not None: webbrowser.open(algHelp)
class ConfigDialog(QDialog): NO_BASE_LAYER = "Do not add base layer" def __init__(self): QDialog.__init__(self) self.setupUi() self.fillTree() self.tree.expandAll() 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 fillTree(self): self.items = {} self.tree.clear() _layers = [self.NO_BASE_LAYER] _layers.extend([lay.name for lay in layers()]) generalParams = [ConfigParameter("AddLayerToNewProjects", "Automatically add base layer to new projects", _layers)] icon = QIcon(os.path.dirname(__file__) + "/../../images/geoserver.png") generalItem = self._getItem("General", icon, generalParams) self.tree.addTopLevelItem(generalItem) for provider in providers: providerItem = self._getItem(provider.name, provider.icon, provider.options()) self.tree.addTopLevelItem(providerItem) self.tree.setColumnWidth(0, 400) def _getItem(self, name, icon, params): icon = QIcon(icon) item = QTreeWidgetItem() item.setText(0, name) item.setIcon(0, icon) for param in params: subItem = TreeSettingItem(item, self.tree, name, param) item.addChild(subItem) return item def saveSettings(self): iterator = QTreeWidgetItemIterator(self.tree) value = iterator.value() while value: if hasattr(value, 'saveValue'): try: value.saveValue() except Exception as e: self.bar.pushMessage("Error for parameter '%s':" % value.param.description, str(e), level=QgsMessageBar.WARNING) return False iterator += 1 value = iterator.value() return True def accept(self): if self.saveSettings(): QDialog.accept(self)
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): out = open(f, 'w') out.write('from qgis.core import *\n') out.write('import processing\n\n') out.write('def removeall():\n') out.write('\tmapreg = QgsMapLayerRegistry.instance()\n') out.write('\tmapreg.removeAllMapLayers()\n\n') out.write('def load(*args):\n') out.write('\tprocessing.load(args[0])\n') out.close() 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)
class ModelerParametersPanelWidget(QgsPanelWidget): def __init__(self, alg, model, algName=None, configuration=None, dialog=None, context=None): super().__init__() self._alg = alg # The algorithm to define in this dialog. It is an instance of QgsProcessingAlgorithm self.model = model # The model this algorithm is going to be added to. It is an instance of QgsProcessingModelAlgorithm self.childId = algName # The name of the algorithm in the model, in case we are editing it and not defining it for the first time self.configuration = configuration self.context = context self.dialog = dialog self.widget_labels = {} class ContextGenerator(QgsProcessingContextGenerator): def __init__(self, context): super().__init__() self.processing_context = context def processingContext(self): return self.processing_context self.context_generator = ContextGenerator(self.context) self.setupUi() self.params = None def algorithm(self): return self._alg def setupUi(self): self.showAdvanced = False self.wrappers = {} self.algorithmItem = None self.mainLayout = QVBoxLayout() self.mainLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout = QVBoxLayout() self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.verticalLayout.addWidget(self.bar) hLayout = QHBoxLayout() hLayout.setContentsMargins(0, 0, 0, 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.setActiveLayer(iface.activeLayer()) 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.dialog) 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: 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 output in self._alg.destinationParameterDefinitions(): if output.flags() & QgsProcessingParameterDefinition.FlagHidden: continue widget = QgsGui.processingGuiRegistry( ).createModelerParameterWidget(self.model, self.childId, output, self.context) widget.setDialog(self.dialog) widget.setWidgetContext(widget_context) widget.registerProcessingContextGenerator(self.context_generator) self.wrappers[output.name()] = widget item = QgsFilterLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText( self.tr('[Enter name if this is a final result]')) label = widget.createLabel() if label is not None: self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(widget) label = QLabel(' ') self.verticalLayout.addWidget(label) label = QLabel(self.tr('Dependencies')) self.dependencies_panel = QgsModelChildDependenciesWidget( self, self.model, self.childId) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(self.dependencies_panel) self.verticalLayout.addStretch(1000) self.setPreviousValues() 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.scrollArea.setFrameStyle(QFrame.NoFrame) self.verticalLayout2.addWidget(self.scrollArea) w = QWidget() w.setLayout(self.verticalLayout2) self.mainLayout.addWidget(w) self.setLayout(self.mainLayout) def showAdvancedParametersClicked(self): self.showAdvanced = not self.showAdvanced if self.showAdvanced: self.advancedButton.setText(self.tr('Hide advanced parameters')) else: self.advancedButton.setText(self.tr('Show advanced parameters')) for param in self._alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: wrapper = self.wrappers[param.name()] if issubclass(wrapper.__class__, QgsProcessingModelerParameterWidget): wrapper.setVisible(self.showAdvanced) else: wrapper.widget.setVisible(self.showAdvanced) self.widget_labels[param.name()].setVisible(self.showAdvanced) def setPreviousValues(self): if self.childId is not None: alg = self.model.childAlgorithm(self.childId) self.descriptionBox.setText(alg.description()) for param in alg.algorithm().parameterDefinitions(): if param.isDestination() or param.flags( ) & QgsProcessingParameterDefinition.FlagHidden: continue value = None if param.name() in alg.parameterSources(): value = alg.parameterSources()[param.name()] if isinstance(value, list) and len(value) == 1: value = value[0] elif isinstance(value, list) and len(value) == 0: value = None wrapper = self.wrappers[param.name()] if issubclass(wrapper.__class__, QgsProcessingModelerParameterWidget): if value is None: value = QgsProcessingModelChildParameterSource.fromStaticValue( param.defaultValue()) wrapper.setWidgetValue(value) else: if value is None: value = param.defaultValue() if isinstance( value, QgsProcessingModelChildParameterSource ) and value.source( ) == QgsProcessingModelChildParameterSource.StaticValue: value = value.staticValue() wrapper.setValue(value) for output in self.algorithm().destinationParameterDefinitions(): if output.flags( ) & QgsProcessingParameterDefinition.FlagHidden: continue model_output_name = None for name, out in alg.modelOutputs().items(): if out.childId() == self.childId and out.childOutputName( ) == output.name(): # this destination parameter is linked to a model output model_output_name = out.name() break value = None if model_output_name is None and output.name( ) in alg.parameterSources(): value = alg.parameterSources()[output.name()] if isinstance(value, list) and len(value) == 1: value = value[0] elif isinstance(value, list) and len(value) == 0: value = None wrapper = self.wrappers[output.name()] if model_output_name is not None: wrapper.setToModelOutput(model_output_name) elif value is not None or output.defaultValue() is not None: if value is None: value = QgsProcessingModelChildParameterSource.fromStaticValue( output.defaultValue()) wrapper.setWidgetValue(value) self.dependencies_panel.setValue(alg.dependencies()) def createAlgorithm(self): alg = QgsProcessingModelChildAlgorithm(self._alg.id()) if not self.childId: alg.generateChildId(self.model) else: alg.setChildId(self.childId) alg.setDescription(self.descriptionBox.text()) if self.algorithmItem: alg.setConfiguration(self.algorithmItem.configuration()) self._alg = alg.algorithm().create( self.algorithmItem.configuration()) for param in self._alg.parameterDefinitions(): if param.isDestination( ) or param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue try: wrapper = self.wrappers[param.name()] if issubclass(wrapper.__class__, WidgetWrapper): val = wrapper.value() elif issubclass(wrapper.__class__, QgsProcessingModelerParameterWidget): val = wrapper.value() else: val = wrapper.parameterValue() except InvalidParameterValue: val = None if isinstance(val, QgsProcessingModelChildParameterSource): val = [val] elif not (isinstance(val, list) and all([ isinstance(subval, QgsProcessingModelChildParameterSource) for subval in val ])): val = [ QgsProcessingModelChildParameterSource.fromStaticValue(val) ] valid = True for subval in val: if (isinstance(subval, QgsProcessingModelChildParameterSource) and subval.source() == QgsProcessingModelChildParameterSource.StaticValue and not param.checkValueIsAcceptable(subval.staticValue())) \ or (subval is None and not param.flags() & QgsProcessingParameterDefinition.FlagOptional): valid = False break if valid: alg.addParameterSources(param.name(), val) outputs = {} for output in self._alg.destinationParameterDefinitions(): if not output.flags( ) & QgsProcessingParameterDefinition.FlagHidden: wrapper = self.wrappers[output.name()] if wrapper.isModelOutput(): name = wrapper.modelOutputName() if name: model_output = QgsProcessingModelOutput(name, name) model_output.setChildId(alg.childId()) model_output.setChildOutputName(output.name()) outputs[name] = model_output else: val = wrapper.value() if isinstance(val, QgsProcessingModelChildParameterSource): val = [val] alg.addParameterSources(output.name(), val) if output.flags( ) & QgsProcessingParameterDefinition.FlagIsModelOutput: if output.name() not in outputs: model_output = QgsProcessingModelOutput( output.name(), output.name()) model_output.setChildId(alg.childId()) model_output.setChildOutputName(output.name()) outputs[output.name()] = model_output alg.setModelOutputs(outputs) alg.setDependencies(self.dependencies_panel.value()) return alg
class ModelerParametersDialog(QDialog): ENTER_NAME = '[Enter name if this is a final result]' NOT_SELECTED = '[Not selected]' USE_MIN_COVERING_EXTENT = '[Use min covering extent]' def __init__(self, alg, model, algName=None): QDialog.__init__(self) self.setModal(True) # The algorithm to define in this dialog. It is an instance of GeoAlgorithm self._alg = alg # The resulting algorithm after the user clicks on OK. it is an instance of the container Algorithm class self.alg = None # The model this algorithm is going to be added to self.model = model # The name of the algorithm in the model, in case we are editing it and not defining it for the first time self._algName = algName self.setupUi() self.params = None def setupUi(self): self.labels = {} self.widgets = {} self.checkBoxes = {} self.showAdvanced = False self.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, (QgsProcessingParameterRasterOutput, QgsProcessingParameterFeatureSink, QgsProcessingParameterFileOutput, QgsProcessingParameterFolderOutput)): label = QLabel(dest.description()) item = QLineEdit() 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 getAvailableDependencies(self): # spellok if self._algName is None: dependent = [] else: dependent = list(self.model.dependentChildAlgorithms(self._algName)) dependent.append(self._algName) opts = [] for alg in list(self.model.childAlgorithms().values()): if alg.childId() not in dependent: opts.append(alg) return opts def getDependenciesPanel(self): return MultipleInputPanel([alg.description() for alg in self.getAvailableDependencies()]) # spellok def showAdvancedParametersClicked(self): self.showAdvanced = not self.showAdvanced if self.showAdvanced: self.advancedButton.setText(self.tr('Hide advanced parameters')) else: self.advancedButton.setText(self.tr('Show advanced parameters')) for param in self._alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: self.labels[param.name()].setVisible(self.showAdvanced) self.widgets[param.name()].setVisible(self.showAdvanced) def getAvailableValuesOfType(self, paramType, outTypes=[], dataType=None): # upgrade paramType to list if paramType is None: paramType = [] elif not isinstance(paramType, list): paramType = [paramType] if outTypes is None: outTypes = [] elif not isinstance(outTypes, list): outTypes = [outTypes] values = [] inputs = self.model.parameterComponents() for i in list(inputs.values()): param = self.model.parameterDefinition(i.parameterName()) for t in paramType: if isinstance(param, t): if dataType is not None: if param.datatype in dataType: values.append( QgsProcessingModelAlgorithm.ChildParameterSource.fromModelParameter(param.name())) else: values.append(QgsProcessingModelAlgorithm.ChildParameterSource.fromModelParameter(param.name())) break if not outTypes: return values if self._algName is None: dependent = [] else: dependent = list(self.model.dependentChildAlgorithms(self._algName)) dependent.append(self._algName) for alg in list(self.model.childAlgorithms().values()): if alg.childId() not in dependent: for out in alg.algorithm().outputDefinitions(): for t in outTypes: if isinstance(out, t): if dataType is not None and out.datatype in dataType: values.append( QgsProcessingModelAlgorithm.ChildParameterSource.fromChildOutput(alg.childId(), out.name())) else: values.append( QgsProcessingModelAlgorithm.ChildParameterSource.fromChildOutput(alg.childId(), out.name())) return values def resolveValueDescription(self, value): if isinstance(value, QgsProcessingModelAlgorithm.ChildParameterSource): if value.source() == QgsProcessingModelAlgorithm.ChildParameterSource.StaticValue: return value.staticValue() elif value.source() == QgsProcessingModelAlgorithm.ChildParameterSource.ModelParameter: return self.model.parameterDefinition(value.parameterName()).description() elif value.source() == QgsProcessingModelAlgorithm.ChildParameterSource.ChildOutput: alg = self.model.childAlgorithm(value.outputChildId()) return self.tr("'{0}' from algorithm '{1}'").format( alg.algorithm().outputDefinition(value.outputName()).description(), alg.description()) return value def setPreviousValues(self): if self._algName is not None: alg = self.model.childAlgorithm(self._algName) self.descriptionBox.setText(alg.description()) for param in alg.algorithm().parameterDefinitions(): if param.isDestination() or param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue if param.name() in alg.parameterSources(): value = alg.parameterSources()[param.name()] if isinstance(value, list) and len(value) == 1: value = value[0] else: value = param.defaultValue() if isinstance(value, QgsProcessingModelAlgorithm.ChildParameterSource) and value.source() == QgsProcessingModelAlgorithm.ChildParameterSource.StaticValue: value = value.staticValue() self.wrappers[param.name()].setValue(value) for name, out in list(alg.modelOutputs().items()): if out.childOutputName() in self.valueItems: self.valueItems[out.childOutputName()].setText(out.name()) selected = [] dependencies = self.getAvailableDependencies() # spellok for idx, dependency in enumerate(dependencies): if dependency.childId() in alg.dependencies(): selected.append(idx) self.dependenciesPanel.setSelectedItems(selected) def createAlgorithm(self): alg = QgsProcessingModelAlgorithm.ChildAlgorithm(self._alg.id()) if not self._algName: alg.generateChildId(self.model) else: alg.setChildId(self._algName) alg.setDescription(self.descriptionBox.text()) for param in self._alg.parameterDefinitions(): if param.isDestination() or param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue val = self.wrappers[param.name()].value() if (isinstance(val, QgsProcessingModelAlgorithm.ChildParameterSource) and val.source() == QgsProcessingModelAlgorithm.ChildParameterSource.StaticValue and not param.checkValueIsAcceptable( val.staticValue())) \ or (val is None and not param.flags() & QgsProcessingParameterDefinition.FlagOptional): self.bar.pushMessage("Error", "Wrong or missing value for parameter '%s'" % param.description(), level=QgsMessageBar.WARNING) return None if val is None: continue elif isinstance(val, QgsProcessingModelAlgorithm.ChildParameterSource): alg.addParameterSources(param.name(), [val]) elif isinstance(val, list): alg.addParameterSources(param.name(), val) else: alg.addParameterSources(param.name(), [QgsProcessingModelAlgorithm.ChildParameterSource.fromStaticValue(val)]) outputs = {} for dest in self._alg.destinationParameterDefinitions(): if not dest.flags() & QgsProcessingParameterDefinition.FlagHidden: name = str(self.valueItems[dest.name()].text()) if name.strip() != '' and name != ModelerParametersDialog.ENTER_NAME: output = QgsProcessingModelAlgorithm.ModelOutput(name, name) output.setChildId(alg.childId()) output.setChildOutputName(dest.name()) outputs[name] = output alg.setModelOutputs(outputs) selectedOptions = self.dependenciesPanel.selectedoptions availableDependencies = self.getAvailableDependencies() # spellok dep_ids = [] for selected in selectedOptions: dep_ids.append(availableDependencies[selected].childId()) # spellok alg.setDependencies(dep_ids) try: self._alg.processBeforeAddingToModeler(alg, self.model) except: pass return alg def okPressed(self): self.alg = self.createAlgorithm() if self.alg is not None: self.close() def cancelPressed(self): self.alg = None self.close() def openHelp(self): algHelp = self._alg.help() if algHelp is not None: webbrowser.open(algHelp)
class CommitDialog(QDialog): def __init__(self, repo, layername, _message="", parent=None): super(CommitDialog, self).__init__(parent) self.repo = repo self.branch = None self.layername = layername self._message = _message or suggestedMessage self.message = None self.initGui() def initGui(self): self.resize(600, 250) self.setWindowTitle('GeoGig') self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(2) self.verticalLayout.setMargin(5) self.branchLabel = QLabel("Branch") self.verticalLayout.addWidget(self.branchLabel) self.branchCombo = QComboBox() self.branches = [] branches = self.repo.branches() for branch in branches: trees = self.repo.trees(branch) if self.layername in trees: self.branches.append(branch) self.branchCombo.addItems(self.branches) try: idx = self.branches.index("master") except: idx = 0 self.branchCombo.setCurrentIndex(idx) self.verticalLayout.addWidget(self.branchCombo) self.msgLabel = QLabel("Message to describe this update") self.verticalLayout.addWidget(self.msgLabel) self.text = QPlainTextEdit() self.text.setPlainText(self._message) self.text.textChanged.connect(self.textHasChanged) self.verticalLayout.addWidget(self.text) self.buttonBox = QDialogButtonBox(QDialogButtonBox.Ok) self.verticalLayout.addWidget(self.buttonBox) self.buttonBox.button(QDialogButtonBox.Ok).setEnabled( bool(self._message) and bool(self.branches)) self.setLayout(self.verticalLayout) self.buttonBox.accepted.connect(self.okPressed) self.text.setFocus() def textHasChanged(self): self.buttonBox.button(QDialogButtonBox.Ok).setEnabled( self.text.toPlainText() != "" and bool(self.branches)) def okPressed(self): self.branch = self.branchCombo.currentText() self.message = self.text.toPlainText() self.close()