Esempio n. 1
0
    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()
Esempio n. 2
0
    def draw_dialog(self):
        QDialog.__init__(self)

        self.setWindowTitle(self.tr('Drawing'))

        self.name = QLineEdit()

        gtype = 'Polygon'

        # Choose which object is placed
        LandUseTypes = [
            'Trees on grass', 'Trees on avenue', 'Grass field', 'Green roofs',
            'Cool roofs', 'Facade greening', 'Solar Panels', 'Pond/river',
            'Fountain', 'Surface albedo change'
        ]
        self.ObjectType = QComboBox()
        self.ObjectType.insertItems(0, LandUseTypes)
        # change here by QgsMapLayerComboBox()
        self.layerBox = QComboBox()
        self.layers = []
        for layer in QgsProject.instance().mapLayers().values():
            if layer.providerType() == "memory":
                # ligne suivante à remplacer par if layer.geometryType() == :
                if gtype in layer.dataProvider().dataSourceUri(
                )[:26]:  # must be of the same type of the draw
                    if 'field=' + self.tr(
                            'Drawings'
                    ) + ':string(255,0)' in layer.dataProvider().dataSourceUri(
                    )[-28:]:  # must have its first field named Drawings, string type
                        self.layers.append(layer)
                        self.layerBox.addItem(layer.name())
                        global layername
                        layername = layer.name()

        # Save the chosen land use
        chsnlanduse = self.ObjectType.currentText()
        print(chsnlanduse)

        # CheckBox to add to layer
        # self.addLayer = QCheckBox(self.tr('Add to an existing layer'))
        # self.addLayer.toggled.connect(self.addLayerChecked)

        # Ok and cancel button
        buttons = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self)
        buttons.accepted.connect(self.accept)
        # buttons.accepted.connect(self.addInformation(chsnlanduse, layer))
        buttons.rejected.connect(self.reject)

        vbox = QVBoxLayout()
        vbox.addWidget(QLabel(self.tr("Give a name to the feature:")))
        vbox.addWidget(self.name)
        vbox.addWidget(self.ObjectType)
        vbox.addWidget(self.addLayer)
        vbox.addWidget(self.layerBox)
        if len(self.layers) == 0:
            self.addLayer.setEnabled(False)
            self.layerBox.setEnabled(False)
        vbox.addWidget(buttons)
        self.setLayout(vbox)

        self.layerBox.setEnabled(False)
        self.name.setFocus()
Esempio n. 3
0
    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
Esempio n. 4
0
    def construct_form_param_system(self, row, pos):

        widget = None
        for field in row[pos]['fields']:
            if field['label']:
                lbl = QLabel()
                lbl.setObjectName('lbl' + field['widgetname'])
                lbl.setText(field['label'])
                lbl.setMinimumSize(160, 0)
                lbl.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
                lbl.setToolTip(field['tooltip'])

                if field['widgettype'] == 'text' or field[
                        'widgettype'] == 'linetext':
                    widget = QLineEdit()
                    widget.setText(field['value'])
                    widget.editingFinished.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                elif field['widgettype'] == 'textarea':
                    widget = QTextEdit()
                    widget.setText(field['value'])
                    widget.editingFinished.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                elif field['widgettype'] == 'combo':
                    widget = QComboBox()
                    self.populate_combo(widget, field)
                    widget.currentIndexChanged.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                elif field['widgettype'] == 'checkbox' or field[
                        'widgettype'] == 'check':
                    widget = QCheckBox()
                    if field['value'].lower() == 'true':
                        widget.setChecked(True)
                    elif field['value'].lower() == 'FALSE':
                        widget.setChecked(False)
                    widget.stateChanged.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
                elif field['widgettype'] == 'datepickertime':
                    widget = QDateEdit()
                    widget.setCalendarPopup(True)
                    date = QDate.fromString(field['value'], 'yyyy/MM/dd')
                    widget.setDate(date)
                    widget.dateChanged.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                elif field['widgettype'] == 'spinbox':
                    widget = QDoubleSpinBox()
                    if 'value' in field and field['value'] is not None:
                        value = float(str(field['value']))
                        widget.setValue(value)
                    widget.valueChanged.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                else:
                    pass

                if widget:
                    widget.setObjectName(field['widgetname'])
                else:
                    pass

                # Order Widgets
                if field['layout_id'] == 1:
                    self.order_widgets_system(field, self.basic_form, lbl,
                                              widget)
                elif field['layout_id'] == 2:
                    self.order_widgets_system(field, self.om_form, lbl, widget)
                elif field['layout_id'] == 3:
                    self.order_widgets_system(field, self.workcat_form, lbl,
                                              widget)
                elif field['layout_id'] == 4:
                    self.order_widgets_system(field, self.mapzones_form, lbl,
                                              widget)
                elif field['layout_id'] == 5:
                    self.order_widgets_system(field, self.cad_form, lbl,
                                              widget)
                elif field['layout_id'] == 6:
                    self.order_widgets_system(field, self.epa_form, lbl,
                                              widget)
                elif field['layout_id'] == 7:
                    self.order_widgets_system(field, self.masterplan_form, lbl,
                                              widget)
                elif field['layout_id'] == 8:
                    self.order_widgets_system(field, self.other_form, lbl,
                                              widget)
                elif field['layout_id'] == 9:
                    self.order_widgets_system(field, self.node_type_form, lbl,
                                              widget)
                elif field['layout_id'] == 10:
                    self.order_widgets_system(field, self.cat_form, lbl,
                                              widget)
                elif field['layout_id'] == 11:
                    self.order_widgets_system(field, self.utils_form, lbl,
                                              widget)
                elif field['layout_id'] == 12:
                    self.order_widgets_system(field, self.connec_form, lbl,
                                              widget)
                elif field['layout_id'] == 13:
                    self.order_widgets_system(field, self.topology_form, lbl,
                                              widget)
                elif field['layout_id'] == 14:
                    self.order_widgets_system(field, self.builder_form, lbl,
                                              widget)
                elif field['layout_id'] == 15:
                    self.order_widgets_system(field, self.review_form, lbl,
                                              widget)
                elif field['layout_id'] == 16:
                    self.order_widgets_system(field, self.analysis_form, lbl,
                                              widget)
                elif field['layout_id'] == 17:
                    self.order_widgets_system(field, self.system_form, lbl,
                                              widget)
    def setupUi(self):
        type_metadata = QgsApplication.processingRegistry().parameterType(
            self.param.type() if self.param else self.paramType)
        self.setWindowTitle(
            self.tr('{} Parameter Definition').format(type_metadata.name()))

        self.mainLayout = QVBoxLayout()
        self.tab = QTabWidget()
        self.mainLayout.addWidget(self.tab)

        self.setMinimumWidth(300)

        self.verticalLayout = QVBoxLayout()

        self.label = QLabel(self.tr('Parameter name'))
        self.verticalLayout.addWidget(self.label)
        self.nameTextBox = QLineEdit()
        self.verticalLayout.addWidget(self.nameTextBox)

        if isinstance(self.param, QgsProcessingParameterDefinition):
            self.nameTextBox.setText(self.param.description())

        if isinstance(self.param, QgsProcessingDestinationParameter):
            self.verticalLayout.addWidget(QLabel(self.tr('Default value')))
            self.defaultWidget = QgsProcessingLayerOutputDestinationWidget(
                self.param, defaultSelection=True)
            self.verticalLayout.addWidget(self.defaultWidget)

        self.verticalLayout.addSpacing(20)
        self.requiredCheck = QCheckBox()
        self.requiredCheck.setText(self.tr('Mandatory'))
        self.requiredCheck.setChecked(True)
        if self.param is not None:
            self.requiredCheck.setChecked(
                not self.param.flags()
                & QgsProcessingParameterDefinition.FlagOptional)
        self.verticalLayout.addWidget(self.requiredCheck)

        self.advancedCheck = QCheckBox()
        self.advancedCheck.setText(self.tr('Advanced'))
        self.advancedCheck.setChecked(False)
        if self.param is not None:
            self.advancedCheck.setChecked(
                self.param.flags()
                & QgsProcessingParameterDefinition.FlagAdvanced)
        self.verticalLayout.addWidget(self.advancedCheck)

        # If child algorithm output is mandatory, disable checkbox
        if isinstance(self.param, QgsProcessingDestinationParameter):
            child = self.alg.childAlgorithms()[self.param.metadata()
                                               ['_modelChildId']]
            model_output = child.modelOutput(
                self.param.metadata()['_modelChildOutputName'])
            param_def = child.algorithm().parameterDefinition(
                model_output.childOutputName())
            if not (param_def.flags()
                    & QgsProcessingParameterDefinition.FlagOptional):
                self.requiredCheck.setEnabled(False)
                self.requiredCheck.setChecked(True)

            self.advancedCheck.setEnabled(False)
            self.advancedCheck.setChecked(False)

        self.verticalLayout.addStretch()

        w = QWidget()
        w.setLayout(self.verticalLayout)
        self.tab.addTab(w, self.tr('Properties'))

        self.commentLayout = QVBoxLayout()
        self.commentEdit = QTextEdit()
        self.commentEdit.setAcceptRichText(False)
        self.commentLayout.addWidget(self.commentEdit, 1)

        hl = QHBoxLayout()
        hl.setContentsMargins(0, 0, 0, 0)
        hl.addWidget(QLabel(self.tr('Color')))
        self.comment_color_button = QgsColorButton()
        self.comment_color_button.setAllowOpacity(True)
        self.comment_color_button.setWindowTitle(self.tr('Comment Color'))
        self.comment_color_button.setShowNull(True, self.tr('Default'))
        hl.addWidget(self.comment_color_button)
        self.commentLayout.addLayout(hl)

        w2 = QWidget()
        w2.setLayout(self.commentLayout)
        self.tab.addTab(w2, self.tr('Comments'))

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName('buttonBox')
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

        self.mainLayout.addWidget(self.buttonBox)

        self.setLayout(self.mainLayout)
Esempio n. 6
0
    def setupUi(self):
        type_metadata = QgsApplication.processingRegistry().parameterType(
            self.param.type() if self.param else self.paramType)
        self.setWindowTitle(
            self.tr('{} Parameter Definition').format(type_metadata.name()))
        self.setMinimumWidth(300)

        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setMargin(20)

        self.label = QLabel(self.tr('Parameter name'))
        self.verticalLayout.addWidget(self.label)
        self.nameTextBox = QLineEdit()
        self.verticalLayout.addWidget(self.nameTextBox)

        if isinstance(self.param, QgsProcessingParameterDefinition):
            self.nameTextBox.setText(self.param.description())

        if self.paramType == parameters.PARAMETER_BOOLEAN or \
                isinstance(self.param, QgsProcessingParameterBoolean):
            self.state = QCheckBox()
            self.state.setText(self.tr('Checked'))
            self.state.setChecked(False)
            if self.param is not None:
                self.state.setChecked(bool(self.param.defaultValue()))
            self.verticalLayout.addWidget(self.state)
        elif self.paramType == parameters.PARAMETER_TABLE_FIELD or \
                isinstance(self.param, QgsProcessingParameterField):
            self.verticalLayout.addWidget(QLabel(self.tr('Parent layer')))
            self.parentCombo = QComboBox()
            idx = 0
            for param in list(self.alg.parameterComponents().values()):
                definition = self.alg.parameterDefinition(
                    param.parameterName())
                if isinstance(definition, (QgsProcessingParameterFeatureSource,
                                           QgsProcessingParameterVectorLayer)):
                    self.parentCombo.addItem(definition.description(),
                                             definition.name())
                    if self.param is not None:
                        if self.param.parentLayerParameterName(
                        ) == definition.name():
                            self.parentCombo.setCurrentIndex(idx)
                    idx += 1
            self.verticalLayout.addWidget(self.parentCombo)

            # add the datatype selector
            self.verticalLayout.addWidget(QLabel(self.tr('Allowed data type')))
            self.datatypeCombo = QComboBox()
            self.datatypeCombo.addItem(self.tr('Any'), -1)
            self.datatypeCombo.addItem(self.tr('Number'), 0)
            self.datatypeCombo.addItem(self.tr('String'), 1)
            self.datatypeCombo.addItem(self.tr('Date/time'), 2)
            self.verticalLayout.addWidget(self.datatypeCombo)

            if self.param is not None and self.param.dataType() is not None:
                # QComboBoxes indexes start at 0,
                # self.param.datatype start with -1 that is why I need to do +1
                datatypeIndex = self.param.dataType() + 1
                self.datatypeCombo.setCurrentIndex(datatypeIndex)

            self.multipleCheck = QCheckBox()
            self.multipleCheck.setText(self.tr('Accept multiple fields'))
            self.multipleCheck.setChecked(False)
            if self.param is not None:
                self.multipleCheck.setChecked(self.param.allowMultiple())
            self.verticalLayout.addWidget(self.multipleCheck)

            self.verticalLayout.addWidget(QLabel(self.tr('Default value')))
            self.defaultTextBox = QLineEdit()
            self.defaultTextBox.setToolTip(
                self.
                tr('Default field name, or ; separated list of field names for multiple field parameters'
                   ))
            if self.param is not None:
                default = self.param.defaultValue()
                if default is not None:
                    self.defaultTextBox.setText(str(default))
            self.verticalLayout.addWidget(self.defaultTextBox)

        elif self.paramType == parameters.PARAMETER_BAND or \
                isinstance(self.param, QgsProcessingParameterBand):
            self.verticalLayout.addWidget(QLabel(self.tr('Parent layer')))
            self.parentCombo = QComboBox()
            idx = 0
            for param in list(self.alg.parameterComponents().values()):
                definition = self.alg.parameterDefinition(
                    param.parameterName())
                if isinstance(definition, (QgsProcessingParameterRasterLayer)):
                    self.parentCombo.addItem(definition.description(),
                                             definition.name())
                    if self.param is not None:
                        if self.param.parentLayerParameterName(
                        ) == definition.name():
                            self.parentCombo.setCurrentIndex(idx)
                    idx += 1
            self.verticalLayout.addWidget(self.parentCombo)
        elif self.paramType == parameters.PARAMETER_LAYOUTITEM or \
                isinstance(self.param, QgsProcessingParameterLayoutItem):
            self.verticalLayout.addWidget(QLabel(self.tr('Parent layout')))
            self.parentCombo = QComboBox()
            idx = 0
            for param in list(self.alg.parameterComponents().values()):
                definition = self.alg.parameterDefinition(
                    param.parameterName())
                if isinstance(definition, (QgsProcessingParameterLayout)):
                    self.parentCombo.addItem(definition.description(),
                                             definition.name())
                    if self.param is not None:
                        if self.param.parentLayoutParameterName(
                        ) == definition.name():
                            self.parentCombo.setCurrentIndex(idx)
                    idx += 1
            self.verticalLayout.addWidget(self.parentCombo)
        elif (self.paramType
              in (parameters.PARAMETER_VECTOR, parameters.PARAMETER_TABLE)
              or isinstance(self.param, (QgsProcessingParameterFeatureSource,
                                         QgsProcessingParameterVectorLayer))):
            self.verticalLayout.addWidget(QLabel(self.tr('Geometry type')))
            self.shapetypeCombo = QComboBox()
            self.shapetypeCombo.addItem(self.tr('Geometry Not Required'),
                                        QgsProcessing.TypeVector)
            self.shapetypeCombo.addItem(self.tr('Point'),
                                        QgsProcessing.TypeVectorPoint)
            self.shapetypeCombo.addItem(self.tr('Line'),
                                        QgsProcessing.TypeVectorLine)
            self.shapetypeCombo.addItem(self.tr('Polygon'),
                                        QgsProcessing.TypeVectorPolygon)
            self.shapetypeCombo.addItem(self.tr('Any Geometry Type'),
                                        QgsProcessing.TypeVectorAnyGeometry)
            if self.param is not None:
                self.shapetypeCombo.setCurrentIndex(
                    self.shapetypeCombo.findData(self.param.dataTypes()[0]))
            self.verticalLayout.addWidget(self.shapetypeCombo)
        elif (self.paramType == parameters.PARAMETER_MULTIPLE
              or isinstance(self.param, QgsProcessingParameterMultipleLayers)):
            self.verticalLayout.addWidget(QLabel(self.tr('Data type')))
            self.datatypeCombo = QComboBox()
            self.datatypeCombo.addItem(self.tr('Any Map Layer'),
                                       QgsProcessing.TypeMapLayer)
            self.datatypeCombo.addItem(
                self.tr('Vector (No Geometry Required)'),
                QgsProcessing.TypeVector)
            self.datatypeCombo.addItem(self.tr('Vector (Point)'),
                                       QgsProcessing.TypeVectorPoint)
            self.datatypeCombo.addItem(self.tr('Vector (Line)'),
                                       QgsProcessing.TypeVectorLine)
            self.datatypeCombo.addItem(self.tr('Vector (Polygon)'),
                                       QgsProcessing.TypeVectorPolygon)
            self.datatypeCombo.addItem(self.tr('Vector (Any Geometry Type)'),
                                       QgsProcessing.TypeVectorAnyGeometry)
            self.datatypeCombo.addItem(self.tr('Raster'),
                                       QgsProcessing.TypeRaster)
            self.datatypeCombo.addItem(self.tr('File'), QgsProcessing.TypeFile)
            if self.param is not None:
                self.datatypeCombo.setCurrentIndex(
                    self.datatypeCombo.findData(self.param.layerType()))
            self.verticalLayout.addWidget(self.datatypeCombo)
        elif (self.paramType
              in (parameters.PARAMETER_NUMBER, parameters.PARAMETER_DISTANCE,
                  parameters.PARAMETER_SCALE)
              or isinstance(self.param, (QgsProcessingParameterNumber,
                                         QgsProcessingParameterDistance,
                                         QgsProcessingParameterScale))):

            if (self.paramType == parameters.PARAMETER_DISTANCE
                    or isinstance(self.param, QgsProcessingParameterDistance)):
                self.verticalLayout.addWidget(QLabel(self.tr('Linked input')))
                self.parentCombo = QComboBox()
                self.parentCombo.addItem('', '')
                idx = 1
                for param in list(self.alg.parameterComponents().values()):
                    definition = self.alg.parameterDefinition(
                        param.parameterName())
                    if isinstance(definition,
                                  (QgsProcessingParameterFeatureSource,
                                   QgsProcessingParameterVectorLayer,
                                   QgsProcessingParameterMapLayer,
                                   QgsProcessingParameterCrs)):
                        self.parentCombo.addItem(definition.description(),
                                                 definition.name())
                        if self.param is not None:
                            if self.param.parentParameterName(
                            ) == definition.name():
                                self.parentCombo.setCurrentIndex(idx)
                        idx += 1
                self.verticalLayout.addWidget(self.parentCombo)
            elif (self.paramType != parameters.PARAMETER_SCALE
                  and not isinstance(self.param, QgsProcessingParameterScale)):
                self.verticalLayout.addWidget(QLabel(self.tr('Number type')))
                self.type_combo = QComboBox()
                self.type_combo.addItem(self.tr('Float'),
                                        QgsProcessingParameterNumber.Double)
                self.type_combo.addItem(self.tr('Integer'),
                                        QgsProcessingParameterNumber.Integer)
                if self.param:
                    self.type_combo.setCurrentIndex(
                        self.type_combo.findData(self.param.dataType()))
                self.verticalLayout.addWidget(self.type_combo)

            if (self.paramType != parameters.PARAMETER_SCALE and
                    not isinstance(self.param, QgsProcessingParameterScale)):
                self.verticalLayout.addWidget(QLabel(self.tr('Min value')))
                self.minTextBox = QLineEdit()
                self.verticalLayout.addWidget(self.minTextBox)
                self.verticalLayout.addWidget(QLabel(self.tr('Max value')))
                self.maxTextBox = QLineEdit()
                self.verticalLayout.addWidget(self.maxTextBox)
                if self.param is not None:
                    self.minTextBox.setText(str(self.param.minimum()))
                    self.maxTextBox.setText(str(self.param.maximum()))
            self.verticalLayout.addWidget(QLabel(self.tr('Default value')))
            self.defaultTextBox = QLineEdit()
            self.defaultTextBox.setText(self.tr('0'))
            if self.param is not None:
                default = self.param.defaultValue()
                if self.param.dataType(
                ) == QgsProcessingParameterNumber.Integer:
                    default = int(math.floor(float(default)))
                if default:
                    self.defaultTextBox.setText(str(default))
            self.verticalLayout.addWidget(self.defaultTextBox)
        elif (self.paramType == parameters.PARAMETER_EXPRESSION
              or isinstance(self.param, QgsProcessingParameterExpression)):
            self.verticalLayout.addWidget(QLabel(self.tr('Default value')))
            self.defaultEdit = QgsExpressionLineEdit()
            if self.param is not None:
                self.defaultEdit.setExpression(self.param.defaultValue())
            self.verticalLayout.addWidget(self.defaultEdit)

            self.verticalLayout.addWidget(QLabel(self.tr('Parent layer')))
            self.parentCombo = QComboBox()
            self.parentCombo.addItem(self.tr("None"), None)
            idx = 1
            for param in list(self.alg.parameterComponents().values()):
                definition = self.alg.parameterDefinition(
                    param.parameterName())
                if isinstance(definition, (QgsProcessingParameterFeatureSource,
                                           QgsProcessingParameterVectorLayer)):
                    self.parentCombo.addItem(definition.description(),
                                             definition.name())
                    if self.param is not None:
                        if self.param.parentLayerParameterName(
                        ) == definition.name():
                            self.parentCombo.setCurrentIndex(idx)
                    idx += 1
            self.verticalLayout.addWidget(self.parentCombo)
        elif (self.paramType == parameters.PARAMETER_STRING
              or isinstance(self.param, QgsProcessingParameterString)):
            self.verticalLayout.addWidget(QLabel(self.tr('Default value')))
            self.defaultTextBox = QLineEdit()
            if self.param is not None:
                self.defaultTextBox.setText(self.param.defaultValue())
            self.verticalLayout.addWidget(self.defaultTextBox)
        elif (self.paramType == parameters.PARAMETER_FILE
              or isinstance(self.param, QgsProcessingParameterFile)):
            self.verticalLayout.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.behavior(
                ) == QgsProcessingParameterFile.Folder else 0)
            self.verticalLayout.addWidget(self.fileFolderCombo)
        elif (self.paramType == parameters.PARAMETER_POINT
              or isinstance(self.param, QgsProcessingParameterPoint)):
            self.verticalLayout.addWidget(QLabel(self.tr('Default value')))
            self.defaultTextBox = QLineEdit()
            if self.param is not None:
                self.defaultTextBox.setText(self.param.defaultValue())
            self.verticalLayout.addWidget(self.defaultTextBox)
        elif (self.paramType == parameters.PARAMETER_CRS
              or isinstance(self.param, QgsProcessingParameterCrs)):
            self.verticalLayout.addWidget(QLabel(self.tr('Default value')))
            self.selector = QgsProjectionSelectionWidget()
            if self.param is not None:
                self.selector.setCrs(
                    QgsCoordinateReferenceSystem(self.param.defaultValue()))
            else:
                self.selector.setCrs(QgsCoordinateReferenceSystem('EPSG:4326'))
            self.verticalLayout.addWidget(self.selector)
        elif self.paramType == parameters.PARAMETER_ENUM or \
                isinstance(self.param, QgsProcessingParameterEnum):
            self.widget = EnumModelerWidget(self)
            if self.param is not None:
                self.widget.setAllowMultiple(bool(self.param.allowMultiple()))
                self.widget.setOptions(self.param.options())
                self.widget.setDefault(self.param.defaultValue())
            self.verticalLayout.addWidget(self.widget)
        elif self.paramType == parameters.PARAMETER_MATRIX or \
                isinstance(self.param, QgsProcessingParameterMatrix):
            self.widget = MatrixModelerWidget(self)
            if self.param is not None:
                self.widget.setValue(self.param.headers(),
                                     self.param.defaultValue())
                self.widget.setFixedRows(self.param.hasFixedNumberRows())
            self.verticalLayout.addWidget(self.widget)

        elif isinstance(self.param, QgsProcessingDestinationParameter):
            self.verticalLayout.addWidget(QLabel(self.tr('Default value')))
            self.defaultWidget = DestinationSelectionPanel(
                self.param, self.alg, default_selection=True)
            self.verticalLayout.addWidget(self.defaultWidget)

        self.verticalLayout.addSpacing(20)
        self.requiredCheck = QCheckBox()
        self.requiredCheck.setText(self.tr('Mandatory'))
        self.requiredCheck.setChecked(True)
        if self.param is not None:
            self.requiredCheck.setChecked(
                not self.param.flags()
                & QgsProcessingParameterDefinition.FlagOptional)
        self.verticalLayout.addWidget(self.requiredCheck)

        # If child algorithm output is mandatory, disable checkbox
        if isinstance(self.param, QgsProcessingDestinationParameter):
            provider_name, child_name, output_name = self.param.name().split(
                ':')
            child = self.alg.childAlgorithms()['{}:{}'.format(
                provider_name, child_name)]
            model_output = child.modelOutput(output_name)
            param_def = child.algorithm().parameterDefinition(
                model_output.childOutputName())
            if not (param_def.flags()
                    & QgsProcessingParameterDefinition.FlagOptional):
                self.requiredCheck.setEnabled(False)
                self.requiredCheck.setChecked(True)

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName('buttonBox')
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

        self.verticalLayout.addStretch()
        self.verticalLayout.addWidget(self.buttonBox)

        self.setLayout(self.verticalLayout)
Esempio n. 7
0
    def construct_form_param_user(self, row, pos):

        widget = None
        for field in row[pos]['fields']:
            if field['label']:
                lbl = QLabel()
                lbl.setObjectName('lbl' + field['widgetname'])
                lbl.setText(field['label'])
                lbl.setMinimumSize(160, 0)
                lbl.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
                lbl.setToolTip(field['tooltip'])

                chk = QCheckBox()
                chk.setObjectName('chk_' + field['widgetname'])

                if field['checked'] in ('true', 'True', 'TRUE', True):
                    chk.setChecked(True)
                elif field['checked'] in ('false', 'False', 'FALSE', False):
                    chk.setChecked(False)
                chk.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)

                if field['widgettype'] == 'text' or field[
                        'widgettype'] == 'linetext' or field[
                            'widgettype'] == 'typeahead':
                    widget = QLineEdit()
                    widget.setText(field['value'])
                    widget.editingFinished.connect(
                        partial(self.get_values_changed_param_user, chk,
                                widget, field))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                    if field['widgettype'] == 'typeahead':
                        completer = QCompleter()
                        if 'dv_querytext' in field or 'dv_querytext_filterc' in field:
                            widget.setProperty('typeahead', True)
                            model = QStringListModel()
                            widget.textChanged.connect(
                                partial(self.populate_typeahead, completer,
                                        model, field, self.dlg_config, widget))

                elif field['widgettype'] == 'textarea':
                    widget = QTextEdit()
                    widget.setText(field['value'])
                    widget.editingFinished.connect(
                        partial(self.get_values_changed_param_user, chk,
                                widget, field))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                elif field['widgettype'] == 'combo':
                    widget = QComboBox()
                    self.populate_combo(widget, field)
                    widget.currentIndexChanged.connect(
                        partial(self.get_values_changed_param_user, chk,
                                widget, field))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                elif field['widgettype'] == 'check':
                    widget = chk
                    widget.stateChanged.connect(
                        partial(self.get_values_changed_param_user, chk, chk,
                                field))
                    widget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
                elif field['widgettype'] == 'datetime':
                    widget = QgsDateTimeEdit()
                    widget.setAllowNull(True)
                    widget.setCalendarPopup(True)
                    widget.setDisplayFormat('dd/MM/yyyy')

                    if field['value']:
                        field['value'] = field['value'].replace('/', '-')
                    date = QDate.fromString(field['value'], 'yyyy-MM-dd')
                    if date:
                        widget.setDate(date)
                    else:
                        widget.clear()
                    widget.dateChanged.connect(
                        partial(self.get_values_changed_param_user, chk,
                                widget, field))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                elif field['widgettype'] == 'spinbox':
                    widget = QDoubleSpinBox()
                    if 'value' in field and field['value'] is not None:
                        value = float(str(field['value']))
                        widget.setValue(value)
                    widget.valueChanged.connect(
                        partial(self.get_values_changed_param_user, chk,
                                widget, field))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                else:
                    pass

                widget.setObjectName(field['widgetname'])

                # Set signals
                chk.stateChanged.connect(
                    partial(self.get_values_checked_param_user, chk, widget,
                            field))

                if field['layoutname'] == 'lyt_basic':
                    self.order_widgets(field, self.basic_form, lbl, chk,
                                       widget)
                elif field['layoutname'] == 'lyt_om':
                    self.order_widgets(field, self.om_form, lbl, chk, widget)
                elif field['layoutname'] == 'lyt_inventory':
                    self.order_widgets(field, self.inventory_form, lbl, chk,
                                       widget)
                elif field['layoutname'] == 'lyt_mapzones':
                    self.order_widgets(field, self.mapzones_form, lbl, chk,
                                       widget)
                elif field['layoutname'] == 'lyt_edit':
                    self.order_widgets(field, self.cad_form, lbl, chk, widget)
                elif field['layoutname'] == 'lyt_epa':
                    self.order_widgets(field, self.epa_form, lbl, chk, widget)
                elif field['layoutname'] == 'lyt_masterplan':
                    self.order_widgets(field, self.masterplan_form, lbl, chk,
                                       widget)
                elif field['layoutname'] == 'lyt_other':
                    self.order_widgets(field, self.other_form, lbl, chk,
                                       widget)
                elif field['layoutname'] == 'lyt_node_vdef':
                    self.order_widgets(field, self.node_type_form, lbl, chk,
                                       widget)
                elif field['layoutname'] == 'lyt_arc_vdef':
                    self.order_widgets(field, self.cat_form, lbl, chk, widget)
                elif field['layoutname'] == 'lyt_utils_vdef':
                    self.order_widgets(field, self.utils_form, lbl, chk,
                                       widget)
                elif field['layoutname'] == 'lyt_connec_vdef':
                    self.order_widgets(field, self.connec_form, lbl, chk,
                                       widget)
                elif field['layoutname'] == 'lyt_gully_vdef':
                    self.order_widgets(field, self.gully_form, lbl, chk,
                                       widget)
                elif field['layoutname'] == 'lyt_fluid_type':
                    self.order_widgets(field, self.fluid_type_form, lbl, chk,
                                       widget)
                elif field['layoutname'] == 'lyt_location_type':
                    self.order_widgets(field, self.location_type_form, lbl,
                                       chk, widget)
                elif field['layoutname'] == 'lyt_category_type':
                    self.order_widgets(field, self.category_type_form, lbl,
                                       chk, widget)
                elif field['layoutname'] == 'lyt_function_type':
                    self.order_widgets(field, self.function_type_form, lbl,
                                       chk, widget)
                elif field['layoutname'] == 'lyt_addfields':
                    self.order_widgets(field, self.addfields_form, lbl, chk,
                                       widget)
Esempio n. 8
0
    def __select_wfs_layer(self) -> None:

        indexes = self.tbl_wdgt_stored_queries.selectedIndexes()
        if not indexes:
            LOGGER.warning(
                tr("Could not execute select"),
                extra=bar_msg(tr("Data source must be selected first!")),
            )
            return
        self.selected_stored_query = self.stored_queries[indexes[0].row()]
        LOGGER.info(
            tr("Selected query id: {}",
               self.selected_stored_query.id))  # type: ignore # noqa E501
        self.sq_factory.expand(self.selected_stored_query)  # type: ignore

        for widget_set in self.parameter_rows.values():
            for widget in widget_set:
                if isinstance(widget, QVBoxLayout):
                    self.grid.removeItem(widget)
                else:
                    self.grid.removeWidget(widget)
                    widget.hide()
                widget.setParent(None)
                widget = None
        self.parameter_rows = {}

        row_idx = -1
        self.extent_group_box_bbox.setEnabled(False)
        for param_name, parameter in self.selected_stored_query.parameters.items(
        ):  # type: ignore # noqa E501
            possible_values = parameter.possible_values
            widgets = set()  # type: ignore
            if parameter.type in (QVariant.Rect, QVariant.RectF):
                self.parameter_rows[param_name] = widgets
                self.extent_group_box_bbox.setEnabled(True)
                if possible_values:
                    dataset_extent = QgsRectangle(
                        *(map(float, possible_values[0].split(","))))
                    current_extent: QgsRectangle = (
                        self.extent_group_box_bbox.outputExtent())
                    extent_msg = tr(
                        "Your extent: {}, dataset maximum extent: {}",
                        current_extent.toString(2),
                        dataset_extent.toString(2),
                    )

                    if dataset_extent.area() / current_extent.area() > 100:
                        LOGGER.warning(
                            tr("Big difference in bounding boxes"),
                            extra=bar_msg(
                                tr(
                                    "You might want to get a larger extent. {}",
                                    extent_msg,
                                )),
                        )
                    elif current_extent.area() / dataset_extent.area() > 100:
                        LOGGER.warning(
                            tr("Big difference in bounding boxes"),
                            extra=bar_msg(
                                tr(
                                    "You might want to get a smaller extent. {}",
                                    extent_msg,
                                )),
                        )

                    if not current_extent.toRectF().intersects(
                            dataset_extent.toRectF()):
                        LOGGER.warning(
                            tr("Your bounding box and dataset bounding "
                               "box do not intersect"),
                            extra=bar_msg(
                                tr(
                                    "You might want to change your extent. {}",
                                    extent_msg,
                                )),
                        )
                continue
            row_idx += 1
            widget: QWidget = widget_for_field(parameter.type)  # type: ignore
            if (isinstance(widget, QComboBox) or isinstance(widget, QSpinBox)
                    or isinstance(widget, QgsDoubleSpinBox)):
                widget = QLineEdit()
                if possible_values:
                    if len(possible_values) == 1:
                        widget.setText(possible_values[0])
                    else:
                        widget = QComboBox()
                        widget.addItems(possible_values)
                        widget.setEditable(True)

            if isinstance(widget, QgsDateTimeEdit) and possible_values:
                widget.setDateTimeRange(min(possible_values),
                                        max(possible_values))
                if param_name.startswith("end"):
                    widget.setDateTime(max(possible_values))
                else:
                    widget.setDateTime(min(possible_values))
                if len(possible_values) == 1:
                    widget.setEnabled(False)

            widget.setToolTip(parameter.abstract)

            if parameter.type == QVariant.StringList:
                if parameter.has_variables():
                    widget = QVBoxLayout()
                    widget.addStretch(1)
                    for variable in parameter.variables:
                        box = QCheckBox(text=variable.alias)
                        box.setToolTip(variable.label)
                        widgets.add(box)
                        widget.addWidget(box)
                        LOGGER.info(tr("Variables: {}", variable.alias))

            # TODO: all others
            if widget is None:
                LOGGER.error(
                    tr("Unknown parameter type"),
                    extra=bar_msg(
                        tr('With parameter"{}": {}', param_name,
                           parameter.type)),
                )
                return
            label = QLabel(text=parameter.name)
            label.setToolTip(parameter.abstract)

            widgets.update({label, widget})

            self.grid.addWidget(label, row_idx, 1)
            if isinstance(widget, QVBoxLayout):
                self.grid.addLayout(widget, row_idx, 2)
            else:
                self.grid.addWidget(widget, row_idx, 2)
            self.parameter_rows[param_name] = widgets
Esempio n. 9
0
    def __init__(self, canvas, pare=None):
        """[summary]
        Arguments:
            canvas {[QgsMapCanvas]} -- [El canvas que es vol gestionar]


        """
        self.pare = pare
        self.canvas = canvas
        QWidget.__init__(self)

        # Leemos un fichero serializado para cargar sus ubicaciones en data
        try:
            with open(fic_guardar_arbre, 'rb') as fga:
                data = pickle.load(fga)
                fga.close()
        except:
            data = []

        # Instanciamos ARBOL ************************************************************+*****
        self.arbre = QTreeView()

        # Ponemos menu contextual l arbol
        self.arbre.setContextMenuPolicy(Qt.ActionsContextMenu)
        self.actEsborrar = QAction("Esborrar branca", self)
        self.actEsborrar.setStatusTip("Esborrar")
        self.actEsborrar.triggered.connect(self.esborrarNode)
        self.arbre.addAction(self.actEsborrar)

        self.actExpand = QAction("Expandeix/Contreu Tot", self)
        self.actExpand.setStatusTip("Expand")
        self.actExpand.triggered.connect(self.expand_all)
        self.arbre.addAction(self.actExpand)

        self.actClear = QAction("Esborrar arbre", self)
        self.actClear.setStatusTip("Clear")
        self.actClear.triggered.connect(self.clear_all)
        self.arbre.addAction(self.actClear)

        # Permitimos arrastre de ramas en arbol
        self.arbre.setDragDropMode(
            QAbstractItemView.InternalMove)  #  4atencion  internal
        # Amaguem (o no) les capçaleres. False és que no s'amaguen.
        # self.arbre.setHeaderHidden(True)  #aqui
        # self.arbre.setColumnWidth(0,8000)
        # self.arbre.setHorizontalScrollBarPolicy(1)

        self.arbre.clicked.connect(self._clickArbre)

        # Fem visible l'arbre
        self.arbre.show()

        # Instanciamos MODELO *********************************************************************
        self.model = StandardItemModel_mio(data, ubicacions=self)

        # asignamos al arbol el modelo
        self.arbre.setModel(self.model)

        #Amaguem totes les columnes menys la primera
        for i in range(self.model.columnCount()):
            if i != 0:
                self.arbre.setColumnHidden(
                    i, False
                )  # atencion, si oculto columnas no puedo ver coordenadas de los hijos

        # Connectem el click de l'arbre a la funció _clickArbre

        # no_se
        self.selectionModel = self.arbre.selectionModel()

        # Cal un invisibleRootItem  qu eés la arrel del arbre d'on penjen els elements de la base.
        self.arrelModel = self.model.invisibleRootItem()

        # Definim els labels del arbre.
        self.labels = ['Ubicació', 'xMin', 'yMin', 'xMax', 'yMax', 'Projecte']
        # En funció  d'aquests labels s'estableix el numero de columnes que tindrà el model (i l'arbre)
        self.model.setColumnCount(len(self.labels))
        # Coloquem els labels com a headers del model (i l'arbre)
        self.model.setHorizontalHeaderLabels(self.labels)

        # ELEMENTOS GRAFICOS DE LA CLASE
        # Definim un lineEdit, li afegim un tooltip i el connectem a una funció quan es premi Return
        self.leUbicacions = QLineEdit()
        self.leUbicacions.setToolTip(
            'Escriu el nom de la ubicació i prem Return')
        self.leUbicacions.returnPressed.connect(self._novaUbicacio)

        #Definimos un boton para guardar las ubicaciones
        icon = QIcon()
        fichero = './imatges/guardar.png'
        icon.addPixmap(QPixmap(fichero))
        # icon.addPixmap(QPixmap("D:/projectes_py/qVista/imatges/guardar.png"))

        # self.boton_1 = QPushButton(icon,'')
        # self.boton_1.setToolTip("Desar ubicacions")
        # self.boton_1.setMaximumSize(QSize(20,20))
        # self.boton_1.show()
        # self.boton_1.clicked.connect(self.model.exportData)

        self.lblubicacio = QLabel('Ubicació:')

        # Creamos un caja de diseño vertical que s'aplica al widget QvUbicacions
        self.layVUbicacions = QVBoxLayout(self)
        # Creamos una caja de diseño horizontal
        self.layHUbicacions = QHBoxLayout()
        # incluimos en la caja horizontal el line edit y el boton (entran de izquierda a derecha)
        self.layHUbicacions.addWidget(self.lblubicacio)
        self.layHUbicacions.addWidget(self.leUbicacions)
        # self.layHUbicacions.addWidget(self.boton_1)  # y colocacion en contenidor horizontal

        # incluimos en caja vertical el la caja horizontal y el arbol  (entran desde abajo)
        self.layVUbicacions.addLayout(self.layHUbicacions)
        self.layVUbicacions.addWidget(self.arbre)

        # Podriem afegir un frame (fBotonera), sobre el que carregar botons
        # self.layUbicacions.addWidget(self.fBotonera)

        # PARA QUE HAGA CASO HA DE PONERSE ESTAS LINEAS POST .SETMODEL
        self.arbre.setHeaderHidden(True)  #aqui
        self.arbre.setColumnWidth(0, 8000)
        self.arbre.setHorizontalScrollBarPolicy(1)
Esempio n. 10
0
    def initGui(self):
        # Create action that will start plugin configuration
        runIcon = QIcon(os.path.join(self.plugin_dir, 'icon_add_service.svg'))
        self.run_action = QAction(runIcon, \
            "PDOK Services plugin", self.iface.mainWindow())

        self.servicesLoaded = False
        # connect the action to the run method
        # 2018 may: RD: deprecating Docked window, as the content is getting to big anyway
        # if "True" == self.docked or "true" == self.docked or  True == self.docked:
        #     self.run_action.triggered.connect(self.showAndRaise)
        #     self.dlg.radioDocked.setChecked(True)
        #     # docked the dialog is immidiately visible, so should run NOW
        # else:
        #     self.run_action.triggered.connect(self.run)
        #     self.dlg.radioDocked.setChecked(False)
        #     self.setupfq()
        self.run_action.triggered.connect(self.run)
        #self.dlg.radioDocked.setChecked(False)
        self.setupfq()

        # Add toolbar button and menu item
        #self.iface.addToolBarIcon(self.action)

        self.toolbar = self.iface.addToolBar("PDOK services plugin")
        self.toolbar.setObjectName("PDOK services plugin")
        self.toolbar.addAction(self.run_action)
        self.toolbarSearch = QLineEdit()
        self.toolbarSearch.setMaximumWidth(200)
        self.toolbarSearch.setAlignment(Qt.AlignLeft)
        self.toolbarSearch.setPlaceholderText("PDOK Locatieserver zoek")
        self.toolbar.addWidget(self.toolbarSearch)
        self.toolbarSearch.returnPressed.connect(self.searchAddressFromToolbar)
        # address/point cleanup
        eraserIcon = QIcon(
            os.path.join(self.plugin_dir, 'icon_remove_cross.svg'))
        self.clean_action = QAction(eraserIcon, \
            "Cleanup", self.eraseAddress())
        self.toolbar.addAction(self.clean_action)
        self.clean_action.triggered.connect(self.eraseAddress)
        self.clean_action.setEnabled(False)

        self.iface.addPluginToMenu(u"&Pdok Services Plugin", self.run_action)

        # about
        self.aboutAction = QAction(QIcon(":/plugins/pdokservicesplugin/icon_help.png"), \
                            "About", self.iface.mainWindow())
        self.aboutAction.setWhatsThis("Pdok Services Plugin About")
        self.iface.addPluginToMenu(u"&Pdok Services Plugin", self.aboutAction)

        self.aboutAction.triggered.connect(self.about)
        self.dlg.ui.btnLoadLayer.clicked.connect(self.loadService)

        self.dlg.geocoderSearch.returnPressed.connect(self.searchAddress)

        self.dlg.geocoderSearch.textEdited.connect(self.searchAddress)
        self.dlg.geocoderSearch.setPlaceholderText(
            "PDOK Locatieserver zoek, bv postcode of postcode huisnummer")

        self.dlg.geocoderResultSearch.textChanged.connect(
            self.filterGeocoderResult)
        self.dlg.geocoderResultSearch.setPlaceholderText(
            "een of meer zoekwoorden uit resultaat")

        #self.dlg.radioDocked.toggled.connect(self.set_docked)

        self.dlg.btnCheckPdokJson.clicked.connect(self.checkPdokJson)
        #self.iface.mapCanvas().renderStarting.connect(self.extentsChanged)

        ui = self.dlg.ui
        cbxs = [
            ui.cbx_gem, ui.cbx_wpl, ui.cbx_weg, ui.cbx_pcd, ui.cbx_adr,
            ui.cbx_pcl, ui.cbx_hmp
        ]
        # connect all fq checkboxes with suggest, so upon a change in fq filter we re-search
        for cbx in cbxs:
            cbx.stateChanged.connect(self.searchAddress)

        self.run(True)
    def __init__(self, iface):
        QtWidgets.QDialog.__init__(self)
        self.iface = iface
        self.setupUi(self)

        self.path = standard_path()
        self.error = None
        self.report = []
        self.worker_thread = None
        self.running = False
        self.bbox = None
        self.json = []
        self.project = None
        self.logger = logging.getLogger("aequilibrae")

        self._run_layout = QGridLayout()

        # Area to import network for
        self.choose_place = QRadioButton()
        self.choose_place.setText("Place name")
        self.choose_place.toggled.connect(self.change_place_type)
        self.choose_place.setChecked(False)

        self.choose_canvas = QRadioButton()
        self.choose_canvas.setText("Current map canvas area")
        self.choose_canvas.setChecked(True)

        self.place = QLineEdit()
        self.place.setVisible(False)

        self.source_type_frame = QVBoxLayout()
        self.source_type_frame.setAlignment(Qt.AlignLeft)
        self.source_type_frame.addWidget(self.choose_place)
        self.source_type_frame.addWidget(self.choose_canvas)
        self.source_type_frame.addWidget(self.place)

        self.source_type_widget = QGroupBox('Target')
        self.source_type_widget.setLayout(self.source_type_frame)

        # Buttons and output
        self.but_choose_output = QPushButton()
        self.but_choose_output.setText("Choose file output")
        self.but_choose_output.clicked.connect(self.choose_output)

        self.output_path = QLineEdit()

        self.but_run = QPushButton()
        self.but_run.setText("Import network and create project")
        self.but_run.clicked.connect(self.run)

        self.buttons_frame = QVBoxLayout()
        self.buttons_frame.addWidget(self.but_choose_output)
        self.buttons_frame.addWidget(self.output_path)
        self.buttons_frame.addWidget(self.but_run)

        self.buttons_widget = QWidget()
        self.buttons_widget.setLayout(self.buttons_frame)

        self.progressbar = QProgressBar()
        self.progress_label = QLabel()

        self.update_widget = QWidget()
        self.update_frame = QVBoxLayout()
        self.update_frame.addWidget(self.progressbar)
        self.update_frame.addWidget(self.progress_label)
        self.update_widget.setLayout(self.update_frame)
        self.update_widget.setVisible(False)

        self._run_layout.addWidget(self.source_type_widget)
        self._run_layout.addWidget(self.buttons_widget)
        self._run_layout.addWidget(self.update_widget)

        self.setLayout(self._run_layout)
        self.resize(280, 250)
Esempio n. 12
0
    def generateRestrictionForVehiclesForm(self):

        QgsMessageLog.logMessage(
            "In generateRestrictionForVehiclesForm::generateForm ... ",
            tag="TOMs panel")

        layout = QFormLayout()
        # Add restriction for vehicles type
        self.cb_restrictionForVehiclesType = QComboBox(self)
        enumList = self.getEnumList('RestrictionTypeValue')
        self.cb_restrictionForVehiclesType.addItems(enumList)
        layout.addRow(self.tr("&Access Restriction Type:"),
                      self.cb_restrictionForVehiclesType)

        # add measure
        self.le_restrictionForVehiclesMeasure = QLineEdit()
        self.le_restrictionForVehiclesMeasure.setValidator(
            QDoubleValidator(0.99, 999.99, 2))
        layout.addRow(self.tr("&Measure (in metric units):"),
                      self.le_restrictionForVehiclesMeasure)

        # add measure
        self.le_restrictionForVehiclesMeasure2 = QLineEdit()
        self.le_restrictionForVehiclesMeasure2.setValidator(
            QDoubleValidator(0.99, 999.99, 2))
        layout.addRow(
            self.tr("&Measure (in imperial units) [only if present]:"),
            self.le_restrictionForVehiclesMeasure2)

        # Add vehicle exemption
        self.cb_restrictionForVehiclesVehicleExemptions = QComboBox(self)
        enumList = self.getTableList('"moving_traffic"."vehicleQualifiers"')
        self.cb_restrictionForVehiclesVehicleExemptions.addItems(enumList)
        layout.addRow(self.tr("&Vehicle exemptions:"),
                      self.cb_restrictionForVehiclesVehicleExemptions)

        # Add vehicle inclusions
        self.cb_restrictionForVehiclesVehicleInclusions = QComboBox(self)
        enumList = self.getTableList('"moving_traffic"."vehicleQualifiers"')
        self.cb_restrictionForVehiclesVehicleInclusions.addItems(enumList)
        layout.addRow(self.tr("&Vehicle inclusions:"),
                      self.cb_restrictionForVehiclesVehicleInclusions)

        # add structure type
        self.cb_restrictionForVehiclesStructureType = QComboBox(self)
        enumList = self.getEnumList('StructureTypeValue')
        self.cb_restrictionForVehiclesStructureType.addItems(enumList)
        layout.addRow(self.tr("&Structure Type:"),
                      self.cb_restrictionForVehiclesStructureType)

        # add traffic sign
        """self.cb_trafficSign = QComboBox(self)
        enumList = self.getTableList('Signs')
        self.cb_timePeriods.addItems(enumList)
        layout.addRow(self.tr("&Traffic Sign:"), self.cb_timePeriods)"""

        self.restrictionForVehiclesAttributeStack.setLayout(layout)

        geomLayout = QFormLayout()
        self.btn_PointReference = QPushButton("Location")
        self.btn_PointReference.clicked.connect(self.getPointReference)
        geomLayout.addRow(self.tr("&Restriction For Vehicle Location:"),
                          self.btn_PointReference)

        # add link direction
        self.cb_restrictionForVehiclesLinkDirectionValue = QComboBox(self)
        enumList = self.getEnumList('LinkDirectionValue')
        self.cb_restrictionForVehiclesLinkDirectionValue.addItems(enumList)
        geomLayout.addRow(self.tr("&Applicable link direction:"),
                          self.cb_restrictionForVehiclesLinkDirectionValue)

        self.restrictionForVehiclesGeometryStack.setLayout(geomLayout)

        # create relevant features
        """
Esempio n. 13
0
    def __init__(self, parent, params):

        QDialog.__init__(self, parent)

        self.parent = parent
        self.params = params

        self.setMinimumWidth(min_width)

        # Build dialog
        self.setWindowTitle('Options - Times')  # TODO: softcode
        self.setWindowModality(QtCore.Qt.ApplicationModal)

        self.fra_form = QFrame(self)
        fra_form_lay = QFormLayout(self.fra_form)
        fra_form_lay.setContentsMargins(10, 10, 10, 10)

        self.lbl_units = QLabel('Units:')  # TODO: softocode
        self.cbo_units = QComboBox()
        fra_form_lay.addRow(self.lbl_units, self.cbo_units)

        self.lbl_duration = QLabel('Duration:')  # TODO: softocode
        self.txt_duration = QLineEdit()
        fra_form_lay.addRow(self.lbl_duration, self.txt_duration)

        self.lbl_hydraulic_timestep = QLabel('Hydraulic timestep:')  # TODO: softocode
        self.txt_hydraulic_timestep = QLineEdit()
        fra_form_lay.addRow(self.lbl_hydraulic_timestep, self.txt_hydraulic_timestep)

        self.lbl_quality_timestep = QLabel('Quality timestep:')  # TODO: softocode
        self.txt_quality_timestep = QLineEdit()
        fra_form_lay.addRow(self.lbl_quality_timestep, self.txt_quality_timestep)

        self.lbl_rule_timestep = QLabel('Rule timestep:')  # TODO: softocode
        self.txt_rule_timestep = QLineEdit()
        fra_form_lay.addRow(self.lbl_rule_timestep, self.txt_rule_timestep)

        self.lbl_pattern_timestep = QLabel('Pattern timestep:')  # TODO: softocode
        self.txt_pattern_timestep = QLineEdit()
        fra_form_lay.addRow(self.lbl_pattern_timestep, self.txt_pattern_timestep)

        self.lbl_pattern_start = QLabel('Pattern start:')  # TODO: softocode
        self.txt_pattern_start = QLineEdit()
        fra_form_lay.addRow(self.lbl_pattern_start, self.txt_pattern_start)

        self.lbl_report_timestep = QLabel('Report timestep:')  # TODO: softocode
        self.txt_report_timestep = QLineEdit()
        fra_form_lay.addRow(self.lbl_report_timestep, self.txt_report_timestep)

        self.lbl_report_start = QLabel('Report start:')  # TODO: softocode
        self.txt_report_start = QLineEdit()
        fra_form_lay.addRow(self.lbl_report_start, self.txt_report_start)

        self.lbl_clock_time_start = QLabel('Clock start time:')  # TODO: softocode
        self.txt_clock_time_start = QLineEdit()
        fra_form_lay.addRow(self.lbl_clock_time_start, self.txt_clock_time_start)

        self.lbl_statistic = QLabel('Statistic:')  # TODO: softocode
        self.cbo_statistic = QComboBox()
        fra_form_lay.addRow(self.lbl_statistic, self.cbo_statistic)

        # Buttons
        self.fra_buttons = QFrame(self)
        fra_buttons_lay = QHBoxLayout(self.fra_buttons)
        self.btn_Ok = QPushButton('OK')
        self.btn_Cancel = QPushButton('Cancel')
        fra_buttons_lay.addWidget(self.btn_Ok)
        fra_buttons_lay.addWidget(self.btn_Cancel)

        # Add to main
        fra_main_lay = QVBoxLayout(self)
        fra_main_lay.setContentsMargins(0, 0, 0, 0)
        fra_main_lay.addWidget(self.fra_form)
        fra_main_lay.addWidget(self.fra_buttons)

        self.setup()
Esempio n. 14
0
    def __init__(self, parent, params, new_proj=False):
        QDialog.__init__(self, parent)

        self.parent = parent
        self.params = params
        self.new_proj = new_proj

        self.setMinimumWidth(min_width)
        # self.setMinimumHeight(min_height)

        # Build dialog
        self.setWindowTitle('Options - Hydraulics')  # TODO: softcode
        self.setWindowModality(QtCore.Qt.ApplicationModal)

        self.fra_form = QFrame(self)
        fra_form_lay = QFormLayout(self.fra_form)
        fra_form_lay.setContentsMargins(10, 10, 10, 10)

        self.lbl_units = QLabel('Units system:') # TODO: softocode
        self.cbo_units = QComboBox()
        fra_form_lay.addRow(self.lbl_units, self.cbo_units)

        self.lbl_flow_units = QLabel('Flow units:')  # TODO: softocode
        self.cbo_flow_units = QComboBox()
        fra_form_lay.addRow(self.lbl_flow_units, self.cbo_flow_units)

        self.lbl_headloss = QLabel('Head loss:')  # TODO: softocode
        self.cbo_headloss = QComboBox()
        fra_form_lay.addRow(self.lbl_headloss, self.cbo_headloss)

        self.chk_hydraulics = QCheckBox('Hydraulics:') # TODO: softcode
        self.cbo_hydraulics = QComboBox()
        fra_form_lay.addRow(self.chk_hydraulics, self.cbo_hydraulics)

        self.txt_hydraulics_file = QLineEdit()
        fra_form_lay.addRow(None, self.txt_hydraulics_file)

        self.btn_hydraulics_file = QPushButton('File...')  # TODO: softcode
        fra_form_lay.addRow(None, self.btn_hydraulics_file)

        self.lbl_viscosity = QLabel('Viscosity:')  # TODO: softocode
        self.txt_viscosity = QLineEdit()
        fra_form_lay.addRow(self.lbl_viscosity, self.txt_viscosity)

        # self.lbl_diffusivity = QLabel('Diffusivity:')  # TODO: softocode
        # self.txt_diffusivity = QLineEdit()
        # fra_form_lay.addRow(self.lbl_diffusivity, self.txt_diffusivity)

        self.lbl_spec_gravity = QLabel('Specific gravity:')  # TODO: softocode
        self.txt_spec_gravity = QLineEdit()
        fra_form_lay.addRow(self.lbl_spec_gravity, self.txt_spec_gravity)

        self.lbl_max_trials = QLabel('Max trials:')  # TODO: softocode
        self.txt_max_trials = QLineEdit()
        fra_form_lay.addRow(self.lbl_max_trials, self.txt_max_trials)

        self.lbl_accuracy = QLabel('Accuracy:')  # TODO: softocode
        self.txt_accuracy = QLineEdit()
        fra_form_lay.addRow(self.lbl_accuracy, self.txt_accuracy)

        self.lbl_unbalanced = QLabel('Unbalanced:') # TODO: softcode
        self.fra_unbalanced = QFrame(self)
        fra_unbalanced_lay = QHBoxLayout(self.fra_unbalanced)
        fra_unbalanced_lay.setContentsMargins(0, 0, 0, 0)
        self.cbo_unbalanced = QComboBox()
        self.txt_unbalanced = QLineEdit()
        fra_unbalanced_lay.addWidget(self.cbo_unbalanced)
        fra_unbalanced_lay.addWidget(self.txt_unbalanced)
        fra_form_lay.addRow(self.lbl_unbalanced, self.fra_unbalanced)

        self.lbl_pattern = QLabel('Pattern:')  # TODO: softocode
        self.cbo_pattern = QComboBox()
        fra_form_lay.addRow(self.lbl_pattern, self.cbo_pattern)

        self.lbl_demand_mult = QLabel('Demand multiplier:')  # TODO: softocode
        self.txt_demand_mult = QLineEdit()
        fra_form_lay.addRow(self.lbl_demand_mult, self.txt_demand_mult)

        self.lbl_emitter_exp = QLabel('Emitter exponent:')  # TODO: softocode
        self.txt_emitter_exp = QLineEdit()
        fra_form_lay.addRow(self.lbl_emitter_exp, self.txt_emitter_exp)

        self.lbl_tolerance = QLabel('Tolerance:')  # TODO: softocode
        self.txt_tolerance = QLineEdit()
        fra_form_lay.addRow(self.lbl_tolerance, self.txt_tolerance)

        # Buttons
        self.fra_buttons = QFrame(self)
        fra_buttons_lay = QHBoxLayout(self.fra_buttons)
        self.btn_Cancel = QPushButton('Cancel')
        self.btn_Ok = QPushButton('OK')
        fra_buttons_lay.addWidget(self.btn_Ok)
        fra_buttons_lay.addWidget(self.btn_Cancel)

        # Add to main
        fra_main_lay = QVBoxLayout(self)
        fra_main_lay.setContentsMargins(0, 0, 0, 0)
        fra_main_lay.addWidget(self.fra_form)
        fra_main_lay.addWidget(self.fra_buttons)

        self.setup()
Esempio n. 15
0
 def createBCWidget(self, mainWidget):
     newWidget = QLineEdit(mainWidget)  # QtGui.QSpinBox(mainWidget)
     # newWidget.setMinimum(-1000000)
     # newWidget.setValue(-1)
     newWidget.setText("0001 BC")
     return newWidget
Esempio n. 16
0
    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)
Esempio n. 17
0
    def setupUi(self):
        self.checkBoxes = {}
        self.showAdvanced = False
        self.wrappers = {}
        self.valueItems = {}
        self.dependentItems = {}
        self.algorithmItem = None

        self.resize(650, 450)
        self.buttonBox = QDialogButtonBox()
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok | QDialogButtonBox.Help)
        self.setSizePolicy(QSizePolicy.Expanding,
                           QSizePolicy.Expanding)
        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.setSpacing(5)
        self.verticalLayout.setMargin(20)

        self.bar = QgsMessageBar()
        self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.verticalLayout.addWidget(self.bar)

        hLayout = QHBoxLayout()
        hLayout.setSpacing(5)
        hLayout.setMargin(0)
        descriptionLabel = QLabel(self.tr("Description"))
        self.descriptionBox = QLineEdit()
        self.descriptionBox.setText(self._alg.displayName())
        hLayout.addWidget(descriptionLabel)
        hLayout.addWidget(self.descriptionBox)
        self.verticalLayout.addLayout(hLayout)
        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)
        self.verticalLayout.addWidget(line)
        self.algorithmItem = QgsGui.instance().processingGuiRegistry().algorithmConfigurationWidget(self._alg)
        if self.configuration:
            self.algorithmItem.setConfiguration(self.configuration)
        self.verticalLayout.addWidget(self.algorithmItem)

        widget_context = QgsProcessingParameterWidgetContext()
        if iface is not None:
            widget_context.setMapCanvas(iface.mapCanvas())
        widget_context.setModel(self.model)
        widget_context.setModelChildAlgorithmId(self.childId)

        for param in self._alg.parameterDefinitions():
            if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced:
                self.advancedButton = QPushButton()
                self.advancedButton.setText(self.tr('Show advanced parameters'))
                self.advancedButton.clicked.connect(
                    self.showAdvancedParametersClicked)
                advancedButtonHLayout = QHBoxLayout()
                advancedButtonHLayout.addWidget(self.advancedButton)
                advancedButtonHLayout.addStretch()
                self.verticalLayout.addLayout(advancedButtonHLayout)
                break
        for param in self._alg.parameterDefinitions():
            if param.isDestination() or param.flags() & QgsProcessingParameterDefinition.FlagHidden:
                continue

            wrapper = WidgetWrapperFactory.create_wrapper(param, self)
            self.wrappers[param.name()] = wrapper

            if issubclass(wrapper.__class__, QgsProcessingModelerParameterWidget):
                wrapper.setWidgetContext(widget_context)
                wrapper.registerProcessingContextGenerator(self.context_generator)
                widget = wrapper
            else:
                widget = wrapper.widget
            if widget is not None:
                self.valueItems[param.name()] = widget

                if issubclass(wrapper.__class__, QgsProcessingModelerParameterWidget):
                    label = wrapper.createLabel()
                else:
                    tooltip = param.description()
                    widget.setToolTip(tooltip)
                    label = wrapper.label
                self.widget_labels[param.name()] = label

                if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced:
                    label.setVisible(self.showAdvanced)
                    widget.setVisible(self.showAdvanced)

                self.verticalLayout.addWidget(label)
                self.verticalLayout.addWidget(widget)

        for dest in self._alg.destinationParameterDefinitions():
            if dest.flags() & QgsProcessingParameterDefinition.FlagHidden:
                continue
            if isinstance(dest, (QgsProcessingParameterRasterDestination, QgsProcessingParameterVectorDestination,
                                 QgsProcessingParameterFeatureSink, QgsProcessingParameterFileDestination, QgsProcessingParameterFolderDestination)):
                label = QLabel(dest.description())
                item = QgsFilterLineEdit()
                if hasattr(item, 'setPlaceholderText'):
                    item.setPlaceholderText(self.tr('[Enter name if this is a final result]'))
                self.verticalLayout.addWidget(label)
                self.verticalLayout.addWidget(item)
                self.valueItems[dest.name()] = item

        label = QLabel(' ')
        self.verticalLayout.addWidget(label)
        label = QLabel(self.tr('Parent algorithms'))
        self.dependenciesPanel = self.getDependenciesPanel()
        self.verticalLayout.addWidget(label)
        self.verticalLayout.addWidget(self.dependenciesPanel)
        self.verticalLayout.addStretch(1000)

        self.setPreviousValues()
        self.setWindowTitle(self._alg.displayName())
        self.verticalLayout2 = QVBoxLayout()
        self.verticalLayout2.setSpacing(2)
        self.verticalLayout2.setMargin(0)

        self.paramPanel = QWidget()
        self.paramPanel.setLayout(self.verticalLayout)
        self.scrollArea = QgsScrollArea()
        self.scrollArea.setWidget(self.paramPanel)
        self.scrollArea.setWidgetResizable(True)

        self.verticalLayout2.addWidget(self.scrollArea)
        self.verticalLayout2.addWidget(self.buttonBox)
        self.setLayout(self.verticalLayout2)
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)
        self.buttonBox.helpRequested.connect(self.openHelp)
        QMetaObject.connectSlotsByName(self)
Esempio n. 18
0
 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
Esempio n. 19
0
    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()))
Esempio n. 20
0
    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)
Esempio n. 21
0
    def construct_form_param_system(self, row, pos):

        widget = None
        for field in row[pos]['fields']:
            if field['label']:
                lbl = QLabel()
                lbl.setObjectName('lbl' + field['widgetname'])
                lbl.setText(field['label'])
                lbl.setMinimumSize(160, 0)
                lbl.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
                lbl.setToolTip(field['tooltip'])

                if field['widgettype'] == 'text' or field[
                        'widgettype'] == 'linetext':
                    widget = QLineEdit()
                    widget.setText(field['value'])
                    widget.editingFinished.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                elif field['widgettype'] == 'textarea':
                    widget = QTextEdit()
                    widget.setText(field['value'])
                    widget.editingFinished.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                elif field['widgettype'] == 'combo':
                    widget = QComboBox()
                    self.populate_combo(widget, field)
                    widget.currentIndexChanged.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                elif field['widgettype'] == 'checkbox' or field[
                        'widgettype'] == 'check':
                    widget = QCheckBox()
                    if field['value'] in ('true', 'True', 'TRUE', True):
                        widget.setChecked(True)
                    elif field['value'] in ('false', 'False', 'FALSE', False):
                        widget.setChecked(False)
                    widget.stateChanged.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
                elif field['widgettype'] == 'datetime':
                    widget = QDateEdit()
                    widget.setCalendarPopup(True)
                    if field['value']:
                        field['value'] = field['value'].replace('/', '-')
                    date = QDate.fromString(field['value'], 'yyyy-MM-dd')
                    widget.setDate(date)
                    widget.dateChanged.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                elif field['widgettype'] == 'spinbox':
                    widget = QSpinBox()
                    if 'value' in field and field['value'] is not None:
                        value = float(str(field['value']))
                        widget.setValue(value)
                    widget.valueChanged.connect(
                        partial(self.get_values_changed_param_system, widget))
                    widget.setSizePolicy(QSizePolicy.Expanding,
                                         QSizePolicy.Fixed)
                else:
                    pass

                if widget:
                    widget.setObjectName(field['widgetname'])
                else:
                    pass

                # Order Widgets
                if 'layoutname' in field:
                    if field['layoutname'] == 'lyt_topology':
                        self.order_widgets_system(field, self.topology_form,
                                                  lbl, widget)
                    elif field['layoutname'] == 'lyt_builder':
                        self.order_widgets_system(field, self.builder_form,
                                                  lbl, widget)
                    elif field['layoutname'] == 'lyt_review':
                        self.order_widgets_system(field, self.review_form, lbl,
                                                  widget)
                    elif field['layoutname'] == 'lyt_analysis':
                        self.order_widgets_system(field, self.analysis_form,
                                                  lbl, widget)
                    elif field['layoutname'] == 'lyt_system':
                        self.order_widgets_system(field, self.system_form, lbl,
                                                  widget)
Esempio n. 22
0
    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)
Esempio n. 23
0
    def setupUi(self):
        self.setWindowTitle(self.tr('Parameter definition'))
        self.setMinimumWidth(300)

        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setMargin(20)

        self.label = QLabel(self.tr('Parameter name'))
        self.verticalLayout.addWidget(self.label)
        self.nameTextBox = QLineEdit()
        self.verticalLayout.addWidget(self.nameTextBox)

        if isinstance(self.param, QgsProcessingParameterDefinition):
            self.nameTextBox.setText(self.param.description())

        if self.paramType == ModelerParameterDefinitionDialog.PARAMETER_BOOLEAN or \
                isinstance(self.param, QgsProcessingParameterBoolean):
            self.state = QCheckBox()
            self.state.setText(self.tr('Checked'))
            self.state.setChecked(False)
            if self.param is not None:
                self.state.setChecked(bool(self.param.defaultValue()))
            self.verticalLayout.addWidget(self.state)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or \
                isinstance(self.param, QgsProcessingParameterField):
            self.verticalLayout.addWidget(QLabel(self.tr('Parent layer')))
            self.parentCombo = QComboBox()
            idx = 0
            for param in list(self.alg.parameterComponents().values()):
                definition = self.alg.parameterDefinition(param.parameterName())
                if isinstance(definition, (QgsProcessingParameterFeatureSource, QgsProcessingParameterVectorLayer)):
                    self.parentCombo.addItem(definition.description(), definition.name())
                    if self.param is not None:
                        if self.param.parentLayerParameterName() == definition.name():
                            self.parentCombo.setCurrentIndex(idx)
                    idx += 1
            self.verticalLayout.addWidget(self.parentCombo)

            # add the datatype selector
            self.verticalLayout.addWidget(QLabel(self.tr('Allowed data type')))
            self.datatypeCombo = QComboBox()
            self.datatypeCombo.addItem(self.tr('Any'), -1)
            self.datatypeCombo.addItem(self.tr('Number'), 0)
            self.datatypeCombo.addItem(self.tr('String'), 1)
            self.datatypeCombo.addItem(self.tr('Date/time'), 2)
            self.verticalLayout.addWidget(self.datatypeCombo)

            if self.param is not None and self.param.dataType() is not None:
                # QComboBoxes indexes start at 0,
                # self.param.datatype start with -1 that is why I need to do +1
                datatypeIndex = self.param.dataType() + 1
                self.datatypeCombo.setCurrentIndex(datatypeIndex)

            self.multipleCheck = QCheckBox()
            self.multipleCheck.setText(self.tr('Accept multiple fields'))
            self.multipleCheck.setChecked(False)
            if self.param is not None:
                self.multipleCheck.setChecked(self.param.allowMultiple())
            self.verticalLayout.addWidget(self.multipleCheck)

            self.verticalLayout.addWidget(QLabel(self.tr('Default value')))
            self.defaultTextBox = QLineEdit()
            self.defaultTextBox.setToolTip(
                self.tr('Default field name, or ; separated list of field names for multiple field parameters'))
            if self.param is not None:
                default = self.param.defaultValue()
                if default is not None:
                    self.defaultTextBox.setText(str(default))
            self.verticalLayout.addWidget(self.defaultTextBox)

        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_BAND or \
                isinstance(self.param, QgsProcessingParameterBand):
            self.verticalLayout.addWidget(QLabel(self.tr('Parent layer')))
            self.parentCombo = QComboBox()
            idx = 0
            for param in list(self.alg.parameterComponents().values()):
                definition = self.alg.parameterDefinition(param.parameterName())
                if isinstance(definition, (QgsProcessingParameterRasterLayer)):
                    self.parentCombo.addItem(definition.description(), definition.name())
                    if self.param is not None:
                        if self.param.parentLayerParameterName() == definition.name():
                            self.parentCombo.setCurrentIndex(idx)
                    idx += 1
            self.verticalLayout.addWidget(self.parentCombo)
        elif (self.paramType in (
                ModelerParameterDefinitionDialog.PARAMETER_VECTOR, ModelerParameterDefinitionDialog.PARAMETER_TABLE) or
                isinstance(self.param, (QgsProcessingParameterFeatureSource, QgsProcessingParameterVectorLayer))):
            self.verticalLayout.addWidget(QLabel(self.tr('Geometry type')))
            self.shapetypeCombo = QComboBox()
            self.shapetypeCombo.addItem(self.tr('Geometry Not Required'), QgsProcessing.TypeVector)
            self.shapetypeCombo.addItem(self.tr('Point'), QgsProcessing.TypeVectorPoint)
            self.shapetypeCombo.addItem(self.tr('Line'), QgsProcessing.TypeVectorLine)
            self.shapetypeCombo.addItem(self.tr('Polygon'), QgsProcessing.TypeVectorPolygon)
            self.shapetypeCombo.addItem(self.tr('Any Geometry Type'), QgsProcessing.TypeVectorAnyGeometry)
            if self.param is not None:
                self.shapetypeCombo.setCurrentIndex(self.shapetypeCombo.findData(self.param.dataTypes()[0]))
            self.verticalLayout.addWidget(self.shapetypeCombo)
        elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE or
              isinstance(self.param, QgsProcessingParameterMultipleLayers)):
            self.verticalLayout.addWidget(QLabel(self.tr('Data type')))
            self.datatypeCombo = QComboBox()
            self.datatypeCombo.addItem(self.tr('Any Map Layer'), QgsProcessing.TypeMapLayer)
            self.datatypeCombo.addItem(self.tr('Vector (No Geometry Required)'), QgsProcessing.TypeVector)
            self.datatypeCombo.addItem(self.tr('Vector (Point)'), QgsProcessing.TypeVectorPoint)
            self.datatypeCombo.addItem(self.tr('Vector (Line)'), QgsProcessing.TypeVectorLine)
            self.datatypeCombo.addItem(self.tr('Vector (Polygon)'), QgsProcessing.TypeVectorPolygon)
            self.datatypeCombo.addItem(self.tr('Vector (Any Geometry Type)'), QgsProcessing.TypeVectorAnyGeometry)
            self.datatypeCombo.addItem(self.tr('Raster'), QgsProcessing.TypeRaster)
            self.datatypeCombo.addItem(self.tr('File'), QgsProcessing.TypeFile)
            if self.param is not None:
                self.datatypeCombo.setCurrentIndex(self.datatypeCombo.findData(self.param.layerType()))
            self.verticalLayout.addWidget(self.datatypeCombo)
        elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_NUMBER or
              isinstance(self.param, QgsProcessingParameterNumber)):
            self.verticalLayout.addWidget(QLabel(self.tr('Min value')))
            self.minTextBox = QLineEdit()
            self.verticalLayout.addWidget(self.minTextBox)
            self.verticalLayout.addWidget(QLabel(self.tr('Max value')))
            self.maxTextBox = QLineEdit()
            self.verticalLayout.addWidget(self.maxTextBox)
            if self.param is not None:
                self.minTextBox.setText(str(self.param.minimum()))
                self.maxTextBox.setText(str(self.param.maximum()))
            self.verticalLayout.addWidget(QLabel(self.tr('Default value')))
            self.defaultTextBox = QLineEdit()
            self.defaultTextBox.setText(self.tr('0'))
            if self.param is not None:
                default = self.param.defaultValue()
                if self.param.dataType() == QgsProcessingParameterNumber.Integer:
                    default = int(math.floor(default))
                if default:
                    self.defaultTextBox.setText(str(default))
            self.verticalLayout.addWidget(self.defaultTextBox)
        elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_EXPRESSION or
              isinstance(self.param, QgsProcessingParameterExpression)):
            self.verticalLayout.addWidget(QLabel(self.tr('Default value')))
            self.defaultEdit = QgsExpressionLineEdit()
            if self.param is not None:
                self.defaultEdit.setExpression(self.param.defaultValue())
            self.verticalLayout.addWidget(self.defaultEdit)

            self.verticalLayout.addWidget(QLabel(self.tr('Parent layer')))
            self.parentCombo = QComboBox()
            self.parentCombo.addItem(self.tr("None"), None)
            idx = 1
            for param in list(self.alg.parameterComponents().values()):
                definition = self.alg.parameterDefinition(param.parameterName())
                if isinstance(definition, (QgsProcessingParameterFeatureSource, QgsProcessingParameterVectorLayer)):
                    self.parentCombo.addItem(definition.description(), definition.name())
                    if self.param is not None:
                        if self.param.parentLayerParameterName() == definition.name():
                            self.parentCombo.setCurrentIndex(idx)
                    idx += 1
            self.verticalLayout.addWidget(self.parentCombo)
        elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_STRING or
              isinstance(self.param, QgsProcessingParameterString)):
            self.verticalLayout.addWidget(QLabel(self.tr('Default value')))
            self.defaultTextBox = QLineEdit()
            if self.param is not None:
                self.defaultTextBox.setText(self.param.defaultValue())
            self.verticalLayout.addWidget(self.defaultTextBox)
        elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE or
              isinstance(self.param, QgsProcessingParameterFile)):
            self.verticalLayout.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.behavior() == QgsProcessingParameterFile.Folder else 0)
            self.verticalLayout.addWidget(self.fileFolderCombo)
        elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_POINT or
              isinstance(self.param, QgsProcessingParameterPoint)):
            self.verticalLayout.addWidget(QLabel(self.tr('Default value')))
            self.defaultTextBox = QLineEdit()
            if self.param is not None:
                self.defaultTextBox.setText(self.param.defaultValue())
            self.verticalLayout.addWidget(self.defaultTextBox)
        elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_CRS or
              isinstance(self.param, QgsProcessingParameterCrs)):
            self.verticalLayout.addWidget(QLabel(self.tr('Default value')))
            self.selector = QgsProjectionSelectionWidget()
            if self.param is not None:
                self.selector.setCrs(QgsCoordinateReferenceSystem(self.param.defaultValue()))
            else:
                self.selector.setCrs(QgsCoordinateReferenceSystem('EPSG:4326'))
            self.verticalLayout.addWidget(self.selector)

        self.verticalLayout.addSpacing(20)
        self.requiredCheck = QCheckBox()
        self.requiredCheck.setText(self.tr('Mandatory'))
        self.requiredCheck.setChecked(True)
        if self.param is not None:
            self.requiredCheck.setChecked(not self.param.flags() & QgsProcessingParameterDefinition.FlagOptional)
        self.verticalLayout.addWidget(self.requiredCheck)

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel |
                                          QDialogButtonBox.Ok)
        self.buttonBox.setObjectName('buttonBox')
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

        self.verticalLayout.addStretch()
        self.verticalLayout.addWidget(self.buttonBox)

        self.setLayout(self.verticalLayout)
Esempio n. 24
0
def on_resolve_href_(dialog, layer, feature, field):
    """
    @param dialog the dialog where the feature form is opened
    @param layer the layer on which the href link stands
    @param feature the current feature
    @param field the field name storing the href URL
    @param linked_layer_id the QGIS layer id of the already resolved layer, for update
    """
    from .import_gmlas_panel import ImportGmlasPanel
    path = feature[field]
    if not path:
        return

    # if parent is a Dialog, we are in a feature form
    # else in a attribute table
    is_feature_form = isinstance(dialog.parent, QDialog)

    # The href is resolved thanks to the OGR GMLAS driver.
    # We need to determine what is the "root" layer of the imported
    # href, so that we can connect the xlink:href link to the
    # newly loaded set of layers.
    # There seems to be no way to determine what is the "root" layer
    # of a GMLAS database.
    # So, we rely on XML parsing to determine the root element
    # and on layer xpath found in metadata

    # Download the file so that it is used for XML parsing
    # and for GMLAS loading
    from ..core.qgis_urlopener import remote_open_from_qgis
    from ..core.gml_utils import extract_features_from_file
    from ..core.xml_utils import no_ns, no_prefix
    import tempfile

    with remote_open_from_qgis(path) as fi:
        with tempfile.NamedTemporaryFile(delete=False) as fo:
            fo.write(fi.read())
            tmp_file = fo.name

    _, _, nodes = extract_features_from_file(tmp_file)
    if not nodes:
        raise RuntimeError("No feature found in linked document")
    root_tag = nodes[0].tag

    # reuse the GMLAS import panel widget
    dlg = QDialog()
    import_widget = ImportGmlasPanel(dlg, gml_path=tmp_file)
    path_edit = QLineEdit(path, dlg)
    path_edit.setEnabled(False)
    btn = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, dlg)
    layout = QVBoxLayout()
    layout.addWidget(path_edit)
    layout.addWidget(import_widget)
    layout.addItem(QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding))
    layout.addWidget(btn)
    dlg.setLayout(layout)
    btn.accepted.connect(dlg.accept)
    btn.rejected.connect(dlg.reject)
    dlg.resize(400, 300)
    dlg.setWindowTitle("Options for xlink:href loading")
    if not dlg.exec_():
        return

    # close the current form
    w = dialog
    while not isinstance(w, QDialog):
        w = w.parent()
    w.close()

    import_widget.do_load()
    # Add a link between the current layer
    # and the root layer of the newly loaded (complex) features

    # 1. determine the root layer and pkid of all its features
    root_layer = None
    for l in QgsProject.instance().mapLayers().values():
        if no_ns(l.customProperty("xpath", "")) == no_prefix(root_tag):
            root_layer = l
            break
    if root_layer is None:
        raise RuntimeError("Cannot determine the root layer")

    pkid = layer.customProperty("pkid")
    pkid_value = feature[pkid]
    root_layer.startEditing()
    # 2. add a href_origin_pkid field in the root layer
    if "parent_href_pkid" not in [f.name() for f in root_layer.fields()]:
        new_field = QgsField(layer.fields().field(pkid))
        new_field.setName("parent_href_pkid")
        root_layer.addAttribute(new_field)

    # 3. set its value to the id of current feature
    ids_to_change=[]
    for f in root_layer.getFeatures():
        if f["parent_href_pkid"] is None:
            ids_to_change.append(f.id())
    idx = root_layer.fields().indexFromName("parent_href_pkid")
    for fid in ids_to_change:
        # sets the pkid_value
        root_layer.changeAttributeValue(fid, idx, pkid_value)

    root_layer.commitChanges()
    
    # 4. declare a new QgsRelation
    rel_name = "1_n_"+layer.name()+"_"+field
    rel = QgsProject.instance().relationManager().relations().get(rel_name)
    if rel is None:
        rel = QgsRelation()
        rel.setId(rel_name)
        rel.setName(field)
        rel.setReferencedLayer(layer.id())
        rel.setReferencingLayer(root_layer.id())
        rel.addFieldPair("parent_href_pkid", pkid)
        QgsProject.instance().relationManager().addRelation(rel)
    
    # 5. declare the new relation in the form widgets
    # new 1:N in the current layer
    fc = layer.editFormConfig()
    rel_tab = fc.tabs()[1]
    rel_tab.addChildElement(QgsAttributeEditorRelation(rel.name(), rel, rel_tab))
    # new field in the root layer
    fc = root_layer.editFormConfig()
    main_tab = fc.tabs()[0]
    main_tab.addChildElement(QgsAttributeEditorField("parent_href_pkid", idx, main_tab))
    # declare as reference relation widget
    s = QgsEditorWidgetSetup("RelationReference", {'AllowNULL': False,
                                                   'ReadOnly': True,
                                                   'Relation': rel.id(),
                                                   'OrderByValue': False,
                                                   'MapIdentification': False,
                                                   'AllowAddFeatures': False,
                                                   'ShowForm': True})
    root_layer.setEditorWidgetSetup(idx, s)
    
    # write metadata in layers
    href_resolved = layer.customProperty("href_resolved", [])
    if path not in href_resolved:
        layer.setCustomProperty("href_resolved", href_resolved + [path])
    href_linked_layers = layer.customProperty("href_linked_layers", {})
    href_linked_layers[field] = root_layer.id()
    layer.setCustomProperty("href_linked_layers", href_linked_layers)
        
    # 6. reload the current form
    from ..main import get_iface    
    if is_feature_form:
        get_iface().openFeatureForm(layer, feature)
    else:
        get_iface().showAttributeTable(layer)
Esempio n. 25
0
    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()
Esempio n. 26
0
 def createWidget(self):
     return QLineEdit()
Esempio n. 27
0
    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()))
Esempio n. 28
0
    def init_gui(self):
        """
        """
        dlg_layout = QVBoxLayout()
        params_layout = QVBoxLayout()
        params_layout.setAlignment(Qt.AlignTop)

        # Config files groupbox
        self.config_files_groupbox = QgsCollapsibleGroupBox(
            u"Fichier de configuration de l'arbre des ressources")
        config_file_groupbox_layout = QFormLayout(self.config_files_groupbox)

        # URL of the file
        self.config_file_url_label = QLabel(u"URL du fichier", self)
        self.config_file_url_edit = QLineEdit(self)
        self.config_file_url_edit.editingFinished.connect(
            self.config_file_url_changed)
        config_file_groupbox_layout.addRow(self.config_file_url_label,
                                           self.config_file_url_edit)

        # Download the file at startup
        self.download_cb = QCheckBox(
            u"Télécharger le fichier à chaque lancement de QGIS", self)
        self.download_cb.stateChanged.connect(self.download_cb_changed)
        config_file_groupbox_layout.addRow(self.download_cb)

        params_layout.addWidget(self.config_files_groupbox)

        # Download the file now
        self.download_now_label = QLabel(u"Télécharger le fichier maintenant",
                                         self)
        self.download_now_btnbox = QDialogButtonBox()
        self.download_now_btnbox.setOrientation(Qt.Horizontal)
        self.download_now_btnbox.setStandardButtons(QDialogButtonBox.Yes)
        self.download_now_btnbox.button(QDialogButtonBox.Yes).clicked.connect(
            self.download_file_now)
        config_file_groupbox_layout.addRow(self.download_now_label,
                                           self.download_now_btnbox)

        # Content of the resource tree groupbox
        self.resource_tree_groupbox = QgsCollapsibleGroupBox(
            u"Contenu de l'arbre des ressources")
        resource_tree_groupbox_layout = QFormLayout(
            self.resource_tree_groupbox)

        # Hide resources with a warn flag
        self.hide_resources_with_warn_status_cb = QCheckBox(
            u"Masquer les ressources en cours d'intégration", self)
        self.hide_resources_with_warn_status_cb.stateChanged.connect(
            self.hide_resources_with_warn_cb_changed)
        resource_tree_groupbox_layout.addRow(
            self.hide_resources_with_warn_status_cb)

        # Hide empty groups in the resources tree
        self.hide_empty_groups_cb = QCheckBox(
            u"Masquer les groupes de ressources vides", self)
        self.hide_empty_groups_cb.stateChanged.connect(
            self.hide_empty_groups_cb_changed)
        resource_tree_groupbox_layout.addRow(self.hide_empty_groups_cb)

        params_layout.addWidget(self.resource_tree_groupbox)
        dlg_layout.addLayout(params_layout)

        # Set values
        self.set_values_from_qsettings()

        # Bottom dialog buttons
        self.button_box = QDialogButtonBox()
        self.button_box.setOrientation(Qt.Horizontal)
        self.button_box.setStandardButtons(QDialogButtonBox.RestoreDefaults
                                           | QDialogButtonBox.Apply
                                           | QDialogButtonBox.Close)
        self.button_box.button(
            QDialogButtonBox.RestoreDefaults).clicked.connect(
                self.restore_defaults_button_clicked)
        self.button_box.button(QDialogButtonBox.Close).clicked.connect(
            self.close_button_clicked)
        self.button_box.button(QDialogButtonBox.Apply).clicked.connect(
            self.apply_button_clicked)

        # Dialog box title, layout, size and display
        title = u"Paramétrage de l'extension GéoGrandEst…"
        self.setWindowTitle(title)
        dlg_layout.addWidget(self.button_box)
        self.setLayout(dlg_layout)
        self.setMinimumWidth(500)
        self.resize(self.sizeHint())
        self.setSizeGripEnabled(False)
        self.setFixedSize(self.size())
        self.show()
        self.setSizeGripEnabled(False)
Esempio n. 29
0
    def setupUi(self):
        self.setWindowTitle(self.tr('Parameter definition'))
        self.setMinimumWidth(300)

        self.verticalLayout = QVBoxLayout(self)
        self.verticalLayout.setMargin(20)

        self.label = QLabel(self.tr('Parameter name'))
        self.verticalLayout.addWidget(self.label)
        self.nameTextBox = QLineEdit()
        self.verticalLayout.addWidget(self.nameTextBox)

        if isinstance(self.param, QgsProcessingParameterDefinition):
            self.nameTextBox.setText(self.param.description())

        if self.paramType == 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(bool(self.param.value))
            self.verticalLayout.addWidget(self.state)
        elif self.paramType == ModelerParameterDefinitionDialog.PARAMETER_TABLE_FIELD or \
                isinstance(self.param, ParameterTableField):
            self.verticalLayout.addWidget(QLabel(self.tr('Parent layer')))
            self.parentCombo = QComboBox()
            idx = 0
            for param in list(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.verticalLayout.addWidget(self.parentCombo)

            # add the datatype selector
            self.verticalLayout.addWidget(QLabel(self.tr('Allowed data type')))
            self.datatypeCombo = QComboBox()
            self.datatypeCombo.addItem(self.tr('Any'), -1)
            self.datatypeCombo.addItem(self.tr('Number'), 0)
            self.datatypeCombo.addItem(self.tr('String'), 1)
            self.datatypeCombo.addItem(self.tr('Date/time'), 2)
            self.verticalLayout.addWidget(self.datatypeCombo)

            if self.param is not None and self.param.datatype is not None:
                # QComboBoxes indexes start at 0,
                # self.param.datatype start with -1 that is why I need to do +1
                datatypeIndex = self.param.datatype + 1
                self.datatypeCombo.setCurrentIndex(datatypeIndex)

            self.multipleCheck = QCheckBox()
            self.multipleCheck.setText(self.tr('Accept multiple fields'))
            self.multipleCheck.setChecked(False)
            if self.param is not None:
                self.multipleCheck.setChecked(self.param.multiple)
            self.verticalLayout.addWidget(self.multipleCheck)

        elif (self.paramType
              == ModelerParameterDefinitionDialog.PARAMETER_VECTOR
              or isinstance(self.param, ParameterVector)):
            self.verticalLayout.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.datatype[0] + 1)
            self.verticalLayout.addWidget(self.shapetypeCombo)
        elif (self.paramType
              == ModelerParameterDefinitionDialog.PARAMETER_MULTIPLE
              or isinstance(self.param, ParameterMultipleInput)):
            self.verticalLayout.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('File'))
            if self.param is not None:
                self.datatypeCombo.setCurrentIndex(self.param.datatype + 1)
            self.verticalLayout.addWidget(self.datatypeCombo)
        elif (self.paramType
              == ModelerParameterDefinitionDialog.PARAMETER_NUMBER
              or isinstance(self.param, ParameterNumber)):
            self.verticalLayout.addWidget(QLabel(self.tr('Min value')))
            self.minTextBox = QLineEdit()
            self.verticalLayout.addWidget(self.minTextBox)
            self.verticalLayout.addWidget(QLabel(self.tr('Max value')))
            self.maxTextBox = QLineEdit()
            self.verticalLayout.addWidget(self.maxTextBox)
            if self.param is not None:
                self.minTextBox.setText(str(self.param.min))
                self.maxTextBox.setText(str(self.param.max))
            self.verticalLayout.addWidget(QLabel(self.tr('Default value')))
            self.defaultTextBox = QLineEdit()
            self.defaultTextBox.setText(self.tr('0'))
            if self.param is not None:
                default = self.param.default
                if self.param.isInteger:
                    default = int(math.floor(default))
                if default:
                    self.defaultTextBox.setText(str(default))
            self.verticalLayout.addWidget(self.defaultTextBox)
        elif (self.paramType
              == ModelerParameterDefinitionDialog.PARAMETER_EXPRESSION
              or isinstance(self.param, ParameterExpression)):
            self.verticalLayout.addWidget(QLabel(self.tr('Default value')))
            self.defaultEdit = QgsExpressionLineEdit()
            if self.param is not None:
                self.defaultEdit.setExpression(self.param.defaultValue())
            self.verticalLayout.addWidget(self.defaultEdit)

            self.verticalLayout.addWidget(QLabel(self.tr('Parent layer')))
            self.parentCombo = QComboBox()
            self.parentCombo.addItem(self.tr("None"), None)
            idx = 1
            for param in list(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_layer == param.param.name():
                            self.parentCombo.setCurrentIndex(idx)
                    idx += 1
            self.verticalLayout.addWidget(self.parentCombo)
        elif (self.paramType
              == ModelerParameterDefinitionDialog.PARAMETER_STRING
              or isinstance(self.param, ParameterString)):
            self.verticalLayout.addWidget(QLabel(self.tr('Default value')))
            self.defaultTextBox = QLineEdit()
            if self.param is not None:
                self.defaultTextBox.setText(self.param.defaultValue())
            self.verticalLayout.addWidget(self.defaultTextBox)
        elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_FILE
              or isinstance(self.param, ParameterFile)):
            self.verticalLayout.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.verticalLayout.addWidget(self.fileFolderCombo)
        elif (self.paramType
              == ModelerParameterDefinitionDialog.PARAMETER_POINT
              or isinstance(self.param, ParameterPoint)):
            self.verticalLayout.addWidget(QLabel(self.tr('Default value')))
            self.defaultTextBox = QLineEdit()
            if self.param is not None:
                self.defaultTextBox.setText(self.param.defaultValue())
            self.verticalLayout.addWidget(self.defaultTextBox)
        elif (self.paramType == ModelerParameterDefinitionDialog.PARAMETER_CRS
              or isinstance(self.param, ParameterCrs)):
            self.verticalLayout.addWidget(QLabel(self.tr('Default value')))
            self.selector = QgsProjectionSelectionWidget()
            if self.param is not None:
                self.selector.setCrs(
                    QgsCoordinateReferenceSystem(self.param.defaultValue()))
            else:
                self.selector.setCrs(QgsCoordinateReferenceSystem('EPSG:4326'))
            self.verticalLayout.addWidget(self.selector)

        self.verticalLayout.addSpacing(20)
        self.requiredCheck = QCheckBox()
        self.requiredCheck.setText(self.tr('Mandatory'))
        self.requiredCheck.setChecked(True)
        if self.param is not None:
            self.requiredCheck.setChecked(
                not self.param.flags()
                & QgsProcessingParameterDefinition.FlagOptional)
        self.verticalLayout.addWidget(self.requiredCheck)

        self.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.addStretch()
        self.verticalLayout.addWidget(self.buttonBox)

        self.setLayout(self.verticalLayout)
Esempio n. 30
0
    def __init__(self, dockwidget, parent, params, edit_type):

        QDialog.__init__(self, parent)
        main_lay = QVBoxLayout(self)
        self.dockwidget = dockwidget
        self.params = params
        self.edit_type = edit_type

        self.x_label = ''
        self.y_label = ''

        self.setMinimumWidth(600)
        self.setMinimumHeight(400)

        self.setWindowTitle(self.titles[edit_type])  # TODO: softcode
        self.setWindowModality(QtCore.Qt.ApplicationModal)

        self.current = None

        self.current_saved = False

        # File
        self.lbl_file = QLabel('File:')
        self.fra_file = QFrame()
        self.fra_file.setContentsMargins(0, 0, 0, 0)
        fra_file_lay = QHBoxLayout(self.fra_file)

        if edit_type == self.edit_patterns:
            self.txt_file = QLineEdit(self.params.patterns_file)
        elif edit_type == self.edit_curves:
            self.txt_file = QLineEdit(self.params.curves_file)

        self.txt_file.setReadOnly(True)
        self.txt_file.setAlignment(QtCore.Qt.AlignLeft
                                   | QtCore.Qt.AlignVCenter)
        self.txt_file.setSizePolicy(QSizePolicy.MinimumExpanding,
                                    QSizePolicy.Minimum)
        fra_file_lay.addWidget(self.txt_file)
        self.btn_file = QPushButton('Change')  # TODO: softcode
        self.btn_file.clicked.connect(self.import_file)
        fra_file_lay.addWidget(self.btn_file)
        fra_file_lay.setContentsMargins(0, 0, 0, 0)

        self.lbl_list = QLabel(self.labels[edit_type])
        self.lst_list = QListWidget()
        self.lst_list.currentItemChanged.connect(self.list_item_changed)

        # Form
        self.fra_form = QFrame()
        fra_form1_lay = QFormLayout(self.fra_form)
        fra_form1_lay.setContentsMargins(0, 0, 0, 0)
        fra_form1_lay.addRow(self.lbl_list, self.lst_list)

        # Buttons
        self.fra_buttons = QFrame()
        fra_buttons_lay = QHBoxLayout(self.fra_buttons)
        fra_buttons_lay.setContentsMargins(0, 0, 0, 0)

        if self.edit_type == self.edit_patterns:
            ele_name = 'pattern'
        elif self.edit_type == self.edit_curves:
            ele_name = 'curve'

        self.btn_new = QPushButton('New ' + ele_name)  # TODO: softcode
        self.btn_new.clicked.connect(self.new_element)
        fra_buttons_lay.addWidget(self.btn_new)

        self.btn_import = QPushButton('Import ' + ele_name +
                                      's')  # TODO: softcode
        self.btn_import.clicked.connect(self.import_file)
        fra_buttons_lay.addWidget(self.btn_import)

        self.btn_save = QPushButton('Save current ' +
                                    ele_name)  # TODO: softcode
        self.btn_save.clicked.connect(self.save)
        fra_buttons_lay.addWidget(self.btn_save)

        self.btn_del = QPushButton('Delete current ' +
                                   ele_name)  # TODO: softcode
        self.btn_del.clicked.connect(self.del_item)
        fra_buttons_lay.addWidget(self.btn_del)

        # ID
        self.lbl_id = QLabel('ID:')
        self.txt_id = QLineEdit()
        self.txt_id.setSizePolicy(QSizePolicy.Maximum,
                                  QSizePolicy.MinimumExpanding)
        self.lbl_desc = QLabel('Desc.:')
        self.txt_desc = QLineEdit()

        self.fra_id = QFrame()
        fra_id_lay = QHBoxLayout(self.fra_id)
        fra_id_lay.addWidget(self.lbl_id)
        fra_id_lay.addWidget(self.txt_id)
        fra_id_lay.addWidget(self.lbl_desc)
        fra_id_lay.addWidget(self.txt_desc)

        # Table form
        self.table = QTableWidget(self)
        self.rows_nr = 24
        self.cols_nr = 2
        self.table.setRowCount(self.rows_nr)
        self.table.setColumnCount(self.cols_nr)
        self.table.verticalHeader().setVisible(False)

        # Initialize empty table
        self.clear_table()

        self.table.itemChanged.connect(self.data_changed)

        self.fra_table = QFrame()
        fra_table_lay = QVBoxLayout(self.fra_table)
        fra_table_lay.setContentsMargins(0, 0, 0, 0)

        if edit_type == self.edit_curves:
            self.fra_pump_type = QFrame()
            fra_pump_type_lay = QFormLayout(self.fra_pump_type)

            self.lbl_pump_type = QLabel('Curve type:')  # TODO: softcode
            self.cbo_pump_type = QComboBox()

            for key, name in Curve.type_names.items():
                self.cbo_pump_type.addItem(name, key)

            fra_pump_type_lay.addRow(self.lbl_pump_type, self.cbo_pump_type)

            fra_table_lay.addWidget(self.fra_pump_type)

            self.cbo_pump_type.activated.connect(self.cbo_pump_type_activated)

        fra_table_lay.addWidget(self.table)
        self.btn_add_row = QPushButton('Add row')
        self.btn_add_row.clicked.connect(self.add_row)
        fra_table_lay.addWidget(self.btn_add_row)

        # Graph canvas
        self.fra_graph = QFrame()
        self.static_canvas = StaticMplCanvas(self.fra_graph,
                                             width=5,
                                             height=4,
                                             dpi=100)
        fra_graph_lay = QVBoxLayout(self.fra_graph)
        fra_graph_lay.addWidget(self.static_canvas)

        # Top frame
        self.fra_top = QFrame()
        fra_top_lay = QVBoxLayout(self.fra_top)
        fra_top_lay.addWidget(self.fra_form)
        fra_top_lay.addWidget(self.fra_id)
        fra_top_lay.addWidget(self.fra_buttons)

        # Bottom frame
        self.fra_bottom = QFrame()
        fra_bottom_lay = QHBoxLayout(self.fra_bottom)
        fra_bottom_lay.addWidget(self.fra_table)
        fra_bottom_lay.addWidget(self.fra_graph)

        # Main
        main_lay.addWidget(self.fra_top)
        main_lay.addWidget(self.fra_bottom)

        # Get existing patterns/curves
        self.need_to_update_graph = False
        if self.edit_type == self.edit_patterns:
            for pattern_id, pattern in self.params.patterns.items():
                self.lst_list.addItem(pattern.id)

        elif self.edit_type == self.edit_curves:
            for curve_id, curve in self.params.curves.items():
                self.lst_list.addItem(curve.id)

        if self.lst_list.count() > 0:
            self.lst_list.setCurrentRow(0)
            self.txt_id.setEnabled(True)
            self.txt_desc.setEnabled(True)
            self.btn_save.setEnabled(True)
            self.btn_del.setEnabled(True)
            self.table.setEnabled(True)
            self.table.setEditTriggers(QAbstractItemView.AllEditTriggers)
        else:
            self.txt_id.setEnabled(False)
            self.txt_desc.setEnabled(False)
            self.btn_save.setEnabled(False)
            self.btn_del.setEnabled(False)
            self.table.setEnabled(False)
            self.table.setEditTriggers(QAbstractItemView.NoEditTriggers)

        self.new_dialog = None
        self.need_to_update_graph = True