Example #1
0
    def set_up_resource_parameters(self):
        """Set up the resource parameter for the add/edit view.
        """
        name_parameter = StringParameter('UUID-1')
        name_parameter.name = self.resource_parameters['Resource name']
        name_parameter.help_text = tr(
            'Name of the resource that will be provided '
            'as part of minimum needs. '
            'e.g. Rice, Water etc.')
        name_parameter.description = tr(
            'A <b>resource</b> is something that you provide to displaced '
            'persons in the event of a disaster. The resource will be made '
            'available at IDP camps and may need to be stockpiled by '
            'contingency planners in their preparations for a disaster.')
        name_parameter.is_required = True
        name_parameter.value = ''

        description_parameter = StringParameter('UUID-2')
        description_parameter.name = self.resource_parameters[
            'Resource description']
        description_parameter.help_text = tr(
            'Description of the resource that will be provided as part of '
            'minimum needs.')
        description_parameter.description = tr(
            'This gives a detailed description of what the resource is and ')
        description_parameter.is_required = True
        description_parameter.value = ''

        unit_parameter = StringParameter('UUID-3')
        unit_parameter.name = self.resource_parameters['Unit']
        unit_parameter.help_text = tr(
            'Single unit for the resources spelled out. e.g. litre, '
            'kilogram etc.')
        unit_parameter.description = tr(
            'A <b>unit</b> is the basic measurement unit used for computing '
            'the allowance per individual. For example when planning water '
            'rations the unit would be single litre.')
        unit_parameter.is_required = True
        unit_parameter.value = ''

        units_parameter = StringParameter('UUID-4')
        units_parameter.name = self.resource_parameters['Units']
        units_parameter.help_text = tr(
            'Multiple units for the resources spelled out. e.g. litres, '
            'kilogram etc.')
        units_parameter.description = tr(
            '<b>Units</b> are the basic measurement used for computing the '
            'allowance per individual. For example when planning water '
            'rations the units would be litres.')
        units_parameter.is_required = True
        units_parameter.value = ''

        unit_abbreviation_parameter = StringParameter('UUID-5')
        unit_abbreviation_parameter.name = \
            self.resource_parameters['Unit abbreviation']
        unit_abbreviation_parameter.help_text = tr(
            'Abbreviations of unit for the resources. e.g. l, kg etc.')
        unit_abbreviation_parameter.description = tr(
            "A <b>unit abbreviation</b> is the basic measurement unit's "
            "shortened. For example when planning water rations "
            "the units would be l.")
        unit_abbreviation_parameter.is_required = True
        unit_abbreviation_parameter.value = ''

        minimum_parameter = FloatParameter('UUID-6')
        minimum_parameter.name = self.resource_parameters['Minimum allowed']
        minimum_parameter.is_required = True
        minimum_parameter.precision = 6
        minimum_parameter.minimum_allowed_value = 0.0
        minimum_parameter.maximum_allowed_value = 99999.0
        minimum_parameter.help_text = tr(
            'The minimum allowable quantity per person. ')
        minimum_parameter.description = tr(
            'The <b>minimum</b> is the minimum allowed quantity of the '
            'resource per person. For example you may dictate that the water '
            'ration per person per day should never be allowed to be less '
            'than 0.5l. This is enforced when tweaking a minimum needs set '
            'before an impact evaluation')
        minimum_parameter.value = 0.00

        maximum_parameter = FloatParameter('UUID-7')
        maximum_parameter.name = self.resource_parameters['Maximum allowed']
        maximum_parameter.is_required = True
        maximum_parameter.precision = 6
        maximum_parameter.minimum_allowed_value = 0.0
        maximum_parameter.maximum_allowed_value = 99999.0
        maximum_parameter.help_text = tr(
            'The maximum allowable quantity per person. ')
        maximum_parameter.description = tr(
            'The <b>maximum</b> is the maximum allowed quantity of the '
            'resource per person. For example you may dictate that the water '
            'ration per person per day should never be allowed to be more '
            'than 67l. This is enforced when tweaking a maximum needs set '
            'before an impact evaluation.')
        maximum_parameter.value = 100.0

        default_parameter = FloatParameter('UUID-8')
        default_parameter.name = self.resource_parameters['Default']
        default_parameter.is_required = True
        default_parameter.precision = 6
        default_parameter.minimum_allowed_value = 0.0
        default_parameter.maximum_allowed_value = 99999.0
        default_parameter.help_text = tr(
            'The default allowable quantity per person. ')
        default_parameter.description = tr(
            "The <b>default</b> is the default allowed quantity of the "
            "resource per person. For example you may indicate that the water "
            "ration per person weekly should be 67l.")
        default_parameter.value = 10.0

        frequency_parameter = StringParameter('UUID-9')
        frequency_parameter.name = self.resource_parameters['Frequency']
        frequency_parameter.help_text = tr(
            "The frequency that this resource needs to be provided to a "
            "displaced person. e.g. weekly, daily, once etc.")
        frequency_parameter.description = tr(
            "The <b>frequency</b> informs the aid worker how regularly this "
            "resource needs to be provided to the displaced person.")
        frequency_parameter.is_required = True
        frequency_parameter.value = tr('weekly')

        sentence_parameter = TextParameter('UUID-10')
        sentence_parameter.name = self.resource_parameters['Readable sentence']
        sentence_parameter.help_text = tr(
            'A readable presentation of the resource.')
        sentence_parameter.description = tr(
            "A <b>readable sentence</b> is a presentation of the resource "
            "that displays all pertinent information. If you are unsure then "
            "use the default. Properties should be included using double "
            "curly brackets '{{' '}}'. Including the resource name would be "
            "achieved by including e.g. {{ Resource name }}")
        sentence_parameter.is_required = True
        sentence_parameter.value = tr(
            'A displaced person should be provided with '
            '%(default value)s %(unit)s/%(units)s/%(unit abbreviation)s of '
            '%(resource name)s. Though no less than %(minimum allowed)s '
            'and no more than %(maximum allowed)s. This should be provided '
            '%(frequency)s.' % {
                'default value': '{{ Default }}',
                'unit': '{{ Unit }}',
                'units': '{{ Units }}',
                'unit abbreviation': '{{ Unit abbreviation }}',
                'resource name': '{{ Resource name }}',
                'minimum allowed': '{{ Minimum allowed }}',
                'maximum allowed': '{{ Maximum allowed }}',
                'frequency': '{{ Frequency }}'
            })

        parameters = [
            name_parameter, description_parameter, unit_parameter,
            units_parameter, unit_abbreviation_parameter, default_parameter,
            minimum_parameter, maximum_parameter, frequency_parameter,
            sentence_parameter
        ]
        parameter_container = ParameterContainer(parameters)
        parameter_container.setup_ui()

        layout = QGridLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.setSpacing(0)
        layout.addWidget(parameter_container)
        self.parameters_scrollarea.setLayout(layout)
Example #2
0
    def setupUi(self):
        self.setWindowTitle(self.tr("DB Manager"))
        self.setWindowIcon(QIcon(":/db_manager/icon"))
        self.resize(QSize(700, 500).expandedTo(self.minimumSizeHint()))

        # create central tab widget and add the first 3 tabs: info, table and preview
        self.tabs = QTabWidget()
        self.info = InfoViewer(self)
        self.tabs.addTab(self.info, self.tr("Info"))
        self.table = TableViewer(self)
        self.tabs.addTab(self.table, self.tr("Table"))
        self.preview = LayerPreview(self)
        self.tabs.addTab(self.preview, self.tr("Preview"))
        self.setCentralWidget(self.tabs)

        # display close button for all tabs but the first 3 ones, i.e.
        # HACK: just hide the close button where not needed (GS)
        self.tabs.setTabsClosable(True)
        self.tabs.tabCloseRequested.connect(self.close_tab)
        tabbar = self.tabs.tabBar()
        for i in range(3):
            btn = tabbar.tabButton(i, QTabBar.RightSide) if tabbar.tabButton(
                i, QTabBar.RightSide) else tabbar.tabButton(
                    i, QTabBar.LeftSide)
            btn.resize(0, 0)
            btn.hide()

        # Creates layout for message bar
        self.layout = QGridLayout(self.info)
        self.layout.setContentsMargins(0, 0, 0, 0)
        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.layout.addItem(spacerItem, 1, 0, 1, 1)
        # init messageBar instance
        self.infoBar = QgsMessageBar(self.info)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.infoBar.setSizePolicy(sizePolicy)
        self.layout.addWidget(self.infoBar, 0, 0, 1, 1)

        # create database tree
        self.dock = QDockWidget("Tree", self)
        self.dock.setObjectName("DB_Manager_DBView")
        self.dock.setFeatures(QDockWidget.DockWidgetMovable)
        self.tree = DBTree(self)
        self.dock.setWidget(self.tree)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dock)

        # create status bar
        self.statusBar = QStatusBar(self)
        self.setStatusBar(self.statusBar)

        # create menus
        self.menuBar = QMenuBar(self)
        self.menuDb = QMenu(self.tr("&Database"), self)
        self.menuBar.addMenu(self.menuDb)
        self.menuSchema = QMenu(self.tr("&Schema"), self)
        actionMenuSchema = self.menuBar.addMenu(self.menuSchema)
        self.menuTable = QMenu(self.tr("&Table"), self)
        actionMenuTable = self.menuBar.addMenu(self.menuTable)
        self.menuHelp = None  # QMenu(self.tr("&Help"), self)
        # actionMenuHelp = self.menuBar.addMenu(self.menuHelp)

        self.setMenuBar(self.menuBar)

        # create toolbar
        self.toolBar = QToolBar("Default", self)
        self.toolBar.setObjectName("DB_Manager_ToolBar")
        self.addToolBar(self.toolBar)

        # create menus' actions

        # menu DATABASE
        sep = self.menuDb.addSeparator()
        sep.setObjectName("DB_Manager_DbMenu_placeholder")
        sep.setVisible(False)

        self.actionRefresh = self.menuDb.addAction(
            QIcon(":/db_manager/actions/refresh"), self.tr("&Refresh"),
            self.refreshActionSlot, QKeySequence("F5"))
        self.actionSqlWindow = self.menuDb.addAction(
            QIcon(":/db_manager/actions/sql_window"), self.tr("&SQL window"),
            self.runSqlWindow, QKeySequence("F2"))
        self.menuDb.addSeparator()
        self.actionClose = self.menuDb.addAction(QIcon(), self.tr("&Exit"),
                                                 self.close,
                                                 QKeySequence("CTRL+Q"))

        # menu SCHEMA
        sep = self.menuSchema.addSeparator()
        sep.setObjectName("DB_Manager_SchemaMenu_placeholder")
        sep.setVisible(False)

        actionMenuSchema.setVisible(False)

        # menu TABLE
        sep = self.menuTable.addSeparator()
        sep.setObjectName("DB_Manager_TableMenu_placeholder")
        sep.setVisible(False)

        self.actionImport = self.menuTable.addAction(
            QIcon(":/db_manager/actions/import"),
            self.tr("&Import layer/file"), self.importActionSlot)
        self.actionExport = self.menuTable.addAction(
            QIcon(":/db_manager/actions/export"), self.tr("&Export to file"),
            self.exportActionSlot)
        self.menuTable.addSeparator()
        #self.actionShowSystemTables = self.menuTable.addAction(self.tr("Show system tables/views"), self.showSystemTables)
        #self.actionShowSystemTables.setCheckable(True)
        #self.actionShowSystemTables.setChecked(True)
        actionMenuTable.setVisible(False)

        # add actions to the toolbar
        self.toolBar.addAction(self.actionRefresh)
        self.toolBar.addAction(self.actionSqlWindow)
        self.toolBar.addAction(self.actionImport)
        self.toolBar.addAction(self.actionExport)
Example #3
0
    def __init__(self, model=None):
        super().__init__(None)
        self.setAttribute(Qt.WA_DeleteOnClose)

        self.setupUi(self)

        self._variables_scope = None

        # LOTS of bug reports when we include the dock creation in the UI file
        # see e.g. #16428, #19068
        # So just roll it all by hand......!
        self.propertiesDock = QgsDockWidget(self)
        self.propertiesDock.setFeatures(QDockWidget.DockWidgetFloatable
                                        | QDockWidget.DockWidgetMovable)
        self.propertiesDock.setObjectName("propertiesDock")
        propertiesDockContents = QWidget()
        self.verticalDockLayout_1 = QVBoxLayout(propertiesDockContents)
        self.verticalDockLayout_1.setContentsMargins(0, 0, 0, 0)
        self.verticalDockLayout_1.setSpacing(0)
        self.scrollArea_1 = QgsScrollArea(propertiesDockContents)
        sizePolicy = QSizePolicy(QSizePolicy.MinimumExpanding,
                                 QSizePolicy.MinimumExpanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.scrollArea_1.sizePolicy().hasHeightForWidth())
        self.scrollArea_1.setSizePolicy(sizePolicy)
        self.scrollArea_1.setFocusPolicy(Qt.WheelFocus)
        self.scrollArea_1.setFrameShape(QFrame.NoFrame)
        self.scrollArea_1.setFrameShadow(QFrame.Plain)
        self.scrollArea_1.setWidgetResizable(True)
        self.scrollAreaWidgetContents_1 = QWidget()
        self.gridLayout = QGridLayout(self.scrollAreaWidgetContents_1)
        self.gridLayout.setContentsMargins(6, 6, 6, 6)
        self.gridLayout.setSpacing(4)
        self.label_1 = QLabel(self.scrollAreaWidgetContents_1)
        self.gridLayout.addWidget(self.label_1, 0, 0, 1, 1)
        self.textName = QLineEdit(self.scrollAreaWidgetContents_1)
        self.gridLayout.addWidget(self.textName, 0, 1, 1, 1)
        self.label_2 = QLabel(self.scrollAreaWidgetContents_1)
        self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1)
        self.textGroup = QLineEdit(self.scrollAreaWidgetContents_1)
        self.gridLayout.addWidget(self.textGroup, 1, 1, 1, 1)
        self.label_1.setText(self.tr("Name"))
        self.textName.setToolTip(self.tr("Enter model name here"))
        self.label_2.setText(self.tr("Group"))
        self.textGroup.setToolTip(self.tr("Enter group name here"))
        self.scrollArea_1.setWidget(self.scrollAreaWidgetContents_1)
        self.verticalDockLayout_1.addWidget(self.scrollArea_1)
        self.propertiesDock.setWidget(propertiesDockContents)
        self.propertiesDock.setWindowTitle(self.tr("Model Properties"))

        self.inputsDock = QgsDockWidget(self)
        self.inputsDock.setFeatures(QDockWidget.DockWidgetFloatable
                                    | QDockWidget.DockWidgetMovable)
        self.inputsDock.setObjectName("inputsDock")
        self.inputsDockContents = QWidget()
        self.verticalLayout_3 = QVBoxLayout(self.inputsDockContents)
        self.verticalLayout_3.setContentsMargins(0, 0, 0, 0)
        self.scrollArea_2 = QgsScrollArea(self.inputsDockContents)
        sizePolicy.setHeightForWidth(
            self.scrollArea_2.sizePolicy().hasHeightForWidth())
        self.scrollArea_2.setSizePolicy(sizePolicy)
        self.scrollArea_2.setFocusPolicy(Qt.WheelFocus)
        self.scrollArea_2.setFrameShape(QFrame.NoFrame)
        self.scrollArea_2.setFrameShadow(QFrame.Plain)
        self.scrollArea_2.setWidgetResizable(True)
        self.scrollAreaWidgetContents_2 = QWidget()
        self.verticalLayout = QVBoxLayout(self.scrollAreaWidgetContents_2)
        self.verticalLayout.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout.setSpacing(0)
        self.inputsTree = QTreeWidget(self.scrollAreaWidgetContents_2)
        self.inputsTree.setAlternatingRowColors(True)
        self.inputsTree.header().setVisible(False)
        self.verticalLayout.addWidget(self.inputsTree)
        self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2)
        self.verticalLayout_3.addWidget(self.scrollArea_2)
        self.inputsDock.setWidget(self.inputsDockContents)
        self.addDockWidget(Qt.DockWidgetArea(1), self.inputsDock)
        self.inputsDock.setWindowTitle(self.tr("Inputs"))

        self.algorithmsDock = QgsDockWidget(self)
        self.algorithmsDock.setFeatures(QDockWidget.DockWidgetFloatable
                                        | QDockWidget.DockWidgetMovable)
        self.algorithmsDock.setObjectName("algorithmsDock")
        self.algorithmsDockContents = QWidget()
        self.verticalLayout_4 = QVBoxLayout(self.algorithmsDockContents)
        self.verticalLayout_4.setContentsMargins(0, 0, 0, 0)
        self.scrollArea_3 = QgsScrollArea(self.algorithmsDockContents)
        sizePolicy.setHeightForWidth(
            self.scrollArea_3.sizePolicy().hasHeightForWidth())
        self.scrollArea_3.setSizePolicy(sizePolicy)
        self.scrollArea_3.setFocusPolicy(Qt.WheelFocus)
        self.scrollArea_3.setFrameShape(QFrame.NoFrame)
        self.scrollArea_3.setFrameShadow(QFrame.Plain)
        self.scrollArea_3.setWidgetResizable(True)
        self.scrollAreaWidgetContents_3 = QWidget()
        self.verticalLayout_2 = QVBoxLayout(self.scrollAreaWidgetContents_3)
        self.verticalLayout_2.setContentsMargins(0, 0, 0, 0)
        self.verticalLayout_2.setSpacing(4)
        self.searchBox = QgsFilterLineEdit(self.scrollAreaWidgetContents_3)
        self.verticalLayout_2.addWidget(self.searchBox)
        self.algorithmTree = QgsProcessingToolboxTreeView(
            None, QgsApplication.processingRegistry())
        self.algorithmTree.setAlternatingRowColors(True)
        self.algorithmTree.header().setVisible(False)
        self.verticalLayout_2.addWidget(self.algorithmTree)
        self.scrollArea_3.setWidget(self.scrollAreaWidgetContents_3)
        self.verticalLayout_4.addWidget(self.scrollArea_3)
        self.algorithmsDock.setWidget(self.algorithmsDockContents)
        self.addDockWidget(Qt.DockWidgetArea(1), self.algorithmsDock)
        self.algorithmsDock.setWindowTitle(self.tr("Algorithms"))
        self.searchBox.setToolTip(
            self.tr("Enter algorithm name to filter list"))
        self.searchBox.setShowSearchIcon(True)

        self.variables_dock = QgsDockWidget(self)
        self.variables_dock.setFeatures(QDockWidget.DockWidgetFloatable
                                        | QDockWidget.DockWidgetMovable)
        self.variables_dock.setObjectName("variablesDock")
        self.variables_dock_contents = QWidget()
        vl_v = QVBoxLayout()
        vl_v.setContentsMargins(0, 0, 0, 0)
        self.variables_editor = QgsVariableEditorWidget()
        vl_v.addWidget(self.variables_editor)
        self.variables_dock_contents.setLayout(vl_v)
        self.variables_dock.setWidget(self.variables_dock_contents)
        self.addDockWidget(Qt.DockWidgetArea(1), self.variables_dock)
        self.variables_dock.setWindowTitle(self.tr("Variables"))
        self.addDockWidget(Qt.DockWidgetArea(1), self.propertiesDock)
        self.tabifyDockWidget(self.propertiesDock, self.variables_dock)
        self.variables_editor.scopeChanged.connect(self.variables_changed)

        self.bar = QgsMessageBar()
        self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.centralWidget().layout().insertWidget(0, self.bar)

        try:
            self.setDockOptions(self.dockOptions()
                                | QMainWindow.GroupedDragging)
        except:
            pass

        if iface is not None:
            self.mToolbar.setIconSize(iface.iconSize())
            self.setStyleSheet(iface.mainWindow().styleSheet())

        self.toolbutton_export_to_script = QToolButton()
        self.toolbutton_export_to_script.setPopupMode(QToolButton.InstantPopup)
        self.export_to_script_algorithm_action = QAction(
            QCoreApplication.translate('ModelerDialog',
                                       'Export as Script Algorithm…'))
        self.toolbutton_export_to_script.addActions(
            [self.export_to_script_algorithm_action])
        self.mToolbar.insertWidget(self.mActionExportImage,
                                   self.toolbutton_export_to_script)
        self.export_to_script_algorithm_action.triggered.connect(
            self.export_as_script_algorithm)

        self.mActionOpen.setIcon(
            QgsApplication.getThemeIcon('/mActionFileOpen.svg'))
        self.mActionSave.setIcon(
            QgsApplication.getThemeIcon('/mActionFileSave.svg'))
        self.mActionSaveAs.setIcon(
            QgsApplication.getThemeIcon('/mActionFileSaveAs.svg'))
        self.mActionSaveInProject.setIcon(
            QgsApplication.getThemeIcon('/mAddToProject.svg'))
        self.mActionZoomActual.setIcon(
            QgsApplication.getThemeIcon('/mActionZoomActual.svg'))
        self.mActionZoomIn.setIcon(
            QgsApplication.getThemeIcon('/mActionZoomIn.svg'))
        self.mActionZoomOut.setIcon(
            QgsApplication.getThemeIcon('/mActionZoomOut.svg'))
        self.mActionExportImage.setIcon(
            QgsApplication.getThemeIcon('/mActionSaveMapAsImage.svg'))
        self.mActionZoomToItems.setIcon(
            QgsApplication.getThemeIcon('/mActionZoomFullExtent.svg'))
        self.mActionExportPdf.setIcon(
            QgsApplication.getThemeIcon('/mActionSaveAsPDF.svg'))
        self.mActionExportSvg.setIcon(
            QgsApplication.getThemeIcon('/mActionSaveAsSVG.svg'))
        self.toolbutton_export_to_script.setIcon(
            QgsApplication.getThemeIcon('/mActionSaveAsPython.svg'))
        self.mActionEditHelp.setIcon(
            QgsApplication.getThemeIcon('/mActionEditHelpContent.svg'))
        self.mActionRun.setIcon(
            QgsApplication.getThemeIcon('/mActionStart.svg'))

        self.addDockWidget(Qt.LeftDockWidgetArea, self.propertiesDock)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.inputsDock)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.algorithmsDock)
        self.tabifyDockWidget(self.inputsDock, self.algorithmsDock)
        self.inputsDock.raise_()

        self.setWindowFlags(Qt.WindowMinimizeButtonHint
                            | Qt.WindowMaximizeButtonHint
                            | Qt.WindowCloseButtonHint)

        settings = QgsSettings()
        self.restoreState(
            settings.value("/Processing/stateModeler", QByteArray()))
        self.restoreGeometry(
            settings.value("/Processing/geometryModeler", QByteArray()))

        self.scene = ModelerScene(self, dialog=self)
        self.scene.setSceneRect(
            QRectF(0, 0, self.CANVAS_SIZE, self.CANVAS_SIZE))

        self.view.setScene(self.scene)
        self.view.setAcceptDrops(True)
        self.view.ensureVisible(0, 0, 10, 10)
        self.view.scale(QgsApplication.desktop().logicalDpiX() / 96,
                        QgsApplication.desktop().logicalDpiX() / 96)

        def _dragEnterEvent(event):
            if event.mimeData().hasText() or event.mimeData().hasFormat(
                    'application/x-vnd.qgis.qgis.algorithmid'):
                event.acceptProposedAction()
            else:
                event.ignore()

        def _dropEvent(event):
            def alg_dropped(algorithm_id, pos):
                alg = QgsApplication.processingRegistry().createAlgorithmById(
                    algorithm_id)
                if alg is not None:
                    self._addAlgorithm(alg, pos)
                else:
                    assert False, algorithm_id

            def input_dropped(id, pos):
                if id in [
                        param.id() for param in QgsApplication.instance().
                        processingRegistry().parameterTypes()
                ]:
                    self.addInputOfType(itemId, pos)

            if event.mimeData().hasFormat(
                    'application/x-vnd.qgis.qgis.algorithmid'):
                data = event.mimeData().data(
                    'application/x-vnd.qgis.qgis.algorithmid')
                stream = QDataStream(data, QIODevice.ReadOnly)
                algorithm_id = stream.readQString()
                QTimer.singleShot(
                    0,
                    lambda id=algorithm_id, pos=self.view.mapToScene(event.pos(
                    )): alg_dropped(id, pos))
                event.accept()
            elif event.mimeData().hasText():
                itemId = event.mimeData().text()
                QTimer.singleShot(0,
                                  lambda id=itemId, pos=self.view.mapToScene(
                                      event.pos()): input_dropped(id, pos))
                event.accept()
            else:
                event.ignore()

        def _dragMoveEvent(event):
            if event.mimeData().hasText() or event.mimeData().hasFormat(
                    'application/x-vnd.qgis.qgis.algorithmid'):
                event.accept()
            else:
                event.ignore()

        def _wheelEvent(event):
            self.view.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)

            settings = QgsSettings()
            factor = settings.value('/qgis/zoom_favor', 2.0)

            # "Normal" mouse has an angle delta of 120, precision mouses provide data
            # faster, in smaller steps
            factor = 1.0 + (factor - 1.0) / 120.0 * abs(event.angleDelta().y())

            if (event.modifiers() == Qt.ControlModifier):
                factor = 1.0 + (factor - 1.0) / 20.0

            if event.angleDelta().y() < 0:
                factor = 1 / factor

            self.view.scale(factor, factor)

        def _enterEvent(e):
            QGraphicsView.enterEvent(self.view, e)
            self.view.viewport().setCursor(Qt.ArrowCursor)

        def _mouseReleaseEvent(e):
            QGraphicsView.mouseReleaseEvent(self.view, e)
            self.view.viewport().setCursor(Qt.ArrowCursor)

        def _mousePressEvent(e):
            if e.button() == Qt.MidButton:
                self.previousMousePos = e.pos()
            else:
                QGraphicsView.mousePressEvent(self.view, e)

        def _mouseMoveEvent(e):
            if e.buttons() == Qt.MidButton:
                offset = self.previousMousePos - e.pos()
                self.previousMousePos = e.pos()

                self.view.verticalScrollBar().setValue(
                    self.view.verticalScrollBar().value() + offset.y())
                self.view.horizontalScrollBar().setValue(
                    self.view.horizontalScrollBar().value() + offset.x())
            else:
                QGraphicsView.mouseMoveEvent(self.view, e)

        self.view.setDragMode(QGraphicsView.ScrollHandDrag)
        self.view.dragEnterEvent = _dragEnterEvent
        self.view.dropEvent = _dropEvent
        self.view.dragMoveEvent = _dragMoveEvent
        self.view.wheelEvent = _wheelEvent
        self.view.enterEvent = _enterEvent
        self.view.mousePressEvent = _mousePressEvent
        self.view.mouseMoveEvent = _mouseMoveEvent

        def _mimeDataInput(items):
            mimeData = QMimeData()
            text = items[0].data(0, Qt.UserRole)
            mimeData.setText(text)
            return mimeData

        self.inputsTree.mimeData = _mimeDataInput

        self.inputsTree.setDragDropMode(QTreeWidget.DragOnly)
        self.inputsTree.setDropIndicatorShown(True)

        self.algorithms_model = ModelerToolboxModel(
            self, QgsApplication.processingRegistry())
        self.algorithmTree.setToolboxProxyModel(self.algorithms_model)
        self.algorithmTree.setDragDropMode(QTreeWidget.DragOnly)
        self.algorithmTree.setDropIndicatorShown(True)

        filters = QgsProcessingToolboxProxyModel.Filters(
            QgsProcessingToolboxProxyModel.FilterModeler)
        if ProcessingConfig.getSetting(
                ProcessingConfig.SHOW_ALGORITHMS_KNOWN_ISSUES):
            filters |= QgsProcessingToolboxProxyModel.FilterShowKnownIssues
        self.algorithmTree.setFilters(filters)

        if hasattr(self.searchBox, 'setPlaceholderText'):
            self.searchBox.setPlaceholderText(
                QCoreApplication.translate('ModelerDialog', 'Search…'))
        if hasattr(self.textName, 'setPlaceholderText'):
            self.textName.setPlaceholderText(self.tr('Enter model name here'))
        if hasattr(self.textGroup, 'setPlaceholderText'):
            self.textGroup.setPlaceholderText(self.tr('Enter group name here'))

        # Connect signals and slots
        self.inputsTree.doubleClicked.connect(self.addInput)
        self.searchBox.textChanged.connect(self.algorithmTree.setFilterString)
        self.algorithmTree.doubleClicked.connect(self.addAlgorithm)

        # Ctrl+= should also trigger a zoom in action
        ctrlEquals = QShortcut(QKeySequence("Ctrl+="), self)
        ctrlEquals.activated.connect(self.zoomIn)

        self.mActionOpen.triggered.connect(self.openModel)
        self.mActionSave.triggered.connect(self.save)
        self.mActionSaveAs.triggered.connect(self.saveAs)
        self.mActionSaveInProject.triggered.connect(self.saveInProject)
        self.mActionZoomIn.triggered.connect(self.zoomIn)
        self.mActionZoomOut.triggered.connect(self.zoomOut)
        self.mActionZoomActual.triggered.connect(self.zoomActual)
        self.mActionZoomToItems.triggered.connect(self.zoomToItems)
        self.mActionExportImage.triggered.connect(self.exportAsImage)
        self.mActionExportPdf.triggered.connect(self.exportAsPdf)
        self.mActionExportSvg.triggered.connect(self.exportAsSvg)
        #self.mActionExportPython.triggered.connect(self.exportAsPython)
        self.mActionEditHelp.triggered.connect(self.editHelp)
        self.mActionRun.triggered.connect(self.runModel)

        if model is not None:
            self.model = model.create()
            self.model.setSourceFilePath(model.sourceFilePath())
            self.textGroup.setText(self.model.group())
            self.textName.setText(self.model.displayName())
            self.repaintModel()

        else:
            self.model = QgsProcessingModelAlgorithm()
            self.model.setProvider(
                QgsApplication.processingRegistry().providerById('model'))
        self.update_variables_gui()

        self.fillInputsTree()

        self.view.centerOn(0, 0)
        self.help = None

        self.hasChanged = False
Example #4
0
    def __init__(self, parent=None):
        QWidget.__init__(self, parent)
        self.setWindowTitle(
            QCoreApplication.translate("PythonConsole", "Python Console"))

        self.settings = QSettings()

        self.shell = ShellScintilla(self)
        self.setFocusProxy(self.shell)
        self.shellOut = ShellOutputScintilla(self)
        self.tabEditorWidget = EditorTabWidget(self)

        ##------------ UI -------------------------------

        self.splitterEditor = QSplitter(self)
        self.splitterEditor.setOrientation(Qt.Horizontal)
        self.splitterEditor.setHandleWidth(6)
        self.splitterEditor.setChildrenCollapsible(True)

        self.shellOutWidget = QWidget(self)
        self.shellOutWidget.setLayout(QVBoxLayout())
        self.shellOutWidget.layout().setContentsMargins(0, 0, 0, 0)
        self.shellOutWidget.layout().addWidget(self.shellOut)

        self.splitter = QSplitter(self.splitterEditor)
        self.splitter.setOrientation(Qt.Vertical)
        self.splitter.setHandleWidth(3)
        self.splitter.setChildrenCollapsible(False)
        self.splitter.addWidget(self.shellOutWidget)
        self.splitter.addWidget(self.shell)

        #self.splitterEditor.addWidget(self.tabEditorWidget)

        self.splitterObj = QSplitter(self.splitterEditor)
        self.splitterObj.setHandleWidth(3)
        self.splitterObj.setOrientation(Qt.Horizontal)
        #self.splitterObj.setSizes([0, 0])
        #self.splitterObj.setStretchFactor(0, 1)

        self.widgetEditor = QWidget(self.splitterObj)
        self.widgetFind = QWidget(self)

        self.listClassMethod = QTreeWidget(self.splitterObj)
        self.listClassMethod.setColumnCount(2)
        objInspLabel = QCoreApplication.translate("PythonConsole",
                                                  "Object Inspector")
        self.listClassMethod.setHeaderLabels([objInspLabel, ''])
        self.listClassMethod.setColumnHidden(1, True)
        self.listClassMethod.setAlternatingRowColors(True)

        #self.splitterEditor.addWidget(self.widgetEditor)
        #self.splitterObj.addWidget(self.listClassMethod)
        #self.splitterObj.addWidget(self.widgetEditor)

        # Hide side editor on start up
        self.splitterObj.hide()
        self.listClassMethod.hide()
        # Hide search widget on start up
        self.widgetFind.hide()

        sizes = self.splitter.sizes()
        self.splitter.setSizes(sizes)

        ##----------------Restore Settings------------------------------------

        self.restoreSettingsConsole()

        ##------------------Toolbar Editor-------------------------------------

        ## Action for Open File
        openFileBt = QCoreApplication.translate("PythonConsole",
                                                "Open Script...")
        self.openFileButton = QAction(self)
        self.openFileButton.setCheckable(False)
        self.openFileButton.setEnabled(True)
        self.openFileButton.setIcon(
            QgsApplication.getThemeIcon("console/iconOpenConsole.png"))
        self.openFileButton.setMenuRole(QAction.PreferencesRole)
        self.openFileButton.setIconVisibleInMenu(True)
        self.openFileButton.setToolTip(openFileBt)
        self.openFileButton.setText(openFileBt)

        openExtEditorBt = QCoreApplication.translate(
            "PythonConsole", "Open in External Editor")
        self.openInEditorButton = QAction(self)
        self.openInEditorButton.setCheckable(False)
        self.openInEditorButton.setEnabled(True)
        self.openInEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconShowEditorConsole.png"))
        self.openInEditorButton.setMenuRole(QAction.PreferencesRole)
        self.openInEditorButton.setIconVisibleInMenu(True)
        self.openInEditorButton.setToolTip(openExtEditorBt)
        self.openInEditorButton.setText(openExtEditorBt)
        ## Action for Save File
        saveFileBt = QCoreApplication.translate("PythonConsole", "Save")
        self.saveFileButton = QAction(self)
        self.saveFileButton.setCheckable(False)
        self.saveFileButton.setEnabled(False)
        self.saveFileButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSaveConsole.png"))
        self.saveFileButton.setMenuRole(QAction.PreferencesRole)
        self.saveFileButton.setIconVisibleInMenu(True)
        self.saveFileButton.setToolTip(saveFileBt)
        self.saveFileButton.setText(saveFileBt)
        ## Action for Save File As
        saveAsFileBt = QCoreApplication.translate("PythonConsole",
                                                  "Save As...")
        self.saveAsFileButton = QAction(self)
        self.saveAsFileButton.setCheckable(False)
        self.saveAsFileButton.setEnabled(True)
        self.saveAsFileButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSaveAsConsole.png"))
        self.saveAsFileButton.setMenuRole(QAction.PreferencesRole)
        self.saveAsFileButton.setIconVisibleInMenu(True)
        self.saveAsFileButton.setToolTip(saveAsFileBt)
        self.saveAsFileButton.setText(saveAsFileBt)
        ## Action Cut
        cutEditorBt = QCoreApplication.translate("PythonConsole", "Cut")
        self.cutEditorButton = QAction(self)
        self.cutEditorButton.setCheckable(False)
        self.cutEditorButton.setEnabled(True)
        self.cutEditorButton.setIcon(
            QgsApplication.getThemeIcon("mActionEditCut.svg"))
        self.cutEditorButton.setMenuRole(QAction.PreferencesRole)
        self.cutEditorButton.setIconVisibleInMenu(True)
        self.cutEditorButton.setToolTip(cutEditorBt)
        self.cutEditorButton.setText(cutEditorBt)
        ## Action Copy
        copyEditorBt = QCoreApplication.translate("PythonConsole", "Copy")
        self.copyEditorButton = QAction(self)
        self.copyEditorButton.setCheckable(False)
        self.copyEditorButton.setEnabled(True)
        self.copyEditorButton.setIcon(
            QgsApplication.getThemeIcon("mActionEditCopy.svg"))
        self.copyEditorButton.setMenuRole(QAction.PreferencesRole)
        self.copyEditorButton.setIconVisibleInMenu(True)
        self.copyEditorButton.setToolTip(copyEditorBt)
        self.copyEditorButton.setText(copyEditorBt)
        ## Action Paste
        pasteEditorBt = QCoreApplication.translate("PythonConsole", "Paste")
        self.pasteEditorButton = QAction(self)
        self.pasteEditorButton.setCheckable(False)
        self.pasteEditorButton.setEnabled(True)
        self.pasteEditorButton.setIcon(
            QgsApplication.getThemeIcon("mActionEditPaste.svg"))
        self.pasteEditorButton.setMenuRole(QAction.PreferencesRole)
        self.pasteEditorButton.setIconVisibleInMenu(True)
        self.pasteEditorButton.setToolTip(pasteEditorBt)
        self.pasteEditorButton.setText(pasteEditorBt)
        ## Action Run Script (subprocess)
        runScriptEditorBt = QCoreApplication.translate("PythonConsole",
                                                       "Run script")
        self.runScriptEditorButton = QAction(self)
        self.runScriptEditorButton.setCheckable(False)
        self.runScriptEditorButton.setEnabled(True)
        self.runScriptEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconRunScriptConsole.png"))
        self.runScriptEditorButton.setMenuRole(QAction.PreferencesRole)
        self.runScriptEditorButton.setIconVisibleInMenu(True)
        self.runScriptEditorButton.setToolTip(runScriptEditorBt)
        self.runScriptEditorButton.setText(runScriptEditorBt)
        ## Action Run Script (subprocess)
        commentEditorBt = QCoreApplication.translate("PythonConsole",
                                                     "Comment")
        self.commentEditorButton = QAction(self)
        self.commentEditorButton.setCheckable(False)
        self.commentEditorButton.setEnabled(True)
        self.commentEditorButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconCommentEditorConsole.png"))
        self.commentEditorButton.setMenuRole(QAction.PreferencesRole)
        self.commentEditorButton.setIconVisibleInMenu(True)
        self.commentEditorButton.setToolTip(commentEditorBt)
        self.commentEditorButton.setText(commentEditorBt)
        ## Action Run Script (subprocess)
        uncommentEditorBt = QCoreApplication.translate("PythonConsole",
                                                       "Uncomment")
        self.uncommentEditorButton = QAction(self)
        self.uncommentEditorButton.setCheckable(False)
        self.uncommentEditorButton.setEnabled(True)
        self.uncommentEditorButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconUncommentEditorConsole.png"))
        self.uncommentEditorButton.setMenuRole(QAction.PreferencesRole)
        self.uncommentEditorButton.setIconVisibleInMenu(True)
        self.uncommentEditorButton.setToolTip(uncommentEditorBt)
        self.uncommentEditorButton.setText(uncommentEditorBt)
        ## Action for Object browser
        objList = QCoreApplication.translate("PythonConsole",
                                             "Object Inspector...")
        self.objectListButton = QAction(self)
        self.objectListButton.setCheckable(True)
        self.objectListButton.setEnabled(
            self.settings.value("pythonConsole/enableObjectInsp",
                                False,
                                type=bool))
        self.objectListButton.setIcon(
            QgsApplication.getThemeIcon("console/iconClassBrowserConsole.png"))
        self.objectListButton.setMenuRole(QAction.PreferencesRole)
        self.objectListButton.setIconVisibleInMenu(True)
        self.objectListButton.setToolTip(objList)
        self.objectListButton.setText(objList)
        ## Action for Find text
        findText = QCoreApplication.translate("PythonConsole", "Find Text")
        self.findTextButton = QAction(self)
        self.findTextButton.setCheckable(True)
        self.findTextButton.setEnabled(True)
        self.findTextButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSearchEditorConsole.png"))
        self.findTextButton.setMenuRole(QAction.PreferencesRole)
        self.findTextButton.setIconVisibleInMenu(True)
        self.findTextButton.setToolTip(findText)
        self.findTextButton.setText(findText)

        ##----------------Toolbar Console-------------------------------------

        ## Action Show Editor
        showEditor = QCoreApplication.translate("PythonConsole", "Show Editor")
        self.showEditorButton = QAction(self)
        self.showEditorButton.setEnabled(True)
        self.showEditorButton.setCheckable(True)
        self.showEditorButton.setIcon(
            QgsApplication.getThemeIcon("console/iconShowEditorConsole.png"))
        self.showEditorButton.setMenuRole(QAction.PreferencesRole)
        self.showEditorButton.setIconVisibleInMenu(True)
        self.showEditorButton.setToolTip(showEditor)
        self.showEditorButton.setText(showEditor)
        ## Action for Clear button
        clearBt = QCoreApplication.translate("PythonConsole", "Clear Console")
        self.clearButton = QAction(self)
        self.clearButton.setCheckable(False)
        self.clearButton.setEnabled(True)
        self.clearButton.setIcon(
            QgsApplication.getThemeIcon("console/iconClearConsole.png"))
        self.clearButton.setMenuRole(QAction.PreferencesRole)
        self.clearButton.setIconVisibleInMenu(True)
        self.clearButton.setToolTip(clearBt)
        self.clearButton.setText(clearBt)
        ## Action for settings
        optionsBt = QCoreApplication.translate("PythonConsole", "Options...")
        self.optionsButton = QAction(self)
        self.optionsButton.setCheckable(False)
        self.optionsButton.setEnabled(True)
        self.optionsButton.setIcon(
            QgsApplication.getThemeIcon("console/iconSettingsConsole.png"))
        self.optionsButton.setMenuRole(QAction.PreferencesRole)
        self.optionsButton.setIconVisibleInMenu(True)
        self.optionsButton.setToolTip(optionsBt)
        self.optionsButton.setText(optionsBt)
        ## Action menu for class
        actionClassBt = QCoreApplication.translate("PythonConsole",
                                                   "Import Class")
        self.actionClass = QAction(self)
        self.actionClass.setCheckable(False)
        self.actionClass.setEnabled(True)
        self.actionClass.setIcon(
            QgsApplication.getThemeIcon("console/iconClassConsole.png"))
        self.actionClass.setMenuRole(QAction.PreferencesRole)
        self.actionClass.setIconVisibleInMenu(True)
        self.actionClass.setToolTip(actionClassBt)
        self.actionClass.setText(actionClassBt)
        ## Action for Run script
        runBt = QCoreApplication.translate("PythonConsole", "Run Command")
        self.runButton = QAction(self)
        self.runButton.setCheckable(False)
        self.runButton.setEnabled(True)
        self.runButton.setIcon(
            QgsApplication.getThemeIcon("console/iconRunConsole.png"))
        self.runButton.setMenuRole(QAction.PreferencesRole)
        self.runButton.setIconVisibleInMenu(True)
        self.runButton.setToolTip(runBt)
        self.runButton.setText(runBt)
        ## Help action
        helpBt = QCoreApplication.translate("PythonConsole", "Help...")
        self.helpButton = QAction(self)
        self.helpButton.setCheckable(False)
        self.helpButton.setEnabled(True)
        self.helpButton.setIcon(
            QgsApplication.getThemeIcon("console/iconHelpConsole.png"))
        self.helpButton.setMenuRole(QAction.PreferencesRole)
        self.helpButton.setIconVisibleInMenu(True)
        self.helpButton.setToolTip(helpBt)
        self.helpButton.setText(helpBt)

        self.toolBar = QToolBar()
        self.toolBar.setEnabled(True)
        self.toolBar.setFocusPolicy(Qt.NoFocus)
        self.toolBar.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.toolBar.setLayoutDirection(Qt.LeftToRight)
        self.toolBar.setIconSize(QSize(16, 16))
        self.toolBar.setMovable(False)
        self.toolBar.setFloatable(False)
        self.toolBar.addAction(self.clearButton)
        self.toolBar.addAction(self.actionClass)
        self.toolBar.addAction(self.runButton)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.showEditorButton)
        self.toolBar.addSeparator()
        self.toolBar.addAction(self.optionsButton)
        self.toolBar.addAction(self.helpButton)

        self.toolBarEditor = QToolBar()
        self.toolBarEditor.setEnabled(False)
        self.toolBarEditor.setFocusPolicy(Qt.NoFocus)
        self.toolBarEditor.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.toolBarEditor.setLayoutDirection(Qt.LeftToRight)
        self.toolBarEditor.setIconSize(QSize(16, 16))
        self.toolBarEditor.setMovable(False)
        self.toolBarEditor.setFloatable(False)
        self.toolBarEditor.addAction(self.openFileButton)
        self.toolBarEditor.addAction(self.openInEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.saveFileButton)
        self.toolBarEditor.addAction(self.saveAsFileButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.runScriptEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.findTextButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.cutEditorButton)
        self.toolBarEditor.addAction(self.copyEditorButton)
        self.toolBarEditor.addAction(self.pasteEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.commentEditorButton)
        self.toolBarEditor.addAction(self.uncommentEditorButton)
        self.toolBarEditor.addSeparator()
        self.toolBarEditor.addAction(self.objectListButton)

        ## Menu Import Class
        default_command = {
            (QCoreApplication.translate("PythonConsole", "Import Processing Class"),
             QgsApplication.getThemeIcon("console/iconProcessingConsole.png")):
            ["import processing"],
            (QCoreApplication.translate("PythonConsole", "Import PyQt.QtCore Class"),
             QgsApplication.getThemeIcon("console/iconQtCoreConsole.png")):
            ["from qgis.PyQt.QtCore import *"],
            (QCoreApplication.translate("PythonConsole", "Import PyQt.QtGui Class"),
             QgsApplication.getThemeIcon("console/iconQtGuiConsole.png")): [
                "from qgis.PyQt.QtGui import *",
                "from qgis.PyQt.QtWidgets import *"
            ]
        }

        self.classMenu = QMenu()
        for (title, icon), commands in list(default_command.items()):
            action = self.classMenu.addAction(icon, title)
            action.triggered.connect(
                partial(self.shell.commandConsole, commands))

        cM = self.toolBar.widgetForAction(self.actionClass)
        cM.setMenu(self.classMenu)
        cM.setPopupMode(QToolButton.InstantPopup)

        self.widgetButton = QWidget()
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.widgetButton.sizePolicy().hasHeightForWidth())
        self.widgetButton.setSizePolicy(sizePolicy)

        self.widgetButtonEditor = QWidget(self.widgetEditor)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.widgetButtonEditor.sizePolicy().hasHeightForWidth())
        self.widgetButtonEditor.setSizePolicy(sizePolicy)

        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.shellOut.sizePolicy().hasHeightForWidth())
        self.shellOut.setSizePolicy(sizePolicy)

        self.shellOut.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)
        self.shell.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded)

        ##------------ Layout -------------------------------

        self.mainLayout = QGridLayout(self)
        self.mainLayout.setMargin(0)
        self.mainLayout.setSpacing(0)
        self.mainLayout.addWidget(self.widgetButton, 0, 0, 1, 1)
        self.mainLayout.addWidget(self.splitterEditor, 0, 1, 1, 1)

        self.shellOutWidget.layout().insertWidget(0, self.toolBar)

        self.layoutEditor = QGridLayout(self.widgetEditor)
        self.layoutEditor.setMargin(0)
        self.layoutEditor.setSpacing(0)
        self.layoutEditor.addWidget(self.toolBarEditor, 0, 1, 1, 1)
        self.layoutEditor.addWidget(self.widgetButtonEditor, 1, 0, 2, 1)
        self.layoutEditor.addWidget(self.tabEditorWidget, 1, 1, 1, 1)
        self.layoutEditor.addWidget(self.widgetFind, 2, 1, 1, 1)

        ## Layout for the find widget
        self.layoutFind = QGridLayout(self.widgetFind)
        self.layoutFind.setContentsMargins(0, 0, 0, 0)
        self.lineEditFind = QgsFilterLineEdit()
        placeHolderTxt = QCoreApplication.translate("PythonConsole",
                                                    "Enter text to find...")

        self.lineEditFind.setPlaceholderText(placeHolderTxt)
        self.findNextButton = QToolButton()
        self.findNextButton.setEnabled(False)
        toolTipfindNext = QCoreApplication.translate("PythonConsole",
                                                     "Find Next")
        self.findNextButton.setToolTip(toolTipfindNext)
        self.findNextButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconSearchNextEditorConsole.png"))
        self.findNextButton.setIconSize(QSize(24, 24))
        self.findNextButton.setAutoRaise(True)
        self.findPrevButton = QToolButton()
        self.findPrevButton.setEnabled(False)
        toolTipfindPrev = QCoreApplication.translate("PythonConsole",
                                                     "Find Previous")
        self.findPrevButton.setToolTip(toolTipfindPrev)
        self.findPrevButton.setIcon(
            QgsApplication.getThemeIcon(
                "console/iconSearchPrevEditorConsole.png"))
        self.findPrevButton.setIconSize(QSize(24, 24))
        self.findPrevButton.setAutoRaise(True)
        self.caseSensitive = QCheckBox()
        caseSensTr = QCoreApplication.translate("PythonConsole",
                                                "Case Sensitive")
        self.caseSensitive.setText(caseSensTr)
        self.wholeWord = QCheckBox()
        wholeWordTr = QCoreApplication.translate("PythonConsole", "Whole Word")
        self.wholeWord.setText(wholeWordTr)
        self.wrapAround = QCheckBox()
        self.wrapAround.setChecked(True)
        wrapAroundTr = QCoreApplication.translate("PythonConsole",
                                                  "Wrap Around")
        self.wrapAround.setText(wrapAroundTr)
        self.layoutFind.addWidget(self.lineEditFind, 0, 1, 1, 1)
        self.layoutFind.addWidget(self.findPrevButton, 0, 2, 1, 1)
        self.layoutFind.addWidget(self.findNextButton, 0, 3, 1, 1)
        self.layoutFind.addWidget(self.caseSensitive, 0, 4, 1, 1)
        self.layoutFind.addWidget(self.wholeWord, 0, 5, 1, 1)
        self.layoutFind.addWidget(self.wrapAround, 0, 6, 1, 1)

        ##------------ Add first Tab in Editor -------------------------------

        #self.tabEditorWidget.newTabEditor(tabName='first', filename=None)

        ##------------ Signal -------------------------------

        self.findTextButton.triggered.connect(self._toggleFind)
        self.objectListButton.toggled.connect(self.toggleObjectListWidget)
        self.commentEditorButton.triggered.connect(self.commentCode)
        self.uncommentEditorButton.triggered.connect(self.uncommentCode)
        self.runScriptEditorButton.triggered.connect(self.runScriptEditor)
        self.cutEditorButton.triggered.connect(self.cutEditor)
        self.copyEditorButton.triggered.connect(self.copyEditor)
        self.pasteEditorButton.triggered.connect(self.pasteEditor)
        self.showEditorButton.toggled.connect(self.toggleEditor)
        self.clearButton.triggered.connect(self.shellOut.clearConsole)
        self.optionsButton.triggered.connect(self.openSettings)
        self.runButton.triggered.connect(self.shell.entered)
        self.openFileButton.triggered.connect(self.openScriptFile)
        self.openInEditorButton.triggered.connect(self.openScriptFileExtEditor)
        self.saveFileButton.triggered.connect(self.saveScriptFile)
        self.saveAsFileButton.triggered.connect(self.saveAsScriptFile)
        self.helpButton.triggered.connect(self.openHelp)
        self.listClassMethod.itemClicked.connect(self.onClickGoToLine)
        self.lineEditFind.returnPressed.connect(self._findNext)
        self.findNextButton.clicked.connect(self._findNext)
        self.findPrevButton.clicked.connect(self._findPrev)
        self.lineEditFind.textChanged.connect(self._textFindChanged)

        self.findScut = QShortcut(QKeySequence.Find, self.widgetEditor)
        self.findScut.setContext(Qt.WidgetWithChildrenShortcut)
        self.findScut.activated.connect(self._openFind)

        self.findNextScut = QShortcut(QKeySequence.FindNext, self.widgetEditor)
        self.findNextScut.setContext(Qt.WidgetWithChildrenShortcut)
        self.findNextScut.activated.connect(self._findNext)

        self.findPreviousScut = QShortcut(QKeySequence.FindPrevious,
                                          self.widgetEditor)
        self.findPreviousScut.setContext(Qt.WidgetWithChildrenShortcut)
        self.findPreviousScut.activated.connect(self._findPrev)

        # Escape on editor hides the find bar
        self.findScut = QShortcut(Qt.Key_Escape, self.widgetEditor)
        self.findScut.setContext(Qt.WidgetWithChildrenShortcut)
        self.findScut.activated.connect(self._closeFind)
    def setup_thresholds_panel(self, classification):
        """Setup threshold panel in the right panel.

        :param classification: Classification definition.
        :type classification: dict
        """
        # Set text in the label
        layer_purpose = self.parent.step_kw_purpose.selected_purpose()
        layer_subcategory = self.parent.step_kw_subcategory.\
            selected_subcategory()

        if is_raster_layer(self.parent.layer):
            active_band = self.parent.step_kw_band_selector.selected_band()
            layer_extent = self.parent.layer.extent()
            statistics = self.parent.layer.dataProvider().bandStatistics(
                active_band, QgsRasterBandStats.All, layer_extent, 0)
            description_text = continuous_raster_question % (
                layer_purpose['name'],
                layer_subcategory['name'],
                classification['name'],
                statistics.minimumValue,
                statistics.maximumValue)
        else:
            field_name = self.parent.step_kw_field.selected_fields()
            field_index = self.parent.layer.fields().lookupField(field_name)
            min_value_layer = self.parent.layer.minimumValue(field_index)
            max_value_layer = self.parent.layer.maximumValue(field_index)
            description_text = continuous_vector_question % (
                layer_purpose['name'],
                layer_subcategory['name'],
                field_name,
                classification['name'],
                min_value_layer,
                max_value_layer)

        # Set description
        description_label = QLabel(description_text)
        description_label.setWordWrap(True)
        self.right_layout.addWidget(description_label)

        if self.thresholds:
            thresholds = self.thresholds
        else:
            thresholds = self.parent.get_existing_keyword('thresholds')
        selected_unit = self.parent.step_kw_unit.selected_unit()['key']

        self.threshold_classes = OrderedDict()
        classes = classification.get('classes')
        # Sort by value, put the lowest first
        classes = sorted(classes, key=lambda the_key: the_key['value'])

        grid_layout_thresholds = QGridLayout()

        for i, the_class in enumerate(classes):
            class_layout = QHBoxLayout()

            # Class label
            class_label = QLabel(the_class['name'])

            # Min label
            min_label = QLabel(tr('Min >'))

            # Min value as double spin
            min_value_input = QDoubleSpinBox()
            # TODO(IS) We can set the min and max depends on the unit, later
            min_value_input.setMinimum(0)
            min_value_input.setMaximum(999999)

            if thresholds.get(self.active_exposure['key']):
                exposure_thresholds = thresholds.get(
                    self.active_exposure['key'])
                if exposure_thresholds.get(classification['key']):
                    exposure_thresholds_classifications = exposure_thresholds\
                        .get(classification['key'])
                    min_value_input.setValue(
                        exposure_thresholds_classifications['classes'][
                            the_class['key']][0])
                else:
                    default_min = the_class['numeric_default_min']
                    if isinstance(default_min, dict):
                        default_min = the_class[
                            'numeric_default_min'][selected_unit]
                    min_value_input.setValue(default_min)
            else:
                default_min = the_class['numeric_default_min']
                if isinstance(default_min, dict):
                    default_min = the_class[
                        'numeric_default_min'][selected_unit]
                min_value_input.setValue(default_min)
            min_value_input.setSingleStep(0.1)

            # Max label
            max_label = QLabel(tr('Max <='))

            # Max value as double spin
            max_value_input = QDoubleSpinBox()
            # TODO(IS) We can set the min and max depends on the unit, later
            max_value_input.setMinimum(0)
            max_value_input.setMaximum(999999)
            if thresholds.get(self.active_exposure['key']):
                exposure_thresholds = thresholds.get(
                    self.active_exposure['key'])
                if exposure_thresholds.get(classification['key']):
                    exposure_thresholds_classifications = exposure_thresholds \
                        .get(classification['key'])
                    max_value_input.setValue(
                        exposure_thresholds_classifications['classes'][
                            the_class['key']][1])
                else:
                    default_max = the_class['numeric_default_max']
                    if isinstance(default_max, dict):
                        default_max = the_class[
                            'numeric_default_max'][selected_unit]
                    max_value_input.setValue(default_max)
            else:
                default_max = the_class['numeric_default_max']
                if isinstance(default_max, dict):
                    default_max = the_class[
                        'numeric_default_max'][selected_unit]
                max_value_input.setValue(default_max)
            max_value_input.setSingleStep(0.1)

            # Add to class_layout
            class_layout.addWidget(min_label)
            class_layout.addWidget(min_value_input)
            class_layout.addWidget(max_label)
            class_layout.addWidget(max_value_input)

            class_layout.setStretch(0, 1)
            class_layout.setStretch(1, 2)
            class_layout.setStretch(2, 1)
            class_layout.setStretch(3, 2)

            # Add to grid_layout
            grid_layout_thresholds.addWidget(class_label, i, 0)
            grid_layout_thresholds.addLayout(class_layout, i, 1)

            self.threshold_classes[the_class['key']] = [
                min_value_input, max_value_input]

        grid_layout_thresholds.setColumnStretch(0, 1)
        grid_layout_thresholds.setColumnStretch(0, 2)

        def min_max_changed(double_spin_index, mode):
            """Slot when min or max value change.

            :param double_spin_index: The index of the double spin.
            :type double_spin_index: int

            :param mode: The flag to indicate the min or max value.
            :type mode: int
            """
            if mode == MAX_VALUE_MODE:
                current_max_value = list(self.threshold_classes.values())[
                    double_spin_index][1]
                target_min_value = list(self.threshold_classes.values())[
                    double_spin_index + 1][0]
                if current_max_value.value() != target_min_value.value():
                    target_min_value.setValue(current_max_value.value())
            elif mode == MIN_VALUE_MODE:
                current_min_value = list(self.threshold_classes.values())[
                    double_spin_index][0]
                target_max_value = list(self.threshold_classes.values())[
                    double_spin_index - 1][1]
                if current_min_value.value() != target_max_value.value():
                    target_max_value.setValue(current_min_value.value())

        # Set behaviour
        for k, v in list(self.threshold_classes.items()):
            index = list(self.threshold_classes.keys()).index(k)
            if index < len(self.threshold_classes) - 1:
                # Max value changed
                v[1].valueChanged.connect(partial(
                    min_max_changed,
                    double_spin_index=index,
                    mode=MAX_VALUE_MODE))
            if index > 0:
                # Min value
                v[0].valueChanged.connect(partial(
                    min_max_changed,
                    double_spin_index=index,
                    mode=MIN_VALUE_MODE))

        grid_layout_thresholds.setSpacing(0)

        self.right_layout.addLayout(grid_layout_thresholds)
Example #6
0
    def __init__(self,
                 entity,
                 parent=None,
                 notification_bar=None,
                 enable_list=True,
                 can_filter=False,
                 plugin=None):

        QWidget.__init__(self, parent)
        self.current_profile = current_profile()

        self._tbFKEntity = QTableView(self)
        self._tbFKEntity.setEditTriggers(QAbstractItemView.NoEditTriggers)
        self._tbFKEntity.setAlternatingRowColors(True)
        self._tbFKEntity.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.plugin = plugin
        self._add_entity_btn = QToolButton(self)
        self._add_entity_btn.setToolTip(
            QApplication.translate("ForeignKeyMapper", "Add"))
        self._add_entity_btn.setIcon(GuiUtils.get_icon("add.png"))
        self._add_entity_btn.clicked.connect(self.onAddEntity)

        self._edit_entity_btn = QToolButton(self)
        self._edit_entity_btn.setVisible(False)
        self._edit_entity_btn.setToolTip(
            QApplication.translate("ForeignKeyMapper", "Edit"))
        self._edit_entity_btn.setIcon(GuiUtils.get_icon("edit.png"))

        self._filter_entity_btn = QToolButton(self)
        self._filter_entity_btn.setVisible(False)
        self._filter_entity_btn.setToolTip(
            QApplication.translate("ForeignKeyMapper", "Select by expression"))
        self._filter_entity_btn.setIcon(GuiUtils.get_icon("filter.png"))
        self._filter_entity_btn.clicked.connect(self.onFilterEntity)

        self._delete_entity_btn = QToolButton(self)
        self._delete_entity_btn.setToolTip(
            QApplication.translate("ForeignKeyMapper", "Remove"))
        self._delete_entity_btn.setIcon(GuiUtils.get_icon("remove.png"))
        self._delete_entity_btn.clicked.connect(self.onRemoveEntity)

        layout = QVBoxLayout(self)
        layout.setSpacing(4)
        layout.setMargin(5)

        self.grid_layout = QGridLayout()
        self.grid_layout.setHorizontalSpacing(5)
        self.grid_layout.addWidget(self._add_entity_btn, 0, 0, 1, 1)
        self.grid_layout.addWidget(self._filter_entity_btn, 0, 1, 1, 1)
        self.grid_layout.addWidget(self._edit_entity_btn, 0, 2, 1, 1)
        self.grid_layout.addWidget(self._delete_entity_btn, 0, 3, 1, 1)
        self.grid_layout.setColumnStretch(4, 5)

        layout.addLayout(self.grid_layout)
        layout.addWidget(self._tbFKEntity)
        self.social_tenure = self.current_profile.social_tenure

        self._tableModel = None
        self._notifBar = notification_bar
        self._headers = []
        self._entity_attrs = []
        self._cell_formatters = {}
        self._searchable_columns = OrderedDict()
        self._supportsLists = enable_list
        self._deleteOnRemove = False
        self._uniqueValueColIndices = OrderedDict()
        self.global_id = None
        self._deferred_objects = {}
        self._use_expression_builder = can_filter

        if self._use_expression_builder:
            self._filter_entity_btn.setVisible(True)
            self._edit_entity_btn.setVisible(False)
        self.set_entity(entity)
    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)
Example #8
0
    def __init__(self, parent=None, plugin=None):
        super().__init__(parent=parent)
        self.setupUi(self)
        self._plugin = plugin

        self.emitFiltersChanged = True

        # Set up checkboxes for old sources (for legacy saved searches)
        item_types = {
            k: v
            for k, v in PlanetClient.getInstance().item_types_names().items()
            if k != "PSScene"
        }
        row_total = floor(len(item_types) / 2)
        row = col = 0
        gl = QGridLayout(self.oldSourcesWidget)
        gl.setContentsMargins(0, 0, 0, 0)
        for a, b in item_types.items():
            # Strip ' Scene' to reduce horizontal width of 2-column layout, except for SkySat
            name = b.replace(" Scene", "") if b != "SkySat Scene" else b
            cb = QCheckBox(name, parent=self.oldSourcesWidget)
            cb.setProperty("api-name", a)
            gl.addWidget(cb, row, col)
            row += 1
            if row > row_total:
                row = 0
                col += 1
        self.oldSourcesWidget.setLayout(gl)

        self.itemTypeCheckBoxes = [
            self.chkPlanetScope,
            self.chkPlanetScopeOrtho,
            self.chkRapidEyeScene,
            self.chkRapidEyeOrtho,
            self.chkSkySatScene,
            self.chkSkySatCollect,
            self.chkLandsat,
            self.chkSentinel,
        ]

        for source in self.itemTypeCheckBoxes:
            apiname = source.property("api-name")
            if apiname is not None:
                source.stateChanged.connect(self.filtersChanged)

        self.chkYellow.stateChanged.connect(self._yellowFilterToggled)
        self.chkNIR.stateChanged.connect(self._nirFilterToggled)
        self.chkPlanetScope.stateChanged.connect(self._pssceneToggled)
        layout = QVBoxLayout()
        layout.setMargin(0)
        self.legacyWarningWidget = LegacyWarningWidget()
        self.legacyWarningWidget.updateLegacySearch.connect(
            self.updateLegacySearch.emit)
        layout.addWidget(self.legacyWarningWidget)
        self.frameWarningLegacySearch.setLayout(layout)
        self.frameWarningLegacySearch.setVisible(False)

        self.startDateEdit.valueChanged["QDateTime"].connect(
            self.filtersChanged)
        self.startDateEdit.valueChanged["QDateTime"].connect(
            self.change_date_vis)
        self.endDateEdit.valueChanged["QDateTime"].connect(self.filtersChanged)
        self.endDateEdit.valueChanged["QDateTime"].connect(
            self.change_date_vis)

        current_day = QDateTime().currentDateTimeUtc()
        self.startDateEdit.setDateTime(current_day.addMonths(-3))
        self.endDateEdit.setDateTime(current_day)

        self.leStringIDs.textChanged.connect(self.filters_changed)

        for slider in slider_filters:
            sliderWidget = PlanetExplorerRangeSlider(**slider)
            self.frameRangeSliders.layout().addWidget(sliderWidget)
            sliderWidget.rangeChanged.connect(self.filters_changed)

        self.chkGroundControl.stateChanged[int].connect(self.filters_changed)
        self.chkFullCatalog.stateChanged[int].connect(self.filters_changed)
            def __init__(self, relation, parent):
                super().__init__(relation, parent)

                self.setLayout(QGridLayout())
                self.checkbox = QCheckBox('Is this checkbox checkboxin?')
                self.layout().addWidget(self.checkbox)
Example #10
0
    def api_catalog(self, previous_dialog, widget_name, geom_type,
                    feature_type):

        # Manage if geom_type is gully and set grate
        if geom_type == 'gully':
            geom_type == 'grate'

        form_name = 'upsert_catalog_' + geom_type + ''
        form = f'"formName":"{form_name}", "tabName":"data", "editable":"TRUE"'
        feature = f'"feature_type":"{feature_type}"'
        body = self.create_body(form, feature)
        sql = f"SELECT gw_api_getcatalog($${{{body}}}$$)::text"
        row = self.controller.get_row(sql, log_sql=True, commit=True)
        if not row:
            self.controller.show_message("NOT ROW FOR: " + sql, 2)
            return

        complet_list = [json.loads(row[0], object_pairs_hook=OrderedDict)]
        groupBox_1 = QGroupBox("Filter")
        self.filter_form = QGridLayout()

        self.dlg_catalog = ApiCatalogUi()
        self.load_settings(self.dlg_catalog)
        self.dlg_catalog.btn_cancel.clicked.connect(
            partial(self.close_dialog, self.dlg_catalog))
        self.dlg_catalog.btn_accept.clicked.connect(
            partial(self.fill_geomcat_id, previous_dialog, widget_name))

        main_layout = self.dlg_catalog.widget.findChild(
            QGridLayout, 'main_layout')
        result = complet_list[0]['body']['data']
        for field in result['fields']:
            label = QLabel()
            label.setObjectName('lbl_' + field['label'])
            label.setText(field['label'].capitalize())
            if field['widgettype'] == 'combo':
                widget = self.add_combobox(self.dlg_catalog, field)
            if field['layout_id'] == 1:
                self.filter_form.addWidget(label, field['layout_order'], 0)
                self.filter_form.addWidget(widget, field['layout_order'], 1)

        groupBox_1.setLayout(self.filter_form)
        main_layout.addWidget(groupBox_1)
        verticalSpacer1 = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                      QSizePolicy.Expanding)
        main_layout.addItem(verticalSpacer1)

        matcat_id = self.dlg_catalog.findChild(QComboBox, 'matcat_id')

        if self.controller.get_project_type() == 'ws':
            pnom = self.dlg_catalog.findChild(QComboBox, 'pnom')
            dnom = self.dlg_catalog.findChild(QComboBox, 'dnom')
        elif self.controller.get_project_type() == 'ud':
            pnom = self.dlg_catalog.findChild(QComboBox, 'shape')
            dnom = self.dlg_catalog.findChild(QComboBox, 'geom1')

        id = self.dlg_catalog.findChild(QComboBox, 'id')

        # Call get_api_catalog first time
        self.get_api_catalog(matcat_id, pnom, dnom, id, feature_type,
                             geom_type)

        # Set Listeners
        matcat_id.currentIndexChanged.connect(
            partial(self.populate_pn_dn, matcat_id, pnom, dnom, feature_type,
                    geom_type))
        pnom.currentIndexChanged.connect(
            partial(self.get_api_catalog, matcat_id, pnom, dnom, id,
                    feature_type, geom_type))
        dnom.currentIndexChanged.connect(
            partial(self.get_api_catalog, matcat_id, pnom, dnom, id,
                    feature_type, geom_type))

        # Open form
        self.open_dialog(self.dlg_catalog)
Example #11
0
    def __init__(self, iface, base_config, parent=None):
        QDialog.__init__(self, parent)
        self.setupUi(self)
        self.iface = iface
        self.buttonBox.accepted.disconnect()
        self.buttonBox.accepted.connect(self.accepted)
        self.buttonBox.clear()
        self.buttonBox.addButton(QDialogButtonBox.Cancel)
        create_button = self.buttonBox.addButton(self.tr('Create'),
                                                 QDialogButtonBox.AcceptRole)
        create_button.setDefault(True)
        self.ili_file_browse_button.clicked.connect(
            make_file_selector(
                self.ili_file_line_edit,
                title=self.tr('Open Interlis Model'),
                file_filter=self.tr('Interlis Model File (*.ili)')))
        self.buttonBox.addButton(QDialogButtonBox.Help)
        self.buttonBox.helpRequested.connect(self.help_requested)
        self.crs = QgsCoordinateReferenceSystem()
        self.ili2db_options = Ili2dbOptionsDialog()
        self.ili2db_options_button.clicked.connect(self.ili2db_options.open)
        self.multiple_models_dialog = MultipleModelsDialog(self)
        self.multiple_models_button.clicked.connect(
            self.multiple_models_dialog.open)
        self.multiple_models_dialog.accepted.connect(
            self.fill_models_line_edit)
        self.type_combo_box.clear()
        self.type_combo_box.addItem(self.tr('Interlis (use PostGIS)'),
                                    'ili2pg')
        self.type_combo_box.addItem(self.tr('Interlis (use GeoPackage)'),
                                    'ili2gpkg')
        self.type_combo_box.addItem(self.tr('PostGIS'), 'pg')
        self.type_combo_box.addItem(self.tr('GeoPackage'), 'gpkg')
        self.type_combo_box.currentIndexChanged.connect(self.type_changed)
        self.txtStdout.anchorClicked.connect(self.link_activated)
        self.crsSelector.crsChanged.connect(self.crs_changed)
        self.base_configuration = base_config

        self.bar = QgsMessageBar()
        self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.txtStdout.setLayout(QGridLayout())
        self.txtStdout.layout().setContentsMargins(0, 0, 0, 0)
        self.txtStdout.layout().addWidget(self.bar, 0, 0, Qt.AlignTop)

        self.validators = Validators()
        nonEmptyValidator = NonEmptyStringValidator()
        fileValidator = FileValidator(pattern='*.ili', allow_empty=True)
        self.gpkgSaveFileValidator = FileValidator(pattern='*.gpkg',
                                                   allow_non_existing=True)
        self.gpkgOpenFileValidator = FileValidator(pattern='*.gpkg')
        self.gpkg_file_line_edit.textChanged.connect(
            self.validators.validate_line_edits)

        self.restore_configuration()

        self.ili_models_line_edit.setValidator(nonEmptyValidator)
        self.pg_host_line_edit.setValidator(nonEmptyValidator)
        self.pg_database_line_edit.setValidator(nonEmptyValidator)
        self.pg_user_line_edit.setValidator(nonEmptyValidator)
        self.ili_file_line_edit.setValidator(fileValidator)

        self.pg_host_line_edit.textChanged.connect(
            self.validators.validate_line_edits)
        self.pg_host_line_edit.textChanged.emit(self.pg_host_line_edit.text())
        self.pg_database_line_edit.textChanged.connect(
            self.validators.validate_line_edits)
        self.pg_database_line_edit.textChanged.emit(
            self.pg_database_line_edit.text())
        self.pg_user_line_edit.textChanged.connect(
            self.validators.validate_line_edits)
        self.pg_user_line_edit.textChanged.emit(self.pg_user_line_edit.text())
        self.ili_models_line_edit.textChanged.connect(
            self.validators.validate_line_edits)
        self.ili_models_line_edit.textChanged.emit(
            self.ili_models_line_edit.text())
        self.ili_models_line_edit.textChanged.connect(self.on_model_changed)

        self.ilicache = IliCache(base_config)
        self.ilicache.models_changed.connect(self.update_models_completer)
        self.ilicache.new_message.connect(self.show_message)
        self.ilicache.refresh()

        self.ili_file_line_edit.textChanged.connect(
            self.validators.validate_line_edits)
        self.ili_file_line_edit.textChanged.connect(self.ili_file_changed)
        self.ili_file_line_edit.textChanged.emit(
            self.ili_file_line_edit.text())
Example #12
0
    def __init__(self, parent, db_action_type):
        DbConfigPanel.__init__(self, parent, db_action_type)

        lbl_host = QLabel(self.tr("Host"))
        lbl_port = QLabel(self.tr("Port"))
        lbl_database = QLabel(self.tr("Database"))
        lbl_schema = QLabel(self.tr("Schema"))
        lbl_user = QLabel(self.tr("User"))
        lbl_password = QLabel(self.tr("Password"))

        self.pg_host_line_edit = QLineEdit()
        self.pg_host_line_edit.setPlaceholderText(self.tr("Database Hostname"))
        self.pg_host_line_edit.setText('localhost')

        self.pg_port_line_edit = QLineEdit()
        self.pg_port_line_edit.setPlaceholderText(
            self.tr("[Leave empty to use standard port 5432]"))

        self.pg_database_line_edit = QLineEdit()
        self.pg_database_line_edit.setPlaceholderText(self.tr("Database Name"))

        self.pg_schema_line_edit = QLineEdit()
        self.pg_schema_line_edit.setPlaceholderText(
            self.tr("[Leave empty to load all schemas in the database]"))

        self.pg_user_line_edit = QLineEdit()
        self.pg_user_line_edit.setPlaceholderText(self.tr("Database Username"))

        self.pg_password_line_edit = QLineEdit()
        self.pg_password_line_edit.setEchoMode(QLineEdit.Password)
        self.pg_password_line_edit.setPlaceholderText(
            self.tr("[Leave empty to use system password]"))

        from QgisModelBaker.libili2db.ili2dbconfig import BaseConfiguration

        if self._db_action_type != DbActionType.EXPORT:
            self.pg_use_super_login = QCheckBox()
            self.pg_use_super_login.setText(
                self.tr(
                    "Generate schema with superuser login from settings ({})").
                format(BaseConfiguration().super_pg_user))

        layout = QGridLayout(self)
        layout.addWidget(lbl_host, 0, 0)
        layout.addWidget(lbl_port, 1, 0)
        layout.addWidget(lbl_database, 2, 0)
        layout.addWidget(lbl_schema, 3, 0)
        layout.addWidget(lbl_user, 4, 0)
        layout.addWidget(lbl_password, 5, 0)

        layout.addWidget(self.pg_host_line_edit, 0, 1)
        layout.addWidget(self.pg_port_line_edit, 1, 1)
        layout.addWidget(self.pg_database_line_edit, 2, 1)
        layout.addWidget(self.pg_schema_line_edit, 3, 1)
        layout.addWidget(self.pg_user_line_edit, 4, 1)
        layout.addWidget(self.pg_password_line_edit, 5, 1)

        if self._db_action_type != DbActionType.EXPORT:
            layout.addWidget(self.pg_use_super_login, 6, 1)

        # define validators
        self.validators = Validators()
        nonEmptyValidator = NonEmptyStringValidator()

        self.pg_host_line_edit.setValidator(nonEmptyValidator)
        self.pg_database_line_edit.setValidator(nonEmptyValidator)
        self.pg_user_line_edit.setValidator(nonEmptyValidator)

        self.pg_host_line_edit.textChanged.connect(
            self.validators.validate_line_edits)
        self.pg_host_line_edit.textChanged.emit(self.pg_host_line_edit.text())
        self.pg_database_line_edit.textChanged.connect(
            self.validators.validate_line_edits)
        self.pg_database_line_edit.textChanged.emit(
            self.pg_database_line_edit.text())
        self.pg_user_line_edit.textChanged.connect(
            self.validators.validate_line_edits)
        self.pg_user_line_edit.textChanged.emit(self.pg_user_line_edit.text())

        self.pg_host_line_edit.textChanged.connect(self.notify_fields_modified)
        self.pg_port_line_edit.textChanged.connect(self.notify_fields_modified)
        self.pg_database_line_edit.textChanged.connect(
            self.notify_fields_modified)
        self.pg_schema_line_edit.textChanged.connect(
            self.notify_fields_modified)
        self.pg_user_line_edit.textChanged.connect(self.notify_fields_modified)
        self.pg_password_line_edit.textChanged.connect(
            self.notify_fields_modified)
Example #13
0
    def stream(self):

        goForStream = True

        # Avoid auth exception if you reopen the project and don't open the search
        if self.mySearch == None:
            self.mySearch = MySearch(self.iface)

        # Get selected feature of active layer
        service = self.selectedFeature['service']

        # Setup raster params
        isWcs = False
        if service == 'BaseMap':
            if self.mySearch.bmAuth is None:
                try:
                    self.mySearch.bmSetAuth()
                except:
                    return
            username = self.mySearch.bmUsernameInput.text()
            password = self.mySearch.bmPasswordInput.text()
            layers = self.mySearch.bmGetLayer(self.selectedFeature['wmts'])
            styles = 'default'
            tileMatrixSet = '4326'
            urlAttr = 'wmts'
        elif service == 'Data':
            if self.mySearch.dtHeaders is None:
                try:
                    self.mySearch.dtSetAuth()
                except:
                    return
            username = '******'
            password = self.mySearch.dtApikeyInput.text()

            # Dialog for image choice (panchro/multi & wmts/wcs)
            self.msgBox = QMessageBox()
            self.msgBox.setWindowTitle(self.menu)

            if self.selectedFeature['processingLevel'] == 'ALBUM':
                self.iface.messageBar().pushMessage("Warning", "The feature can't be displayed (no WMTS for Archive features)", level=Qgis.Warning)
                goForStream = False
            else:
                protocolGroup = QGroupBox('Protocol')
                protocolGrid = QGridLayout()
                wmtsRadio = QRadioButton('WMTS')
                wcsRadio = QRadioButton('WCS')
                protocolGrid.addWidget(wmtsRadio, 0, 0)
                protocolGrid.addWidget(wcsRadio, 0, 1)
                protocolGroup.setLayout(protocolGrid)
                
                styleGroup = QGroupBox('Style')
                styleGrid = QGridLayout()
                multispectralRadio = QRadioButton('multispectral')
                panchromaticRadio = QRadioButton('panchromatic')
                pmsRadio = QRadioButton('pms')
                styleGrid.addWidget(multispectralRadio, 0, 0)
                styleGrid.addWidget(panchromaticRadio, 0, 1)
                styleGrid.addWidget(pmsRadio, 0, 2)
                styleGroup.setLayout(styleGrid)

                self.msgBox.layout().addWidget(protocolGroup, 0, 0)
                self.msgBox.layout().addWidget(styleGroup, 1, 0)

                wmtsRadio.setChecked(True)
                if type(self.selectedFeature['wcs_multispectral']) != str and type(self.selectedFeature['wcs_panchromatic']) != str and type(self.selectedFeature['wcs_pms']) != str:
                    protocolGroup.setEnabled(False)

                if type(self.selectedFeature['wmts_pms']) != str:
                    multispectralRadio.setEnabled(True)
                    panchromaticRadio.setEnabled(True)
                    pmsRadio.setEnabled(False)
                    multispectralRadio.setChecked(True)
                else:
                    multispectralRadio.setEnabled(True)
                    panchromaticRadio.setEnabled(True)
                    pmsRadio.setEnabled(True)
                    pmsRadio.setChecked(True)

                

                self.msgBox.setStandardButtons(QMessageBox.Abort | QMessageBox.Ok)
                reply = self.msgBox.exec_()
                if reply == QMessageBox.Abort:
                    return
                if wmtsRadio.isChecked():
                    urlAttr = 'wmts_'
                    layers = 'default'
                    styles = 'rgb'
                    tileMatrixSet = 'EPSG4326'
                else:
                    urlAttr = 'wcs_'
                    isWcs = True
                if multispectralRadio.isChecked():
                    urlAttr += 'multispectral'
                elif panchromaticRadio.isChecked():
                    urlAttr += 'panchromatic'
                else:
                    urlAttr += 'pms'
        else:
            self.error(f'Service "{service}" of the feature ocg_fid={self.selectedFeature.id()} isn\'t recognized\nIt should be "Basemap" or "Data"')
            return


        if goForStream:
            # Add a WMTS raster layer
            # Order of url parameters are important !
            # Why layers is required, maybe is an internal id for wmts gesture ?
            # What is styles ?
            try:
                url = self.selectedFeature[urlAttr]
                name = f'{service} {self.selectedFeature["id"]}'
                if isWcs:
                    rlayer = QgsRasterLayer(f'dpiMode=7&identifier=default&password={password}&url={url}&username={username}', name, 'wcs')
                else:
                    rlayer = QgsRasterLayer(f'crs=EPSG:4326&dpiMode=7&format=image/png&layers={layers}&password={password}&styles={styles}&tileMatrixSet={tileMatrixSet}&url={url}&username={username}', name, 'wms')
            except Exception as e:
                self.error(f'Error in protocol connection\n\n{str(e)}')
                return
            if rlayer.isValid() == False:
                self.error(f'Raster layer is invalid\n\n{rlayer.error()}')
                return

            QgsProject.instance().addMapLayer(rlayer)
Example #14
0
    def get_selector(self,
                     dialog,
                     selector_type,
                     filter=False,
                     widget=None,
                     text_filter=None,
                     current_tab=None):
        """
        Ask to DB for selectors and make dialog
            :param dialog: Is a standard dialog, from file selector.ui, where put widgets
            :param selector_type: List of selectors to ask DB ['exploitation', 'state', ...]
        """

        index = 0
        main_tab = dialog.findChild(QTabWidget, 'main_tab')

        # Set filter
        if filter is not False:
            main_tab = dialog.findChild(QTabWidget, 'main_tab')
            text_filter = tools_qt.get_text(dialog, widget)
            if text_filter in ('null', None):
                text_filter = ''

            # Set current_tab
            index = dialog.main_tab.currentIndex()
            current_tab = dialog.main_tab.widget(index).objectName()

        # Profilactic control of nones
        if text_filter is None:
            text_filter = ''
        # Built querytext
        form = f'"currentTab":"{current_tab}"'
        extras = f'"selectorType":{selector_type}, "filterText":"{text_filter}"'
        body = tools_gw.create_body(form=form, extras=extras)
        json_result = tools_gw.execute_procedure('gw_fct_getselectors', body)

        if not json_result or json_result['status'] == 'Failed':
            return False

        # Get styles
        stylesheet = json_result['body']['form'][
            'style'] if 'style' in json_result['body']['form'] else None
        color_rows = False
        if stylesheet:
            # Color selectors zebra-styled
            if 'rowsColor' in stylesheet and stylesheet[
                    'rowsColor'] is not None:
                color_rows = tools_os.set_boolean(stylesheet['rowsColor'],
                                                  False)

        for form_tab in json_result['body']['form']['formTabs']:

            if filter and form_tab['tabName'] != str(current_tab):
                continue

            selection_mode = form_tab['selectionMode']

            # Create one tab for each form_tab and add to QTabWidget
            tab_widget = QWidget(main_tab)
            tab_widget.setObjectName(form_tab['tabName'])
            tab_widget.setProperty('selector_type', form_tab['selectorType'])
            if filter:
                main_tab.removeTab(index)
                main_tab.insertTab(index, tab_widget, form_tab['tabLabel'])
            else:
                main_tab.addTab(tab_widget, form_tab['tabLabel'])
            if 'typeaheadForced' in form_tab and form_tab[
                    'typeaheadForced'] is not None:
                tab_widget.setProperty('typeahead_forced',
                                       form_tab['typeaheadForced'])

            # Create a new QGridLayout and put it into tab
            gridlayout = QGridLayout()
            gridlayout.setObjectName("lyt" + form_tab['tabName'])
            tab_widget.setLayout(gridlayout)
            field = {}
            i = 0

            if 'typeaheadFilter' in form_tab:
                label = QLabel()
                label.setObjectName('lbl_filter')
                label.setText('Filter:')
                if tools_qt.get_widget(
                        dialog,
                        'txt_filter_' + str(form_tab['tabName'])) is None:
                    widget = QLineEdit()
                    widget.setObjectName('txt_filter_' +
                                         str(form_tab['tabName']))
                    widget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
                    widget.textChanged.connect(
                        partial(self.get_selector,
                                dialog,
                                selector_type,
                                filter=True,
                                widget=widget,
                                current_tab=current_tab))
                    widget.setLayoutDirection(Qt.RightToLeft)

                else:
                    widget = tools_qt.get_widget(
                        dialog, 'txt_filter_' + str(form_tab['tabName']))

                field['layoutname'] = gridlayout.objectName()
                field['layoutorder'] = i
                i = i + 1
                gridlayout.addWidget(label, int(field['layoutorder']), 0)
                gridlayout.addWidget(widget, int(field['layoutorder']), 2)
                widget.setFocus()

            if 'manageAll' in form_tab:
                if (form_tab['manageAll']).lower() == 'true':
                    if tools_qt.get_widget(
                            dialog, f"chk_all_{form_tab['tabName']}") is None:
                        widget = QCheckBox()
                        widget.setObjectName('chk_all_' +
                                             str(form_tab['tabName']))
                        widget.stateChanged.connect(
                            partial(self._manage_all, dialog, widget))
                        widget.setLayoutDirection(Qt.LeftToRight)
                    else:
                        widget = tools_qt.get_widget(
                            dialog, f"chk_all_{form_tab['tabName']}")
                    widget.setText('Check all')
                    field['layoutname'] = gridlayout.objectName()
                    field['layoutorder'] = i
                    i = i + 1
                    gridlayout.addWidget(widget, int(field['layoutorder']), 0,
                                         1, -1)

            for order, field in enumerate(form_tab['fields']):
                try:
                    # Create checkbox
                    widget = tools_gw.add_checkbox(field)
                    widget.setText(field['label'])
                    widget.stateChanged.connect(
                        partial(self._set_selection_mode, dialog, widget,
                                selection_mode))
                    widget.setLayoutDirection(Qt.LeftToRight)

                    # Set background color every other item (if enabled)
                    if color_rows and order % 2 == 0:
                        widget.setStyleSheet(f"background-color: #E9E7E3")

                    # Add widget to layout
                    field['layoutname'] = gridlayout.objectName()
                    field['layoutorder'] = order + i + 1
                    gridlayout.addWidget(widget, int(field['layoutorder']), 0,
                                         1, -1)
                except Exception:
                    msg = f"key 'comboIds' or/and comboNames not found WHERE columname='{field['columnname']}' AND " \
                          f"widgetname='{field['widgetname']}'"
                    tools_qgis.show_message(msg, 2)

            vertical_spacer1 = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                           QSizePolicy.Expanding)
            gridlayout.addItem(vertical_spacer1)

        # Set last tab used by user as current tab
        tabname = json_result['body']['form']['currentTab']
        tab = main_tab.findChild(QWidget, tabname)

        if tab:
            main_tab.setCurrentWidget(tab)
Example #15
0
    def _setup_columns_content_area(self):
        # Only use this if entity supports documents
        # self.entity_tab_widget = None
        self.doc_widget = None

        self.entity_scroll_area = QScrollArea(self)
        self.entity_scroll_area.setFrameShape(QFrame.NoFrame)
        self.entity_scroll_area.setWidgetResizable(True)
        self.entity_scroll_area.setObjectName('scrollArea')

        # Grid layout for controls
        self.gl = QGridLayout(self.scroll_widget_contents)
        self.gl.setObjectName('gl_widget_contents')

        # Append column labels and widgets
        table_name = self._entity.name
        columns = table_column_names(table_name)
        # Iterate entity column and assert if they exist
        row_id = 0
        for column_name, column_widget in self.column_widgets.items():
            c = self.columns[column_name]

            if c.name in self.exclude_columns:
                continue
            if isinstance(c, MultipleSelectColumn):
                continue
            if c.name not in columns and not isinstance(c, VirtualColumn):
                continue

            if column_widget is not None:
                header = c.ui_display()
                self.c_label = QLabel(self.scroll_widget_contents)

                self.c_label.setText(header)
                self.gl.addWidget(self.c_label, row_id, 0, 1, 1)

                if c.TYPE_INFO == 'AUTO_GENERATED':
                    column_widget.setReadOnly(False)
                    column_widget.btn_load.hide()
                self.gl.addWidget(column_widget, row_id, 1, 1, 1)

                col_name = c.name

                # Add widget to MapperMixin collection
                self.addMapping(
                    col_name,
                    column_widget,
                    c.mandatory,
                    pseudoname=c.ui_display()
                )

                # Bump up row_id
                row_id += 1

        self.entity_scroll_area.setWidget(self.scroll_widget_contents)
        if self.entity_tab_widget is None:
            self.entity_tab_widget = QTabWidget(self)
        # Check if there are children and add foreign key browsers

        # Add primary tab if necessary
        self._add_primary_attr_widget()
        # self.entity_tab_widget.setTabEnabled(0, False)  # enable/disable the tab
        # set the style sheet
        self.setStyleSheet(
            "QTabBar::tab::selected {width: 0; height: 0; margin: 0; "
            "padding: 0; border: none;} ")
        # Return the correct widget
        if self.entity_tab_widget is not None:
            return self.entity_tab_widget

        return self.entity_scroll_area
Example #16
0
    def __init__(self, parameter, parent=None):
        """Constructor

        :param parameter: A DefaultSelectParameter object.
        :type parameter: DefaultSelectParameter
        """
        super(DefaultSelectParameterWidget, self).__init__(parameter, parent)

        self.default_layout = QHBoxLayout()
        self.radio_button_layout = QHBoxLayout()
        self.radio_button_widget = QWidget()

        self.default_label = QLabel(tr('Default'))

        # Create radio button group
        self.default_input_button_group = QButtonGroup()

        # Define string enabler for radio button
        self.radio_button_enabler = self.input.itemData(0, Qt.UserRole)

        for i in range(len(self._parameter.default_labels)):
            if '%s' in self._parameter.default_labels[i]:
                label = (self._parameter.default_labels[i] %
                         self._parameter.default_values[i])
            else:
                label = self._parameter.default_labels[i]

            radio_button = QRadioButton(label)
            self.radio_button_layout.addWidget(radio_button)
            self.default_input_button_group.addButton(radio_button, i)
            if self._parameter.default_value == \
                    self._parameter.default_values[i]:
                radio_button.setChecked(True)

        # Create double spin box for custom value
        self.custom_value = QDoubleSpinBox()
        if self._parameter.default_values[-1]:
            self.custom_value.setValue(self._parameter.default_values[-1])
        has_min = False
        if self._parameter.minimum is not None:
            has_min = True
            self.custom_value.setMinimum(self._parameter.minimum)
        has_max = False
        if self._parameter.maximum is not None:
            has_max = True
            self.custom_value.setMaximum(self._parameter.maximum)
        if has_min and has_max:
            step = (self._parameter.maximum - self._parameter.minimum) / 100.0
            self.custom_value.setSingleStep(step)
        self.radio_button_layout.addWidget(self.custom_value)

        self.toggle_custom_value()

        # Reset the layout
        self.input_layout.setParent(None)
        self.help_layout.setParent(None)

        self.label.setParent(None)
        self.inner_input_layout.setParent(None)

        self.input_layout = QGridLayout()
        self.input_layout.setSpacing(0)

        self.input_layout.addWidget(self.label, 0, 0)
        self.input_layout.addLayout(self.inner_input_layout, 0, 1)
        self.input_layout.addWidget(self.default_label, 1, 0)
        self.input_layout.addLayout(self.radio_button_layout, 1, 1)

        self.main_layout.addLayout(self.input_layout)
        self.main_layout.addLayout(self.help_layout)

        # check every added combobox, it could have been toggled by
        # the existing keyword
        self.toggle_input()

        # Connect
        # noinspection PyUnresolvedReferences
        self.input.currentIndexChanged.connect(self.toggle_input)
        self.default_input_button_group.buttonClicked.connect(
            self.toggle_custom_value)
    def populate_details(self):
        self.bundleWidgets = []

        permissions = [img[PERMISSIONS] for img in self.images]
        item_bundles = order_bundles.bundles_for_item_type(
            self.item_type, permissions=permissions)
        default = order_bundles.item_default_bundle_name(self.item_type)

        def _center(obj):
            hlayout = QHBoxLayout()
            hlayout.addStretch()
            hlayout.addWidget(obj)
            hlayout.addStretch()
            return hlayout

        layout = QVBoxLayout()
        layout.setMargin(0)
        layout.setSpacing(20)

        layout.addLayout(_center(QLabel("<b>RECTIFIED ASSETS</b>")))

        gridlayout = QGridLayout()
        gridlayout.setMargin(0)

        i = 0
        for bundle in item_bundles:
            bundleid = bundle["id"]
            if bundle["rectification"] == "orthorectified":
                name = bundle["name"]
                description = bundle["description"]
                udm = bundle.get("auxiliaryFiles",
                                 "").lower().startswith("udm2")
                w = PlanetOrderBundleWidget(bundleid, name, description, udm,
                                            True)
                gridlayout.addWidget(w, i // 2, i % 2)
                w.setSelected(bundleid == default)
                w.selectionChanged.connect(
                    partial(self._bundle_selection_changed, w))
                self.bundleWidgets.append(w)
                i += 1

        layout.addLayout(gridlayout)

        self.labelUnrectified = QLabel("<b>UNRECTIFIED ASSETS</b>")
        layout.addLayout(_center(self.labelUnrectified))

        self.widgetUnrectified = QWidget()

        gridlayoutUnrect = QGridLayout()
        gridlayoutUnrect.setMargin(0)

        i = 0
        for bundle in item_bundles:
            bundleid = bundle["id"]
            if bundle["rectification"] != "orthorectified":
                name = bundle["name"]
                description = bundle["description"]
                udm = bundle.get("auxiliaryFiles",
                                 "").lower().startswith("udm2")
                w = PlanetOrderBundleWidget(bundleid, name, description, udm,
                                            False)
                gridlayoutUnrect.addWidget(w, i // 2, i % 2)
                w.selectionChanged.connect(
                    partial(self._bundle_selection_changed, w))
                self.bundleWidgets.append(w)
                i += 1

        self.widgetUnrectified.setLayout(gridlayoutUnrect)
        layout.addWidget(self.widgetUnrectified)

        self.labelMore = QLabel('<a href="#">+ Show More</a>')
        self.labelMore.setOpenExternalLinks(False)
        self.labelMore.setTextInteractionFlags(Qt.LinksAccessibleByMouse)
        self.labelMore.linkActivated.connect(self._showMoreClicked)
        layout.addLayout(_center(self.labelMore))

        self.widgetUnrectified.hide()
        self.labelUnrectified.hide()
        self.widgetDetails.setLayout(layout)
Example #18
0
    def api_search(self, dlg_mincut=None):

        # If search is open, dont let user open another one
        open_search = self.controller.get_user_setting_value('open_search', 'false')
        if open_search in ("True", "true", True) and dlg_mincut is None:
            return

        form = ""
        if self.dlg_search is None and dlg_mincut is None:
            self.init_dialog()
        if dlg_mincut:
            self.dlg_search = dlg_mincut
            self.is_mincut = True
            form = f'"singleTab":"tab_address"'

        self.dlg_search.lbl_msg.setStyleSheet("QLabel{color:red;}")
        self.dlg_search.lbl_msg.setVisible(False)
        qgis_project_add_schema = self.controller.plugin_settings_value('gwAddSchema')

        self.controller.set_user_settings_value('open_search', 'true')

        if qgis_project_add_schema is None:
            body = self.create_body(form=form)
        else:
            extras = f'"addSchema":"{qgis_project_add_schema}"'
            body = self.create_body(form=form, extras=extras)
        function_name = "gw_fct_getsearch"
        complet_list = self.controller.get_json(function_name, body)
        if not complet_list:
            return False

        main_tab = self.dlg_search.findChild(QTabWidget, 'main_tab')
        if dlg_mincut and len(complet_list["form"]) == 1:
            main_tab = self.dlg_search.findChild(QTabWidget, 'main_tab')
            main_tab.setStyleSheet("QTabBar::tab { background-color: transparent; text-align:left;"
                                   "border: 1px solid transparent;}"    
                                   "QTabWidget::pane { background-color: #fcfcfc; border: 1 solid #dadada;}")

        first_tab = None
        self.lineedit_list = []
        for tab in complet_list["form"]:
            if first_tab is None:
                first_tab = tab['tabName']
            tab_widget = QWidget(main_tab)
            tab_widget.setObjectName(tab['tabName'])
            main_tab.addTab(tab_widget, tab['tabLabel'])
            gridlayout = QGridLayout()
            tab_widget.setLayout(gridlayout)
            x = 0

            for field in tab['fields']:
                label = QLabel()
                label.setObjectName('lbl_' + field['label'])
                label.setText(field['label'].capitalize())
                widget = None
                if field['widgettype'] == 'typeahead':
                    completer = QCompleter()
                    widget = self.add_lineedit(field)
                    widget = self.set_typeahead_completer(widget, completer)
                    self.lineedit_list.append(widget)
                elif field['widgettype'] == 'combo':
                    widget = self.add_combobox(field)
                gridlayout.addWidget(label, x, 0)
                gridlayout.addWidget(widget, x, 1)
                x += 1

            vertical_spacer1 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
            gridlayout.addItem(vertical_spacer1)

        if self.is_mincut is False:
            self.controller.manage_translation('search', self.dlg_search)
Example #19
0
def main():
    """Main function to run the example."""
    from safe.test.utilities import get_qgis_app
    QGIS_APP, CANVAS, IFACE, PARENT = get_qgis_app(qsetting=INASAFE_TEST)

    options = OrderedDict([
        (DO_NOT_REPORT, {
            'label': 'Do not report',
            'value': None,
            'type': STATIC,
            'constraint': {}
        }),
        (GLOBAL_DEFAULT, {
            'label': 'Global default',
            'value': 0.5,
            'type': STATIC,
            'constraint': {}
        }),
        (
            CUSTOM_VALUE,
            {
                'label': 'Custom',
                'value': 0.7,  # Taken from keywords / recent value
                'type': SINGLE_DYNAMIC,
                'constraint': {
                    'min': 0,
                    'max': 1
                }
            }),
        (
            FIELDS,
            {
                'label': 'Ratio fields',
                'value': ['field A', 'field B',
                          'field C'],  # Taken from keywords
                'type': MULTIPLE_DYNAMIC,
                'constraint': {}
            })
    ])

    default_value_parameter = GroupSelectParameter()
    default_value_parameter.name = 'Group Select parameter'
    default_value_parameter.help_text = 'Help text'
    default_value_parameter.description = 'Description'
    default_value_parameter.options = options
    default_value_parameter.selected = 'ratio fields'

    parameters = [default_value_parameter]

    extra_parameters = [(GroupSelectParameter, GroupSelectParameterWidget)]

    parameter_container = ParameterContainer(parameters,
                                             extra_parameters=extra_parameters)
    parameter_container.setup_ui()

    widget = QWidget()
    layout = QGridLayout()
    layout.addWidget(parameter_container)

    def show_error_message(parent, exception):
        """Generate error message to handle parameter errors

        :param parent: The widget as a parent of message box
        :type parent: QWidget
        :param exception: python Exception or Error
        :type exception: Exception
        """
        box = QMessageBox()
        box.critical(parent, 'Error occured', str(exception))

    def show_parameter(the_parameter_container):
        """Print the value of parameter.

        :param the_parameter_container: A parameter container
        :type the_parameter_container: ParameterContainer
        """
        def show_parameter_value(a_parameter):
            if isinstance(a_parameter, GroupParameter):
                for param in a_parameter.value:
                    show_parameter_value(param)
            else:
                # print(a_parameter.guid, a_parameter.name, a_parameter.value)
                pass

        try:
            the_parameters = the_parameter_container.get_parameters()
            if the_parameters:
                for parameter in the_parameters:
                    show_parameter_value(parameter)
        except Exception as inst:
            show_error_message(parameter_container, inst)

    print_button = QPushButton('Print Result')
    # noinspection PyUnresolvedReferences
    print_button.clicked.connect(
        partial(show_parameter, the_parameter_container=parameter_container))

    layout.addWidget(print_button)

    widget.setLayout(layout)
    widget.setGeometry(0, 0, 500, 500)

    widget.show()

    sys.exit(QGIS_APP.exec_())
    def __init__(self, iface, base_config, parent=None):
        QDialog.__init__(self, parent)
        self.setupUi(self)
        self.iface = iface
        self.db_simple_factory = DbSimpleFactory()
        QgsGui.instance().enableAutoGeometryRestore(self)
        self.buttonBox.accepted.disconnect()
        self.buttonBox.accepted.connect(self.accepted)
        self.buttonBox.clear()
        self.buttonBox.addButton(QDialogButtonBox.Cancel)
        create_button = self.buttonBox.addButton(self.tr('Create'),
                                                 QDialogButtonBox.AcceptRole)
        create_button.setDefault(True)
        self.ili_file_browse_button.clicked.connect(
            make_file_selector(
                self.ili_file_line_edit,
                title=self.tr('Open Interlis Model'),
                file_filter=self.tr('Interlis Model File (*.ili)')))
        self.buttonBox.addButton(QDialogButtonBox.Help)
        self.buttonBox.helpRequested.connect(self.help_requested)
        self.crs = QgsCoordinateReferenceSystem()
        self.ili2db_options = Ili2dbOptionsDialog()
        self.ili2db_options_button.clicked.connect(self.ili2db_options.open)
        self.ili2db_options.finished.connect(self.fill_toml_file_info_label)
        self.multiple_models_dialog = MultipleModelsDialog(self)
        self.multiple_models_button.clicked.connect(
            self.multiple_models_dialog.open)
        self.multiple_models_dialog.accepted.connect(
            self.fill_models_line_edit)

        self.type_combo_box.clear()
        self._lst_panel = dict()

        for db_id in self.db_simple_factory.get_db_list(True):
            self.type_combo_box.addItem(displayDbIliMode[db_id], db_id)

        for db_id in self.db_simple_factory.get_db_list(False):
            db_factory = self.db_simple_factory.create_factory(db_id)
            item_panel = db_factory.get_config_panel(self,
                                                     DbActionType.GENERATE)
            self._lst_panel[db_id] = item_panel
            self.db_layout.addWidget(item_panel)

        self.type_combo_box.currentIndexChanged.connect(self.type_changed)
        self.txtStdout.anchorClicked.connect(self.link_activated)
        self.crsSelector.crsChanged.connect(self.crs_changed)
        self.base_configuration = base_config

        self.bar = QgsMessageBar()
        self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.txtStdout.setLayout(QGridLayout())
        self.txtStdout.layout().setContentsMargins(0, 0, 0, 0)
        self.txtStdout.layout().addWidget(self.bar, 0, 0, Qt.AlignTop)

        self.validators = Validators()
        nonEmptyValidator = NonEmptyStringValidator()
        fileValidator = FileValidator(pattern='*.ili', allow_empty=True)

        self.restore_configuration()

        self.ili_models_line_edit.setValidator(nonEmptyValidator)
        self.ili_file_line_edit.setValidator(fileValidator)

        self.ili_models_line_edit.textChanged.connect(
            self.validators.validate_line_edits)
        self.ili_models_line_edit.textChanged.emit(
            self.ili_models_line_edit.text())
        self.ili_models_line_edit.textChanged.connect(self.on_model_changed)
        self.ili_models_line_edit.textChanged.connect(
            self.complete_models_completer)
        self.ili_models_line_edit.punched.connect(
            self.complete_models_completer)

        self.ilicache = IliCache(self.base_configuration)
        self.refresh_ili_cache()
        self.ili_models_line_edit.setPlaceholderText(
            self.tr('[Search model from repository]'))

        self.ili_file_line_edit.textChanged.connect(
            self.validators.validate_line_edits)
        self.ili_file_line_edit.textChanged.connect(self.ili_file_changed)
        self.ili_file_line_edit.textChanged.emit(
            self.ili_file_line_edit.text())
Example #21
0
    def populate_details(self):
        self.bundleWidgets = []

        client = PlanetClient.getInstance()
        permissions = [img[PERMISSIONS] for img in self.images]
        item_bundles = client.bundles_for_item_type_and_permissions(
            self.item_type, permissions=permissions)
        default = default_bundles.get(self.item_type, [])

        def _center(obj):
            hlayout = QHBoxLayout()
            hlayout.addStretch()
            hlayout.addWidget(obj)
            hlayout.addStretch()
            return hlayout

        layout = QVBoxLayout()
        layout.setMargin(0)
        layout.setSpacing(20)

        layout.addLayout(_center(QLabel("<b>RECTIFIED ASSETS</b>")))

        gridlayout = QGridLayout()
        gridlayout.setMargin(0)

        assets = PlanetClient.getInstance().asset_types_for_item_type(
            self.item_type)
        assets_and_bands = {}
        for a in assets:
            if "bands" in a:
                assets_and_bands[a["id"]] = len(a["bands"])

        widgets = {}
        i = 0
        for bundleid, bundle in item_bundles.items():
            if bundle["rectification"] == "orthorectified":
                w = PlanetOrderBundleWidget(bundleid, bundle, self.item_type)
                gridlayout.addWidget(w, i // 2, i % 2)
                w.setSelected(False)
                widgets[bundleid] = w
                w.selectionChanged.connect(
                    partial(self._bundle_selection_changed, w))
                self.bundleWidgets.append(w)
                i += 1

        selected = False
        for defaultid in default:
            for bundleid, w in widgets.items():
                if defaultid == bundleid:
                    w.setSelected(True)
                    selected = True
                    break
            if selected:
                break

        layout.addLayout(gridlayout)

        self.labelUnrectified = QLabel("<b>UNRECTIFIED ASSETS</b>")
        layout.addLayout(_center(self.labelUnrectified))

        self.widgetUnrectified = QWidget()

        gridlayoutUnrect = QGridLayout()
        gridlayoutUnrect.setMargin(0)

        i = 0
        for bundleid, bundle in item_bundles.items():
            if bundle["rectification"] != "orthorectified":
                w = PlanetOrderBundleWidget(bundleid, bundle, self.item_type)
                gridlayoutUnrect.addWidget(w, i // 2, i % 2)
                w.selectionChanged.connect(
                    partial(self._bundle_selection_changed, w))
                self.bundleWidgets.append(w)
                i += 1

        self.widgetUnrectified.setLayout(gridlayoutUnrect)
        layout.addWidget(self.widgetUnrectified)

        self.labelMore = QLabel('<a href="#">+ Show More</a>')
        self.labelMore.setOpenExternalLinks(False)
        self.labelMore.setTextInteractionFlags(Qt.LinksAccessibleByMouse)
        self.labelMore.linkActivated.connect(self._showMoreClicked)
        layout.addLayout(_center(self.labelMore))

        self.widgetUnrectified.hide()
        self.labelUnrectified.hide()
        self.widgetDetails.setLayout(layout)
    def __init__(self, parent=None):
        """Constructor."""
        super(CoordinateCaptureDockWidget, self).__init__(parent)

        self.setWindowTitle(self.tr("Coordinate Capture"))
        self.setGeometry(0, 0, 300, 228)
        self.dockWidgetContents = QWidget(self)
        self.setWidget(self.dockWidgetContents)
        self.gridLayout = QGridLayout()
        self.dockWidgetContents.setLayout(self.gridLayout)

        self.dockWidgetContents.layout().setColumnMinimumWidth(0, 36)

        self.userCrsToolButton = QToolButton(self.dockWidgetContents)
        self.userCrsToolButton.setIcon(
            QIcon(":/plugins/coordinate_capture/mIconProjectionEnabled.svg"))
        self.userCrsToolButton.setToolTip(
            self.tr("Click to select the CRS to use for coordinate display"))

        self.userCrsLabel = QLabel(self.dockWidgetContents)
        self.userCrsLabel.setPixmap(
            QPixmap(":/plugins/coordinate_capture/transformed.svg"))
        self.userCrsLabel.setGeometry(self.userCrsToolButton.geometry())

        self.userCrsEdit = QLineEdit(self.dockWidgetContents)
        self.userCrsEdit.setReadOnly(True)
        self.userCrsEdit.setToolTip(
            self.tr("Coordinate in your selected CRS (lat,lon or east,north)"))
        self.copyUserCrsCoordinatesAction = self.userCrsEdit.addAction(
            QIcon(":/plugins/coordinate_capture/mActionEditCopy.svg"),
            QLineEdit.TrailingPosition)
        self.copyUserCrsCoordinatesAction.triggered.connect(
            self.copyUserCrsCoordinates)

        self.canvasCrsEdit = QLineEdit(self.dockWidgetContents)
        self.canvasCrsEdit.setReadOnly(True)
        self.canvasCrsEdit.setToolTip(
            self.
            tr("Coordinate in map canvas coordinate reference system (lat,lon or east,north)"
               ))
        self.copyCanvasCrsCoordinatesAction = self.canvasCrsEdit.addAction(
            QIcon(":/plugins/coordinate_capture/mActionEditCopy.svg"),
            QLineEdit.TrailingPosition)
        self.copyCanvasCrsCoordinatesAction.triggered.connect(
            self.copyCanvasCrsCoordinates)

        self.trackMouseButton = QToolButton(self.dockWidgetContents)
        self.trackMouseButton.setIcon(
            QIcon(":/plugins/coordinate_capture/tracking.svg"))
        self.trackMouseButton.setCheckable(True)
        self.trackMouseButton.setToolTip(
            self.tr(
                "Click to enable mouse tracking. Click the canvas to stop"))
        self.trackMouseButton.setChecked(False)

        # Create the action for tool
        self.captureButton = QPushButton(self.dockWidgetContents)
        self.captureButton.setText(self.tr("Start Capture"))
        self.captureButton.setToolTip(
            self.tr("Click to enable coordinate capture"))
        self.captureButton.setIcon(
            QIcon(":/plugins/coordinate_capture/coordinate_capture.png"))
        self.captureButton.setWhatsThis(
            self.
            tr("Click on the map to view coordinates and capture to clipboard."
               ))

        # // Set the icons
        # setCurrentTheme(QString());

        self.dockWidgetContents.layout().addWidget(self.userCrsToolButton, 0,
                                                   0)
        self.dockWidgetContents.layout().addWidget(self.userCrsEdit, 0, 1)
        self.dockWidgetContents.layout().addWidget(self.userCrsLabel, 1, 0)
        self.dockWidgetContents.layout().addWidget(self.canvasCrsEdit, 1, 1)
        self.dockWidgetContents.layout().addWidget(self.trackMouseButton, 2, 0)
        self.dockWidgetContents.layout().addWidget(self.captureButton, 2, 1)
    def setup_left_panel(self):
        """Setup the UI for left panel.

        Generate all exposure, combobox, and edit button.
        """
        hazard = self.parent.step_kw_subcategory.selected_subcategory()
        left_panel_heading = QLabel(tr('Classifications'))
        left_panel_heading.setFont(big_font)
        self.left_layout.addWidget(left_panel_heading)

        inner_left_layout = QGridLayout()

        row = 0
        for exposure in exposure_all:
            special_case = False
            if not setting('developer_mode'):
                # Filter out unsupported exposure for the hazard
                if exposure in hazard['disabled_exposures']:
                    # Remove from the storage if the exposure is disabled
                    if self.layer_mode == layer_mode_continuous:
                        if exposure['key'] in self.thresholds:
                            self.thresholds.pop(exposure['key'])
                    else:
                        if exposure['key'] in self.value_maps:
                            self.value_maps.pop(exposure['key'])
                    continue
            # Trick for EQ raster for population #3853
            if exposure == exposure_population and hazard == hazard_earthquake:
                if is_raster_layer(self.parent.layer):
                    if self.layer_mode == layer_mode_continuous:
                        self.use_default_thresholds = True
                        special_case = True
                        # Set classification for EQ Raster for Population
                        self.thresholds[exposure_population['key']] = {
                            earthquake_mmi_scale['key']: {
                                'classes': default_classification_thresholds(
                                    earthquake_mmi_scale),
                                'active': True
                            }
                        }

            # Add label
            # Hazard on Exposure Classifications
            label = tr(
                '{hazard_name} on {exposure_name} Classifications').format(
                hazard_name=hazard['name'],
                exposure_name=exposure['name']
            )
            exposure_label = QLabel(label)

            # Add combo box
            exposure_combo_box = QComboBox()
            hazard_classifications = hazard.get('classifications')
            exposure_combo_box.addItem(tr('No classifications'))
            exposure_combo_box.setItemData(
                0, None, Qt.UserRole)

            current_index = 0
            i = 0
            # Iterate through all available hazard classifications
            for hazard_classification in hazard_classifications:
                # Skip if the classification is not for the exposure
                if 'exposures' in hazard_classification:
                    if exposure not in hazard_classification['exposures']:
                        continue
                exposure_combo_box.addItem(hazard_classification['name'])
                exposure_combo_box.setItemData(
                    i + 1, hazard_classification, Qt.UserRole)
                if self.layer_mode == layer_mode_continuous:
                    current_hazard_classifications = self.thresholds.get(
                        exposure['key'])
                else:
                    current_hazard_classifications = self.value_maps.get(
                        exposure['key'])
                if current_hazard_classifications:
                    current_hazard_classification = \
                        current_hazard_classifications.get(
                            hazard_classification['key'])
                    if current_hazard_classification:
                        is_active = current_hazard_classification.get('active')
                        if is_active:
                            current_index = i + 1
                i += 1
            # Set current classification
            exposure_combo_box.setCurrentIndex(current_index)

            # Add edit button
            exposure_edit_button = QPushButton(tr('Edit'))

            # For special case. Raster EQ on Population.
            if special_case:
                mmi_index = exposure_combo_box.findText(
                    earthquake_mmi_scale['name'])
                exposure_combo_box.setCurrentIndex(mmi_index)
                exposure_combo_box.setEnabled(False)
                exposure_edit_button.setEnabled(False)
                tool_tip_message = tr(
                    'InaSAFE use default classification for Raster Earthquake '
                    'hazard on population.')
                exposure_label.setToolTip(tool_tip_message)
                exposure_combo_box.setToolTip(tool_tip_message)
                exposure_edit_button.setToolTip(tool_tip_message)

            else:
                if current_index == 0:
                    # Disable if there is no classification chosen.
                    exposure_edit_button.setEnabled(False)
                exposure_edit_button.clicked.connect(
                    partial(
                        self.edit_button_clicked,
                        edit_button=exposure_edit_button,
                        exposure_combo_box=exposure_combo_box,
                        exposure=exposure))
                exposure_combo_box.currentIndexChanged.connect(
                    partial(
                        self.classifications_combo_box_changed,
                        exposure=exposure,
                        exposure_combo_box=exposure_combo_box,
                        edit_button=exposure_edit_button))

            # Arrange in layout
            inner_left_layout.addWidget(exposure_label, row, 0)
            inner_left_layout.addWidget(exposure_combo_box, row, 1)
            inner_left_layout.addWidget(exposure_edit_button, row, 2)

            # Adding to step's attribute
            self.exposures.append(exposure)
            self.exposure_combo_boxes.append(exposure_combo_box)
            self.exposure_edit_buttons.append(exposure_edit_button)
            self.exposure_labels.append(label)
            if special_case:
                self.special_case_index = len(self.exposures) - 1

            row += 1

        self.left_layout.addLayout(inner_left_layout)
        # To push the inner_left_layout up
        self.left_layout.addStretch(1)
Example #24
0
    def __init__(self, iface, db):
        QWizard.__init__(self)
        self.setupUi(self)
        self.iface = iface
        self._db = db
        self.logger = Logger()
        self.app = AppInterface()

        self.names = self._db.names
        self.help_strings = HelpStrings()

        self._layers = {
            self.names.LC_BOUNDARY_POINT_T: None,
            self.names.LC_SURVEY_POINT_T: None,
            self.names.LC_CONTROL_POINT_T: None
        }

        self.target_layer = None

        # Auxiliary data to set nonlinear next pages
        self.pages = [self.wizardPage1, self.wizardPage2, self.wizardPage3]
        self.dict_pages_ids = {self.pages[idx] : pid for idx, pid in enumerate(self.pageIds())}

        self.mMapLayerComboBox.setFilters(QgsMapLayerProxyModel.PointLayer)

        # Set connections
        self.btn_browse_file.clicked.connect(
            make_file_selector(self.txt_file_path,
                               file_filter=QCoreApplication.translate("WizardTranslations",'CSV File (*.csv *.txt)')))
        self.txt_file_path.textChanged.connect(self.file_path_changed)
        self.crsSelector.crsChanged.connect(self.crs_changed)
        self.crs = ""  # SRS auth id
        self.txt_delimiter.textChanged.connect(self.fill_long_lat_combos)
        self.mMapLayerComboBox.layerChanged.connect(self.import_layer_changed)

        self.known_delimiters = [
            {'name': ';', 'value': ';'},
            {'name': ',', 'value': ','},
            {'name': 'tab', 'value': '\t'},
            {'name': 'space', 'value': ' '},
            {'name': '|', 'value': '|'},
            {'name': '~', 'value': '~'},
            {'name': 'Other', 'value': ''}
        ]
        self.cbo_delimiter.addItems([ item['name'] for item in self.known_delimiters ])
        self.cbo_delimiter.currentTextChanged.connect(self.separator_changed)

        self.restore_settings()

        self.txt_file_path.textChanged.emit(self.txt_file_path.text())

        self.rad_boundary_point.toggled.connect(self.point_option_changed)
        self.rad_control_point.toggled.connect(self.point_option_changed)
        self.rad_csv.toggled.connect(self.adjust_page_2_controls)
        self.point_option_changed() # Initialize it
        self.button(QWizard.FinishButton).clicked.connect(self.finished_dialog)
        self.currentIdChanged.connect(self.current_page_changed)

        self.txt_help_page_2.setHtml(self.help_strings.WIZ_ADD_POINTS_SURVEY_PAGE_2_OPTION_CSV)

        self.wizardPage2.setButtonText(QWizard.FinishButton,
                                       QCoreApplication.translate("WizardTranslations",
                                            "Import"))
        self.txt_help_page_3.setHtml(self.help_strings.WIZ_ADD_POINTS_SURVEY_PAGE_3_OPTION_CSV)
        self.txt_help_page_3.anchorClicked.connect(self.save_template)
        self.button(QWizard.HelpButton).clicked.connect(self.show_help)
        self.rejected.connect(self.close_wizard)

        # Set MessageBar for QWizard
        self.bar = QgsMessageBar()
        self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.setLayout(QGridLayout())
        self.layout().addWidget(self.bar, 0, 0, Qt.AlignTop)
    def clicked_event(self):

        # Get user and role
        super_users = self.settings.value('system_variables/super_users')
        cur_user = self.controller.get_current_user()

        self.list_update = []

        # Get visible layers name from TOC
        result = self.get_layers_name()

        body = create_body(form='"formName":"config"', extras=result)
        json_result = self.controller.get_json('gw_fct_getconfig', body)
        if not json_result:
            return False

        self.dlg_config = ConfigUi()
        load_settings(self.dlg_config)
        self.dlg_config.btn_cancel.clicked.connect(
            partial(close_dialog, self.dlg_config))
        self.dlg_config.btn_accept.clicked.connect(partial(self.update_values))

        page1_layout1 = self.dlg_config.tab_main.findChild(
            QGridLayout, 'page1_layout1')
        page1_layout2 = self.dlg_config.tab_main.findChild(
            QGridLayout, 'page1_layout2')
        page2_layout1 = self.dlg_config.tab_main.findChild(
            QGridLayout, 'page2_layout1')
        page2_layout2 = self.dlg_config.tab_main.findChild(
            QGridLayout, 'page2_layout2')

        admin_layout1 = self.dlg_config.tab_main.findChild(
            QGridLayout, 'admin_layout1')
        admin_layout2 = self.dlg_config.tab_main.findChild(
            QGridLayout, 'admin_layout2')

        man_layout1 = self.dlg_config.tab_main.findChild(
            QGridLayout, 'man_layout1')
        man_layout2 = self.dlg_config.tab_main.findChild(
            QGridLayout, 'man_layout2')

        addfields_layout1 = self.dlg_config.tab_main.findChild(
            QGridLayout, 'addfields_layout1')

        groupBox_1 = QGroupBox("Basic")
        groupBox_2 = QGroupBox("O&&M")
        groupBox_3 = QGroupBox("Inventory")
        groupBox_4 = QGroupBox("Mapzones")
        groupBox_5 = QGroupBox("Edit")
        groupBox_6 = QGroupBox("Epa")
        groupBox_7 = QGroupBox("MasterPlan")
        groupBox_8 = QGroupBox("Other")

        groupBox_9 = QGroupBox("Node")
        groupBox_10 = QGroupBox("Arc")
        groupBox_11 = QGroupBox("Utils")
        groupBox_12 = QGroupBox(f"Connec")
        groupBox_13 = QGroupBox(f"Gully")

        groupBox_14 = QGroupBox("Topology")
        groupBox_15 = QGroupBox("Builder")
        groupBox_16 = QGroupBox("Review")
        groupBox_17 = QGroupBox("Analysis")
        groupBox_18 = QGroupBox("System")

        groupBox_19 = QGroupBox("Fluid type")
        groupBox_20 = QGroupBox("Location type")
        groupBox_21 = QGroupBox("Category type")
        groupBox_22 = QGroupBox("Function type")

        groupBox_23 = QGroupBox("Addfields")

        self.basic_form = QGridLayout()
        self.om_form = QGridLayout()
        self.inventory_form = QGridLayout()
        self.mapzones_form = QGridLayout()
        self.cad_form = QGridLayout()
        self.epa_form = QGridLayout()
        self.masterplan_form = QGridLayout()
        self.other_form = QGridLayout()

        self.node_type_form = QGridLayout()
        self.cat_form = QGridLayout()
        self.utils_form = QGridLayout()
        self.connec_form = QGridLayout()
        self.gully_form = QGridLayout()

        self.topology_form = QGridLayout()
        self.builder_form = QGridLayout()
        self.review_form = QGridLayout()
        self.analysis_form = QGridLayout()
        self.system_form = QGridLayout()

        self.fluid_type_form = QGridLayout()
        self.location_type_form = QGridLayout()
        self.category_type_form = QGridLayout()
        self.function_type_form = QGridLayout()

        self.addfields_form = QGridLayout()

        # Construct form for config and admin
        self.construct_form_param_user(json_result['body']['form']['formTabs'],
                                       0)
        self.construct_form_param_system(
            json_result['body']['form']['formTabs'], 1)

        groupBox_1.setLayout(self.basic_form)
        groupBox_2.setLayout(self.om_form)
        groupBox_3.setLayout(self.inventory_form)
        groupBox_4.setLayout(self.mapzones_form)
        groupBox_5.setLayout(self.cad_form)
        groupBox_6.setLayout(self.epa_form)
        groupBox_7.setLayout(self.masterplan_form)
        groupBox_8.setLayout(self.other_form)

        groupBox_9.setLayout(self.node_type_form)
        groupBox_10.setLayout(self.cat_form)
        groupBox_11.setLayout(self.utils_form)
        groupBox_12.setLayout(self.connec_form)
        groupBox_13.setLayout(self.gully_form)

        groupBox_14.setLayout(self.topology_form)
        groupBox_15.setLayout(self.builder_form)
        groupBox_16.setLayout(self.review_form)
        groupBox_17.setLayout(self.analysis_form)
        groupBox_18.setLayout(self.system_form)

        groupBox_19.setLayout(self.fluid_type_form)
        groupBox_20.setLayout(self.location_type_form)
        groupBox_21.setLayout(self.category_type_form)
        groupBox_22.setLayout(self.function_type_form)

        groupBox_23.setLayout(self.addfields_form)

        page1_layout1.addWidget(groupBox_1)
        page1_layout1.addWidget(groupBox_2)
        page1_layout1.addWidget(groupBox_3)
        page1_layout1.addWidget(groupBox_4)
        page1_layout2.addWidget(groupBox_5)
        page1_layout2.addWidget(groupBox_6)
        page1_layout2.addWidget(groupBox_7)
        page1_layout2.addWidget(groupBox_8)

        page2_layout1.addWidget(groupBox_9)
        page2_layout1.addWidget(groupBox_10)
        page2_layout2.addWidget(groupBox_11)
        page2_layout2.addWidget(groupBox_12)
        page2_layout2.addWidget(groupBox_13)

        admin_layout1.addWidget(groupBox_14)
        admin_layout2.addWidget(groupBox_15)
        admin_layout2.addWidget(groupBox_16)
        admin_layout2.addWidget(groupBox_17)
        admin_layout2.addWidget(groupBox_18)

        man_layout1.addWidget(groupBox_19)
        man_layout2.addWidget(groupBox_20)
        man_layout2.addWidget(groupBox_21)
        man_layout2.addWidget(groupBox_22)

        addfields_layout1.addWidget(groupBox_23)

        verticalSpacer1 = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                      QSizePolicy.Expanding)

        page1_layout1.addItem(verticalSpacer1)
        page1_layout2.addItem(verticalSpacer1)
        page2_layout1.addItem(verticalSpacer1)
        page2_layout2.addItem(verticalSpacer1)
        admin_layout1.addItem(verticalSpacer1)
        admin_layout2.addItem(verticalSpacer1)
        man_layout1.addItem(verticalSpacer1)
        man_layout2.addItem(verticalSpacer1)
        addfields_layout1.addItem(verticalSpacer1)

        # Event on change from combo parent
        self.get_event_combo_parent(json_result['body']['form']['formTabs'])

        # Set signals Combo parent/child
        chk_expl = self.dlg_config.tab_main.findChild(
            QWidget, 'chk_exploitation_vdefault')
        chk_dma = self.dlg_config.tab_main.findChild(QWidget,
                                                     'chk_dma_vdefault')
        if chk_dma and chk_expl:
            chk_dma.stateChanged.connect(
                partial(self.check_child_to_parent, chk_dma, chk_expl))
            chk_expl.stateChanged.connect(
                partial(self.check_parent_to_child, chk_expl, chk_dma))
        hide_void_groupbox(self.dlg_config)
        # Check user/role and remove tabs
        role_admin = self.controller.check_role_user("role_admin", cur_user)
        if not role_admin and cur_user not in super_users:
            qt_tools.remove_tab_by_tabName(self.dlg_config.tab_main,
                                           "tab_admin")

        # Open form
        open_dialog(self.dlg_config, dlg_name='config')
Example #26
0
    def __init__(self, parent=None):
        super(ShellOutputScintilla, self).__init__(parent)
        self.parent = parent
        self.shell = self.parent.shell

        self.settings = QSettings()

        # Creates layout for message bar
        self.layout = QGridLayout(self)
        self.layout.setContentsMargins(0, 0, 0, 0)
        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.layout.addItem(spacerItem, 1, 0, 1, 1)
        # messageBar instance
        self.infoBar = QgsMessageBar()
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.infoBar.setSizePolicy(sizePolicy)
        self.layout.addWidget(self.infoBar, 0, 0, 1, 1)

        # Enable non-ascii chars for editor
        self.setUtf8(True)

        sys.stdout = writeOut(self, sys.stdout)
        sys.stderr = writeOut(self, sys.stderr, "_traceback")

        self.insertInitText()
        self.refreshSettingsOutput()
        self.setReadOnly(True)

        # Set the default font
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.setFont(font)
        self.setMarginsFont(font)
        # Margin 0 is used for line numbers
        self.setMarginWidth(0, 0)
        self.setMarginWidth(1, 0)
        self.setMarginWidth(2, 0)
        #fm = QFontMetrics(font)
        self.setMarginsFont(font)
        self.setMarginWidth(1, "00000")
        self.setMarginLineNumbers(1, True)
        self.setMarginsForegroundColor(QColor("#3E3EE3"))
        self.setMarginsBackgroundColor(QColor("#f9f9f9"))
        self.setCaretLineVisible(True)
        self.setCaretWidth(0)

        self.setMinimumHeight(120)

        self.setWrapMode(QsciScintilla.WrapCharacter)
        self.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0)

        self.runScut = QShortcut(QKeySequence(Qt.CTRL + Qt.Key_E), self)
        self.runScut.setContext(Qt.WidgetShortcut)
        self.runScut.activated.connect(self.enteredSelected)
        # Reimplemeted copy action to prevent paste prompt (>>>,...) in command view
        self.copyShortcut = QShortcut(QKeySequence.Copy, self)
        self.copyShortcut.activated.connect(self.copy)
        self.selectAllShortcut = QShortcut(QKeySequence.SelectAll, self)
        self.selectAllShortcut.activated.connect(self.selectAll)
Example #27
0
    def __init__(self, iface, db, qgis_utils, parent=None):
        QWizard.__init__(self, parent)
        self.setupUi(self)
        self.iface = iface
        self.log = QgsApplication.messageLog()
        self._db = db
        self.qgis_utils = qgis_utils
        self.help_strings = HelpStrings()
        self.insert_features_to_layer = InsertFeaturesToLayer()

        self.target_layer = None

        # Auxiliary data to set nonlinear next pages
        self.pages = [self.wizardPage1, self.wizardPage2, self.wizardPage3]
        self.dict_pages_ids = {
            self.pages[idx]: pid
            for idx, pid in enumerate(self.pageIds())
        }

        # Set connections
        self.btn_browse_file.clicked.connect(
            make_file_selector(self.txt_file_path,
                               file_filter=QCoreApplication.translate(
                                   "CreatePointsCadastreWizard",
                                   'CSV File (*.csv *.txt)')))
        self.txt_file_path.textChanged.connect(self.file_path_changed)
        self.crsSelector.crsChanged.connect(self.crs_changed)
        self.crs = QgsCoordinateReferenceSystem()
        self.txt_delimiter.textChanged.connect(self.fill_long_lat_combos)

        self.known_delimiters = [{
            'name': ';',
            'value': ';'
        }, {
            'name': ',',
            'value': ','
        }, {
            'name': 'tab',
            'value': '\t'
        }, {
            'name': 'space',
            'value': ' '
        }, {
            'name': '|',
            'value': '|'
        }, {
            'name': '~',
            'value': '~'
        }, {
            'name': 'Other',
            'value': ''
        }]
        self.cbo_delimiter.addItems(
            [item['name'] for item in self.known_delimiters])
        self.cbo_delimiter.currentTextChanged.connect(self.separator_changed)

        self.restore_settings()

        self.txt_file_path.textChanged.emit(self.txt_file_path.text())

        self.rad_boundary_point.toggled.connect(self.point_option_changed)
        self.rad_control_point.toggled.connect(self.point_option_changed)
        self.rad_csv.toggled.connect(self.adjust_page_2_controls)
        self.point_option_changed()  # Initialize it
        self.button(QWizard.FinishButton).clicked.connect(self.finished_dialog)
        self.currentIdChanged.connect(self.current_page_changed)

        self.mMapLayerComboBox.setFilters(QgsMapLayerProxyModel.PointLayer)

        self.txt_help_page_2.setHtml(
            self.help_strings.WIZ_ADD_POINTS_CADASTRE_PAGE_2_OPTION_CSV)

        self.wizardPage2.setButtonText(
            QWizard.FinishButton,
            QCoreApplication.translate("CreatePointsCadastreWizard", "Import"))
        self.txt_help_page_3.setHtml(
            self.help_strings.WIZ_ADD_POINTS_CADASTRE_PAGE_3_OPTION_CSV)
        self.txt_help_page_3.anchorClicked.connect(self.save_template)
        self.button(QWizard.HelpButton).clicked.connect(self.show_help)

        # Set MessageBar for QWizard
        self.bar = QgsMessageBar()
        self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.setLayout(QGridLayout())
        self.layout().addWidget(self.bar, 0, 0, Qt.AlignTop)
Example #28
0
    def open_catalog(self, previous_dialog, widget_name, feature_type,
                     child_type):
        """ Main function of catalog """

        # Manage if feature_type is gully and set grate
        if feature_type == 'gully':
            feature_type = 'grate'

        form_name = 'upsert_catalog_' + feature_type + ''
        form = f'"formName":"{form_name}", "tabName":"data", "editable":"TRUE"'
        feature = f'"feature_type":"{child_type}"'
        body = tools_gw.create_body(form, feature)
        json_result = tools_gw.execute_procedure('gw_fct_getcatalog',
                                                 body,
                                                 log_sql=True)
        if json_result is None:
            return

        group_box_1 = QGroupBox("Filter")
        self.filter_form = QGridLayout()

        self.dlg_catalog = GwInfoCatalogUi()
        tools_gw.load_settings(self.dlg_catalog)
        self.dlg_catalog.btn_cancel.clicked.connect(
            partial(tools_gw.close_dialog, self.dlg_catalog))
        self.dlg_catalog.btn_accept.clicked.connect(
            partial(self._fill_geomcat_id, previous_dialog, widget_name))

        main_layout = self.dlg_catalog.widget.findChild(
            QGridLayout, 'main_layout')
        result = json_result['body']['data']
        for field in result['fields']:
            label = QLabel()
            label.setObjectName('lbl_' + field['label'])
            label.setText(field['label'].capitalize())
            widget = None
            if field['widgettype'] == 'combo':
                widget = self._add_combobox(field)
            if field['layoutname'] == 'lyt_data_1':
                self.filter_form.addWidget(label, field['layoutorder'], 0)
                self.filter_form.addWidget(widget, field['layoutorder'], 1)

        group_box_1.setLayout(self.filter_form)
        main_layout.addWidget(group_box_1)
        vertical_spacer1 = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                       QSizePolicy.Expanding)
        main_layout.addItem(vertical_spacer1)

        matcat_id = self.dlg_catalog.findChild(QComboBox, 'matcat_id')

        pnom = None
        dnom = None
        if tools_gw.get_project_type() == 'ws':
            pnom = self.dlg_catalog.findChild(QComboBox, 'pnom')
            dnom = self.dlg_catalog.findChild(QComboBox, 'dnom')
        elif tools_gw.get_project_type() == 'ud':
            pnom = self.dlg_catalog.findChild(QComboBox, 'shape')
            dnom = self.dlg_catalog.findChild(QComboBox, 'geom1')

        id = self.dlg_catalog.findChild(QComboBox, 'id')

        # Call _get_catalog first time
        self._get_catalog(matcat_id, pnom, dnom, id, feature_type, child_type)

        # Set Listeners
        if matcat_id:
            matcat_id.currentIndexChanged.connect(
                partial(self._populate_pn_dn, matcat_id, pnom, dnom,
                        feature_type, child_type))
        if pnom:
            pnom.currentIndexChanged.connect(
                partial(self._get_catalog, matcat_id, pnom, dnom, id,
                        feature_type, child_type))
        if dnom:
            dnom.currentIndexChanged.connect(
                partial(self._get_catalog, matcat_id, pnom, dnom, id,
                        feature_type, child_type))

        # Set shortcut keys
        self.dlg_catalog.key_escape.connect(
            partial(tools_gw.close_dialog, self.dlg_catalog))

        # Open form
        tools_gw.open_dialog(self.dlg_catalog, dlg_name='info_catalog')
Example #29
0
    def testAnchor(self):
        """ test setting anchor point for widget """
        main_frame = QWidget()
        gl = QGridLayout()
        main_frame.setLayout(gl)
        main_frame.setMinimumSize(800, 600)

        anchor_widget = QWidget(main_frame)
        anchor_widget.setMinimumSize(300, 200)
        main_frame.layout().addWidget(anchor_widget, 1, 1)
        gl.setColumnStretch(0, 1)
        gl.setColumnStretch(1, 0)
        gl.setColumnStretch(2, 1)
        gl.setRowStretch(0, 1)
        gl.setRowStretch(1, 0)
        gl.setRowStretch(2, 1)

        # 103 = WA_DontShowOnScreen (not available in PyQt)
        main_frame.setAttribute(103)
        main_frame.show()

        fw = qgis.gui.QgsFloatingWidget(main_frame)
        fw.setMinimumSize(100, 50)
        fw.setAnchorWidget(anchor_widget)

        tests = [{
            'anchorPoint': QgsFloatingWidget.TopLeft,
            'widgetAnchorPoint': QgsFloatingWidget.TopLeft,
            'x': 250,
            'y': 200
        }, {
            'anchorPoint': QgsFloatingWidget.TopMiddle,
            'widgetAnchorPoint': QgsFloatingWidget.TopLeft,
            'x': 200,
            'y': 200
        }, {
            'anchorPoint': QgsFloatingWidget.TopRight,
            'widgetAnchorPoint': QgsFloatingWidget.TopLeft,
            'x': 150,
            'y': 200
        }, {
            'anchorPoint': QgsFloatingWidget.MiddleLeft,
            'widgetAnchorPoint': QgsFloatingWidget.TopLeft,
            'x': 250,
            'y': 175
        }, {
            'anchorPoint': QgsFloatingWidget.Middle,
            'widgetAnchorPoint': QgsFloatingWidget.TopLeft,
            'x': 200,
            'y': 175
        }, {
            'anchorPoint': QgsFloatingWidget.MiddleRight,
            'widgetAnchorPoint': QgsFloatingWidget.TopLeft,
            'x': 150,
            'y': 175
        }, {
            'anchorPoint': QgsFloatingWidget.BottomLeft,
            'widgetAnchorPoint': QgsFloatingWidget.TopLeft,
            'x': 250,
            'y': 150
        }, {
            'anchorPoint': QgsFloatingWidget.BottomMiddle,
            'widgetAnchorPoint': QgsFloatingWidget.TopLeft,
            'x': 200,
            'y': 150
        }, {
            'anchorPoint': QgsFloatingWidget.BottomRight,
            'widgetAnchorPoint': QgsFloatingWidget.TopLeft,
            'x': 150,
            'y': 150
        }, {
            'anchorPoint': QgsFloatingWidget.TopLeft,
            'widgetAnchorPoint': QgsFloatingWidget.TopMiddle,
            'x': 400,
            'y': 200
        }, {
            'anchorPoint': QgsFloatingWidget.TopLeft,
            'widgetAnchorPoint': QgsFloatingWidget.TopRight,
            'x': 550,
            'y': 200
        }, {
            'anchorPoint': QgsFloatingWidget.TopLeft,
            'widgetAnchorPoint': QgsFloatingWidget.MiddleLeft,
            'x': 250,
            'y': 300
        }, {
            'anchorPoint': QgsFloatingWidget.TopLeft,
            'widgetAnchorPoint': QgsFloatingWidget.Middle,
            'x': 400,
            'y': 300
        }, {
            'anchorPoint': QgsFloatingWidget.TopLeft,
            'widgetAnchorPoint': QgsFloatingWidget.MiddleRight,
            'x': 550,
            'y': 300
        }, {
            'anchorPoint': QgsFloatingWidget.TopLeft,
            'widgetAnchorPoint': QgsFloatingWidget.BottomLeft,
            'x': 250,
            'y': 400
        }, {
            'anchorPoint': QgsFloatingWidget.TopLeft,
            'widgetAnchorPoint': QgsFloatingWidget.BottomMiddle,
            'x': 400,
            'y': 400
        }, {
            'anchorPoint': QgsFloatingWidget.TopLeft,
            'widgetAnchorPoint': QgsFloatingWidget.BottomRight,
            'x': 550,
            'y': 400
        }]

        for t in tests:
            fw.setAnchorPoint(t['anchorPoint'])
            fw.setAnchorWidgetPoint(t['widgetAnchorPoint'])
            self.assertEqual(fw.pos().x(), t['x'])
            self.assertEqual(fw.pos().y(), t['y'])
Example #30
0
    def __init__(self, iface, base_config, parent=None):

        QDialog.__init__(self, parent)
        self.iface = iface
        self.setupUi(self)
        QgsGui.instance().enableAutoGeometryRestore(self)
        self.db_simple_factory = DbSimpleFactory()
        self.buttonBox.accepted.disconnect()
        self.buttonBox.clear()
        self.buttonBox.addButton(QDialogButtonBox.Cancel)
        self.buttonBox.addButton(QDialogButtonBox.Help)
        self.buttonBox.helpRequested.connect(self.help_requested)

        self.import_text = self.tr('Import Data')
        self.set_button_to_import_action = QAction(self.import_text, None)
        self.set_button_to_import_action.triggered.connect(
            self.set_button_to_import)

        self.import_without_validation_text = self.tr(
            'Import without validation')
        self.set_button_to_import_without_validation_action = QAction(
            self.import_without_validation_text, None)
        self.set_button_to_import_without_validation_action.triggered.connect(
            self.set_button_to_import_without_validation)

        self.edit_command_action = QAction(self.tr('Edit ili2db command'),
                                           None)
        self.edit_command_action.triggered.connect(self.edit_command)

        self.import_tool_button.addAction(
            self.set_button_to_import_without_validation_action)
        self.import_tool_button.addAction(self.edit_command_action)
        self.import_tool_button.setText(self.import_text)
        self.import_tool_button.clicked.connect(self.accepted)

        self.xtf_file_browse_button.clicked.connect(
            make_file_selector(
                self.xtf_file_line_edit,
                title=self.tr('Open Transfer or Catalog File'),
                file_filter=self.
                tr('Transfer File (*.xtf *.itf *.XTF *.ITF);;Catalogue File (*.xml *.XML *.xls *.XLS *.xlsx *.XLSX)'
                   )))

        self.type_combo_box.clear()
        self._lst_panel = dict()

        for db_id in self.db_simple_factory.get_db_list(False):
            self.type_combo_box.addItem(displayDbIliMode[db_id], db_id)
            db_factory = self.db_simple_factory.create_factory(db_id)
            item_panel = db_factory.get_config_panel(self,
                                                     DbActionType.IMPORT_DATA)
            self._lst_panel[db_id] = item_panel
            self.db_layout.addWidget(item_panel)

        self.type_combo_box.currentIndexChanged.connect(self.type_changed)
        self.ili2db_options = Ili2dbOptionsDialog()
        self.ili2db_options_button.clicked.connect(self.ili2db_options.open)
        self.ili2db_options.finished.connect(self.fill_toml_file_info_label)

        self.multiple_models_dialog = MultipleModelsDialog(self)
        self.multiple_models_button.clicked.connect(
            self.multiple_models_dialog.open)
        self.multiple_models_dialog.accepted.connect(
            self.fill_models_line_edit)

        self.validate_data = True  # validates imported data by default, We use --disableValidation when is False
        self.base_configuration = base_config
        self.restore_configuration()

        self.validators = Validators()
        fileValidator = FileValidator(
            pattern=['*.' + ext for ext in self.ValidExtensions])

        self.xtf_file_line_edit.setValidator(fileValidator)

        self.ili_models_line_edit.setPlaceholderText(
            self.tr('[Search model in repository]'))
        self.ili_models_line_edit.textChanged.connect(
            self.complete_models_completer)
        self.ili_models_line_edit.punched.connect(
            self.complete_models_completer)

        self.xtf_file_line_edit.textChanged.connect(
            self.validators.validate_line_edits)
        self.xtf_file_line_edit.textChanged.emit(
            self.xtf_file_line_edit.text())

        # Reset to import as default text
        self.xtf_file_line_edit.textChanged.connect(self.set_button_to_import)

        settings = QSettings()
        ilifile = settings.value('QgisModelBaker/ili2db/ilifile')
        self.ilicache = IliCache(base_config, ilifile or None)
        self.update_models_completer()
        self.ilicache.refresh()

        self.bar = QgsMessageBar()
        self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.txtStdout.setLayout(QGridLayout())
        self.txtStdout.layout().setContentsMargins(0, 0, 0, 0)
        self.txtStdout.layout().addWidget(self.bar, 0, 0, Qt.AlignTop)