Exemplo n.º 1
0
    def _add_simple_query_item(self,
                               field_name: str,
                               operator: str = '=',
                               value=None):
        """
        Adds a simple query item
        """
        combo = QComboBox()
        combo.addItem('=')
        combo.addItem('<')
        combo.addItem('<=')
        combo.addItem('>')
        combo.addItem('>=')
        combo.addItem('<>')
        combo.setCurrentIndex(combo.findText(operator))

        button = QToolButton()
        button.setIcon(GuiUtils.get_icon('remove.svg'))
        button.setAutoRaise(True)

        filter_item = QTreeWidgetItem()
        filter_item.setText(0, field_name)
        filter_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable
                             | Qt.ItemIsEditable)
        filter_item.setText(2, value)
        self.simple_query_list.addTopLevelItem(filter_item)
        self.simple_query_list.setItemWidget(filter_item, 1, combo)
        self.simple_query_list.setItemWidget(filter_item, 3, button)

        button.clicked.connect(partial(self._remove_simple_item, filter_item))
Exemplo n.º 2
0
    def show_task_steps(self):
        self.trw_task_steps.clear()
        steps = self._task.get_steps()
        self.logger.debug(
            __name__,
            "Showing task steps in Task Panel. {} task steps found: {}.".
            format(len(steps), ", ".join([s.get_name() for s in steps])))

        for i, step in enumerate(steps):
            children = []
            step_item = QTreeWidgetItem([
                QCoreApplication.translate("TaskPanelWidget",
                                           "Step {}").format(i + 1)
            ])
            step_item.setData(0, Qt.BackgroundRole, QBrush(GRAY_COLOR))
            step_item.setToolTip(0, step.get_name())
            step_item.setCheckState(
                0, Qt.Checked if step.get_status() else Qt.Unchecked)

            action_item = QTreeWidgetItem([step.get_name()])
            action_item.setData(0, Qt.UserRole, step.get_id())
            action_item.setIcon(
                0, QIcon(":/Asistente-LADM-COL/resources/images/process.svg"))
            action_item.setToolTip(0, step.get_description())
            step_item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
            children.append(action_item)

            step_item.addChildren(children)
            self.trw_task_steps.addTopLevelItem(step_item)

        for i in range(self.trw_task_steps.topLevelItemCount()):
            self.trw_task_steps.topLevelItem(
                i).setFlags(Qt.ItemIsEnabled | Qt.ItemIsUserCheckable
                            | Qt.ItemIsSelectable)
            self.trw_task_steps.topLevelItem(i).setExpanded(True)
Exemplo n.º 3
0
    def __init__(self):
        super(ScriptSelector, self).__init__(None)
        self.setupUi(self)

        self.scripts = None

        allScripts = defaultdict(list)
        alglist = algList.getProviderFromName("script").algs
        for script in alglist:
            allScripts[script.group].append(script)

        for group, groupScripts in list(allScripts.items()):
            groupItem = QTreeWidgetItem()
            groupItem.setText(0, group)
            groupItem.setFlags(groupItem.flags() | Qt.ItemIsTristate)
            for script in groupScripts:
                scriptItem = QTreeWidgetItem()
                scriptItem.setFlags(scriptItem.flags() | Qt.ItemIsUserCheckable)
                scriptItem.setCheckState(0, Qt.Checked)
                scriptItem.script = script
                scriptItem.setText(0, script.name)
                groupItem.addChild(scriptItem)
            self.scriptsTree.addTopLevelItem(groupItem)

        self.scriptsTree.expandAll()

        self.selectAllLabel.linkActivated.connect(lambda: self.checkScripts(True))
        self.unselectAllLabel.linkActivated.connect(lambda: self.checkScripts(False))

        self.folderButton.clicked.connect(self.selectFolder)

        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)
Exemplo n.º 4
0
    def __init__(self):
        super(ScriptSelector, self).__init__(None)
        self.setupUi(self)

        self.scripts = None

        allScripts = defaultdict(list)
        alglist = QgsApplication.processingRegistry().providerById("script").algorithms()
        for script in alglist:
            allScripts[script.group()].append(script)

        for group, groupScripts in list(allScripts.items()):
            groupItem = QTreeWidgetItem()
            groupItem.setText(0, group)
            groupItem.setFlags(groupItem.flags() | Qt.ItemIsTristate)
            for script in groupScripts:
                scriptItem = QTreeWidgetItem()
                scriptItem.setFlags(scriptItem.flags() | Qt.ItemIsUserCheckable)
                scriptItem.setCheckState(0, Qt.Checked)
                scriptItem.script = script
                scriptItem.setText(0, script.name())
                groupItem.addChild(scriptItem)
            self.scriptsTree.addTopLevelItem(groupItem)

        self.scriptsTree.expandAll()

        self.selectAllLabel.linkActivated.connect(lambda: self.checkScripts(True))
        self.deselectAllLabel.linkActivated.connect(lambda: self.checkScripts(False))

        self.folderButton.clicked.connect(self.selectFolder)

        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)
class QNGWItem(QTreeWidgetItem):
    def __init__(self):
        QTreeWidgetItem.__init__(self)

        self.locked_item = QTreeWidgetItem(["loading..."])
        self.locked_item.setFlags(Qt.NoItemFlags)
        self.locked_item.setDisabled(True)

        self.release()

    def lock(self):
        self.__isLock = True
        self.setFlags(Qt.NoItemFlags)

        self.addChild(self.locked_item)

    def is_locked(self):
        return self.__isLock

    def release(self):
        self.__isLock = False
        self.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)

        self.removeChild(self.locked_item)

    def ngw_resource_children_count(self):
        raise NotImplementedError()
Exemplo n.º 6
0
    def _populate_reporting_tab(self):
        """Populate trees about layers."""
        self.tree.clear()
        self.add_layer.setEnabled(False)
        self.remove_layer.setEnabled(False)
        self.move_up.setEnabled(False)
        self.move_down.setEnabled(False)
        self.tree.setColumnCount(1)
        self.tree.setRootIsDecorated(False)
        self.tree.setHeaderHidden(True)

        analysis_branch = QTreeWidgetItem(self.tree.invisibleRootItem(),
                                          [FROM_ANALYSIS['name']])
        analysis_branch.setFont(0, bold_font)
        analysis_branch.setExpanded(True)
        analysis_branch.setFlags(Qt.ItemIsEnabled)

        if self._multi_exposure_if:
            expected = self._multi_exposure_if.output_layers_expected()
            for group, layers in list(expected.items()):
                group_branch = QTreeWidgetItem(analysis_branch, [group])
                group_branch.setFont(0, bold_font)
                group_branch.setExpanded(True)
                group_branch.setFlags(Qt.ItemIsEnabled)

                for layer in layers:
                    layer = definition(layer)
                    if layer.get('allowed_geometries', None):
                        item = QTreeWidgetItem(group_branch,
                                               [layer.get('name')])
                        item.setData(0, LAYER_ORIGIN_ROLE,
                                     FROM_ANALYSIS['key'])
                        item.setData(0, LAYER_PARENT_ANALYSIS_ROLE, group)
                        item.setData(0, LAYER_PURPOSE_KEY_OR_ID_ROLE,
                                     layer['key'])
                        item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)

        canvas_branch = QTreeWidgetItem(self.tree.invisibleRootItem(),
                                        [FROM_CANVAS['name']])
        canvas_branch.setFont(0, bold_font)
        canvas_branch.setExpanded(True)
        canvas_branch.setFlags(Qt.ItemIsEnabled)

        # List layers from the canvas
        loaded_layers = list(QgsProject.instance().mapLayers().values())
        canvas_layers = self.iface.mapCanvas().layers()
        flag = setting('visibleLayersOnlyFlag', expected_type=bool)
        for loaded_layer in loaded_layers:
            if flag and loaded_layer not in canvas_layers:
                continue

            title = loaded_layer.name()
            item = QTreeWidgetItem(canvas_branch, [title])
            item.setData(0, LAYER_ORIGIN_ROLE, FROM_CANVAS['key'])
            item.setData(0, LAYER_PURPOSE_KEY_OR_ID_ROLE, loaded_layer.id())
            item.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)

        self.tree.resizeColumnToContents(0)
Exemplo n.º 7
0
    def populate_classified_values(
            self, unassigned_values, assigned_values, default_classes):
        """Populate lstUniqueValues and treeClasses.from the parameters.

        :param unassigned_values: List of values that haven't been assigned
            to a class. It will be put in self.lstUniqueValues.
        :type unassigned_values: list

        :param assigned_values: Dictionary with class as the key and list of
            value as the value of the dictionary. It will be put in
            self.treeClasses.
        :type assigned_values: dict

        :param default_classes: Default classes from unit.
        :type default_classes: list
        """
        # Populate the unique values list
        self.lstUniqueValues.clear()
        self.lstUniqueValues.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        for value in unassigned_values:
            value_as_string = value is not None and str(value) or 'NULL'
            list_item = QListWidgetItem(self.lstUniqueValues)
            list_item.setFlags(
                Qt.ItemIsEnabled
                | Qt.ItemIsSelectable
                | Qt.ItemIsDragEnabled)
            list_item.setData(Qt.UserRole, value)
            list_item.setText(value_as_string)
            self.lstUniqueValues.addItem(list_item)
        # Populate assigned values tree
        self.treeClasses.clear()
        self.treeClasses.invisibleRootItem().setFlags(Qt.ItemIsEnabled)
        for default_class in default_classes:
            # Create branch for class
            tree_branch = QTreeWidgetItem(self.treeClasses)
            tree_branch.setFlags(Qt.ItemIsDropEnabled | Qt.ItemIsEnabled)
            tree_branch.setExpanded(True)
            tree_branch.setFont(0, bold_font)
            if 'name' in default_class:
                default_class_name = default_class['name']
            else:
                default_class_name = default_class['key']
            tree_branch.setText(0, default_class_name)
            tree_branch.setData(0, Qt.UserRole, default_class['key'])
            if 'description' in default_class:
                tree_branch.setToolTip(0, default_class['description'])
            # Assign known values
            for value in assigned_values[default_class['key']]:
                string_value = value is not None and str(value) or 'NULL'
                tree_leaf = QTreeWidgetItem(tree_branch)
                tree_leaf.setFlags(
                    Qt.ItemIsEnabled
                    | Qt.ItemIsSelectable
                    | Qt.ItemIsDragEnabled)
                tree_leaf.setData(0, Qt.UserRole, value)
                tree_leaf.setText(0, string_value)
Exemplo n.º 8
0
 def createItem(itemRoot, name, class_id, flags, icon):
     # WidgetItem
     item = QTreeWidgetItem( itemRoot )
     item.setText(0, name )
     item.setData(0, Qt.UserRole, class_id )
     checkState = Qt.Checked if class_id in self.l_class_id else Qt.Unchecked
     item.setCheckState(0, checkState )
     item.setFlags( flags )
     item.setIcon(0, icon )
     return item
Exemplo n.º 9
0
 def fillInputsTree(self):
     icon = QIcon(os.path.join(pluginPath, 'images', 'input.png'))
     parametersItem = QTreeWidgetItem()
     parametersItem.setText(0, self.tr('Parameters'))
     for paramType in ModelerParameterDefinitionDialog.paramTypes:
         paramItem = QTreeWidgetItem()
         paramItem.setText(0, paramType)
         paramItem.setIcon(0, icon)
         paramItem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled)
         parametersItem.addChild(paramItem)
     self.inputsTree.addTopLevelItem(parametersItem)
     parametersItem.setExpanded(True)
Exemplo n.º 10
0
 def fillInputsTree(self):
     icon = QIcon(os.path.join(pluginPath, 'images', 'input.svg'))
     parametersItem = QTreeWidgetItem()
     parametersItem.setText(0, self.tr('Parameters'))
     for paramType in ModelerParameterDefinitionDialog.paramTypes:
         paramItem = QTreeWidgetItem()
         paramItem.setText(0, paramType)
         paramItem.setIcon(0, icon)
         paramItem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled)
         parametersItem.addChild(paramItem)
     self.inputsTree.addTopLevelItem(parametersItem)
     parametersItem.setExpanded(True)
Exemplo n.º 11
0
 def fillInputsTree(self):
     icon = QIcon(os.path.join(pluginPath, 'images', 'input.svg'))
     parametersItem = QTreeWidgetItem()
     parametersItem.setText(0, self.tr('Parameters'))
     sortedParams = sorted(QgsApplication.instance().processingRegistry().parameterTypes(), key=lambda pt: pt.name())
     for param in sortedParams:
         if param.flags() & QgsProcessingParameterType.ExposeToModeler:
             paramItem = QTreeWidgetItem()
             paramItem.setText(0, param.name())
             paramItem.setData(0, Qt.UserRole, param.id())
             paramItem.setIcon(0, icon)
             paramItem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled)
             paramItem.setToolTip(0, param.description())
             parametersItem.addChild(paramItem)
     self.inputsTree.addTopLevelItem(parametersItem)
     parametersItem.setExpanded(True)
Exemplo n.º 12
0
 def fillInputsTree(self):
     icon = QIcon(os.path.join(pluginPath, 'images', 'input.svg'))
     parametersItem = QTreeWidgetItem()
     parametersItem.setText(0, self.tr('Parameters'))
     sortedParams = sorted(QgsApplication.instance().processingRegistry().parameterTypes(), key=lambda pt: pt.name())
     for param in sortedParams:
         if param.flags() & QgsProcessingParameterType.ExposeToModeler:
             paramItem = QTreeWidgetItem()
             paramItem.setText(0, param.name())
             paramItem.setData(0, Qt.UserRole, param.id())
             paramItem.setIcon(0, icon)
             paramItem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled)
             paramItem.setToolTip(0, param.description())
             parametersItem.addChild(paramItem)
     self.inputsTree.addTopLevelItem(parametersItem)
     parametersItem.setExpanded(True)
        def create_layers_tree(layer_node):
            """Builds layers tree widget"""
            widget = QTreeWidgetItem()
            widget.setText(0, layer_node.get('title', layer_node['name']))
            if 'layers' in layer_node:
                for child_node in layer_node['layers']:
                    widget.addChild(create_layers_tree(child_node))
            else:
                widget.setData(0, Qt.UserRole, layer_node)

            widget.setFlags(Qt.ItemIsEnabled
                            | Qt.ItemIsSelectable
                            | Qt.ItemIsUserCheckable
                            | Qt.ItemIsTristate)
            widget.setCheckState(0, Qt.Checked)
            widget.setDisabled(layer_node.get('hidden', False))
            return widget
Exemplo n.º 14
0
    def fillInputsTree(self):
        from processing.core.Processing import Processing

        icon = QIcon(os.path.join(pluginPath, 'images', 'input.svg'))
        parametersItem = QTreeWidgetItem()
        parametersItem.setText(0, self.tr('Parameters'))
        sortedParams = sorted(Processing.registeredParameters().items())
        for param in sortedParams:
            if param[1]['exposeToModeller']:
                paramItem = QTreeWidgetItem()
                paramItem.setText(0, param[1]['name'])
                paramItem.setData(0, Qt.UserRole, param[0])
                paramItem.setIcon(0, icon)
                paramItem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled)
                paramItem.setToolTip(0, param[1]['description'])
                parametersItem.addChild(paramItem)
        self.inputsTree.addTopLevelItem(parametersItem)
        parametersItem.setExpanded(True)
Exemplo n.º 15
0
    def fillInputsTree(self):
        from processing.core.Processing import Processing

        icon = QIcon(os.path.join(pluginPath, 'images', 'input.svg'))
        parametersItem = QTreeWidgetItem()
        parametersItem.setText(0, self.tr('Parameters'))
        sortedParams = sorted(Processing.registeredParameters().items())
        for param in sortedParams:
            if param[1]['exposeToModeller']:
                paramItem = QTreeWidgetItem()
                paramItem.setText(0, param[1]['name'])
                paramItem.setData(0, Qt.UserRole, param[0])
                paramItem.setIcon(0, icon)
                paramItem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable
                                   | Qt.ItemIsDragEnabled)
                paramItem.setToolTip(0, param[1]['description'])
                parametersItem.addChild(paramItem)
        self.inputsTree.addTopLevelItem(parametersItem)
        parametersItem.setExpanded(True)
Exemplo n.º 16
0
    def set_items(self, data=None):
        """" Build the tree afresh with no selections """
        self.tree_products.clear()

        data = data if data else {}
        self._data = json.loads(data) if isinstance(data, str) else data

        for product, measurements in self._data.items():
            parent = QTreeWidgetItem(self.tree_products)
            parent.setText(0, product)
            # noinspection PyTypeChecker
            parent.setFlags(parent.flags() | Qt.ItemIsTristate
                            | Qt.ItemIsUserCheckable)

            for measurement in measurements:
                child = QTreeWidgetItem(parent)
                # noinspection PyTypeChecker
                child.setFlags(child.flags() | Qt.ItemIsUserCheckable)
                child.setText(0, measurement)
                child.setCheckState(0, Qt.Unchecked)
Exemplo n.º 17
0
    def __init__(self):
        super(TestSelector, self).__init__()
        self.setupUi(self)

        self.tests = None

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

        allTests = defaultdict(list)
        for test in tests.tests:
            allTests[test.group].append(test)

        for group, groupTests in iteritems(allTests):
            groupItem = QTreeWidgetItem()
            groupItem.setText(0, group)
            groupItem.setFlags(groupItem.flags() | Qt.ItemIsTristate)
            unitItem = QTreeWidgetItem()
            unitItem.setText(0, "Fully automated tests")
            unitItem.setFlags(unitItem.flags() | Qt.ItemIsTristate)
            manualItem = QTreeWidgetItem()
            manualItem.setText(0, "Manual and semi-automated tests")
            manualItem.setFlags(manualItem.flags() | Qt.ItemIsTristate)
            unitTestsByCategories = defaultdict(list)
            manualTestsByCategories = defaultdict(list)
            for test in groupTests:
                if isinstance(test, UnitTestWrapper):
                    unitTestsByCategories[test.category].append(test)
                else:
                    manualTestsByCategories[test.category].append(test)
            for testsList, parentItem in [(unitTestsByCategories, unitItem),
                                          (manualTestsByCategories, manualItem)
                                          ]:
                for cat, catTests in iteritems(testsList):
                    categoryItem = QTreeWidgetItem()
                    categoryItem.setText(0, cat)
                    categoryItem.setFlags(manualItem.flags()
                                          | Qt.ItemIsTristate)
                    for test in catTests:
                        testItem = QTreeWidgetItem()
                        testItem.setFlags(testItem.flags()
                                          | Qt.ItemIsUserCheckable)
                        testItem.setCheckState(0, Qt.Unchecked)
                        testItem.test = test
                        testItem.setText(0, test.name)
                        categoryItem.addChild(testItem)
                    parentItem.addChild(categoryItem)
            if manualItem.childCount():
                groupItem.addChild(manualItem)
            if unitItem.childCount():
                groupItem.addChild(unitItem)
            self.testsTree.addTopLevelItem(groupItem)
            groupItem.setExpanded(True)

        self.buttonBox.button(
            QDialogButtonBox.Ok).setText("Run selected tests")
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)

        self.selectAllLabel.linkActivated.connect(
            lambda: self.checkTests(lambda t: Qt.Checked))
        self.unselectAllLabel.linkActivated.connect(
            lambda: self.checkTests(lambda t: Qt.Unchecked))

        def _onlyManual(t):
            if isinstance(t, UnitTestWrapper):
                return Qt.Unchecked
            else:
                return Qt.Checked

        self.onlyManualLabel.linkActivated.connect(
            lambda: self.checkTests(_onlyManual))

        def _onlyUnit(t):
            if isinstance(t, UnitTestWrapper):
                return Qt.Checked
            else:
                return Qt.Unchecked

        self.onlyUnitLabel.linkActivated.connect(
            lambda: self.checkTests(_onlyUnit))

        self.exportButton.clicked.connect(self.export)
Exemplo n.º 18
0
    def __init__(self):
        super(TestSelector, self).__init__()
        self.setupUi(self)

        self.tests = None

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

        allTests = defaultdict(list)
        for test in tests.tests:
            allTests[test.group].append(test)

        for group, groupTests in iteritems(allTests):
            groupItem = QTreeWidgetItem()
            groupItem.setText(0, group)
            groupItem.setFlags(groupItem.flags() | Qt.ItemIsTristate)
            unitItem = QTreeWidgetItem()
            unitItem.setText(0, "Fully automated tests")
            unitItem.setFlags(unitItem.flags() | Qt.ItemIsTristate)
            manualItem = QTreeWidgetItem()
            manualItem.setText(0, "Manual and semi-automated tests")
            manualItem.setFlags(manualItem.flags() | Qt.ItemIsTristate)
            for test in groupTests:
                testItem = QTreeWidgetItem()
                testItem.setFlags(testItem.flags() | Qt.ItemIsUserCheckable)
                testItem.setCheckState(0, Qt.Unchecked)
                testItem.test = test
                testItem.setText(0, test.name)
                if isinstance(test, UnitTestWrapper):
                    unitItem.addChild(testItem)
                else:
                    manualItem.addChild(testItem)
            if manualItem.childCount():
                groupItem.addChild(manualItem)
            if unitItem.childCount():
                groupItem.addChild(unitItem)
            self.testsTree.addTopLevelItem(groupItem)
            groupItem.setExpanded(True)

        self.buttonBox.button(QDialogButtonBox.Ok).setText("Run selected tests")
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)

        self.selectAllLabel.linkActivated.connect(lambda: self.checkTests(lambda t: Qt.Checked))
        self.unselectAllLabel.linkActivated.connect(lambda: self.checkTests(lambda t: Qt.Unchecked))

        def _onlyManual(t):
            if isinstance(t, UnitTestWrapper):
                return Qt.Unchecked
            else:
                return Qt.Checked

        self.onlyManualLabel.linkActivated.connect(lambda: self.checkTests(_onlyManual))

        def _onlyUnit(t):
            if isinstance(t, UnitTestWrapper):
                return Qt.Checked
            else:
                return Qt.Unchecked

        self.onlyUnitLabel.linkActivated.connect(lambda: self.checkTests(_onlyUnit))

        self.exportButton.clicked.connect(self.export)
Exemplo n.º 19
0
    def fillAlgorithmTreeUsingProviders(self):
        self.algorithmTree.clear()
        text = str(self.searchBox.text())
        search_strings = text.split(' ')
        qgis_groups = {}
        for provider in QgsApplication.processingRegistry().providers():
            if not provider.isActive():
                continue
            groups = {}

            # Add algorithms
            for alg in provider.algorithms():
                if alg.flags() & QgsProcessingAlgorithm.FlagHideFromModeler:
                    continue
                if alg.id() == self.model.id():
                    continue

                item_text = [alg.displayName().lower()]
                item_text.extend(alg.tags())

                show = not search_strings or all(
                    any(part in t for t in item_text)
                    for part in search_strings)

                if show:
                    if alg.group() in groups:
                        groupItem = groups[alg.group()]
                    elif provider.id() in ('qgis', 'native') and alg.group() in qgis_groups:
                        groupItem = qgis_groups[alg.group()]
                    else:
                        groupItem = QTreeWidgetItem()
                        name = alg.group()
                        groupItem.setText(0, name)
                        groupItem.setToolTip(0, name)
                        groupItem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                        if provider.id() in ('qgis', 'native'):
                            groupItem.setIcon(0, provider.icon())
                            qgis_groups[alg.group()] = groupItem
                        else:
                            groups[alg.group()] = groupItem
                    algItem = TreeAlgorithmItem(alg)
                    groupItem.addChild(algItem)

            if len(groups) > 0:
                providerItem = QTreeWidgetItem()
                providerItem.setText(0, provider.name())
                providerItem.setToolTip(0, provider.name())
                providerItem.setIcon(0, provider.icon())
                providerItem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                for groupItem in list(groups.values()):
                    providerItem.addChild(groupItem)
                self.algorithmTree.addTopLevelItem(providerItem)
                providerItem.setExpanded(text != '')
                for groupItem in list(groups.values()):
                    if text != '':
                        groupItem.setExpanded(True)

        if len(qgis_groups) > 0:
            for groupItem in list(qgis_groups.values()):
                self.algorithmTree.addTopLevelItem(groupItem)
            for groupItem in list(qgis_groups.values()):
                if text != '':
                    groupItem.setExpanded(True)

        self.algorithmTree.sortItems(0, Qt.AscendingOrder)
    def populate_classified_values(
            unassigned_values, assigned_values, default_classes,
            list_unique_values, tree_mapping_widget):
        """Populate lstUniqueValues and treeClasses.from the parameters.

        :param unassigned_values: List of values that haven't been assigned
            to a class. It will be put in list_unique_values.
        :type unassigned_values: list

        :param assigned_values: Dictionary with class as the key and list of
            value as the value of the dictionary. It will be put in
            tree_mapping_widget.
        :type assigned_values: dict

        :param default_classes: Default classes from unit.
        :type default_classes: list

        :param list_unique_values: List Widget for unique values
        :type list_unique_values: QListWidget

        :param tree_mapping_widget: Tree Widget for classifying.
        :type tree_mapping_widget: QTreeWidget
        """
        # Populate the unique values list
        list_unique_values.clear()
        list_unique_values.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        for value in unassigned_values:
            value_as_string = value is not None and str(value) or 'NULL'
            list_item = QListWidgetItem(list_unique_values)
            list_item.setFlags(
                Qt.ItemIsEnabled
                | Qt.ItemIsSelectable
                | Qt.ItemIsDragEnabled)
            list_item.setData(Qt.UserRole, value)
            list_item.setText(value_as_string)
            list_unique_values.addItem(list_item)
        # Populate assigned values tree
        tree_mapping_widget.clear()
        bold_font = QFont()
        bold_font.setItalic(True)
        bold_font.setBold(True)
        bold_font.setWeight(75)
        tree_mapping_widget.invisibleRootItem().setFlags(
            Qt.ItemIsEnabled)
        for default_class in default_classes:
            # Create branch for class
            tree_branch = QTreeWidgetItem(tree_mapping_widget)
            tree_branch.setFlags(
                Qt.ItemIsDropEnabled | Qt.ItemIsEnabled)
            tree_branch.setExpanded(True)
            tree_branch.setFont(0, bold_font)
            if 'name' in default_class:
                default_class_name = default_class['name']
            else:
                default_class_name = default_class['key']
            tree_branch.setText(0, default_class_name)
            tree_branch.setData(0, Qt.UserRole, default_class['key'])
            if 'description' in default_class:
                tree_branch.setToolTip(0, default_class['description'])
            # Assign known values
            for value in assigned_values[default_class['key']]:
                string_value = value is not None and str(value) or 'NULL'
                tree_leaf = QTreeWidgetItem(tree_branch)
                tree_leaf.setFlags(
                    Qt.ItemIsEnabled
                    | Qt.ItemIsSelectable
                    | Qt.ItemIsDragEnabled)
                tree_leaf.setData(0, Qt.UserRole, value)
                tree_leaf.setText(0, string_value)
Exemplo n.º 21
0
    def update_available_layers(self):
        self.trw_layers.setUpdatesEnabled(
            False)  # Don't render until we're ready

        # Grab some context data
        show_domains = self.chk_show_domains.isChecked()
        show_structures = self.chk_show_structures.isChecked()
        show_associations = self.chk_show_associations.isChecked()
        top_level_items_expanded_info = []
        for i in range(self.trw_layers.topLevelItemCount()):
            top_level_items_expanded_info.append(
                self.trw_layers.topLevelItem(i).isExpanded())

        # Save selection
        self.update_selected_items()

        # Iterate models adding children
        self.trw_layers.blockSignals(
            True)  # We don't want to get itemSelectionChanged here
        self.trw_layers.clear()
        self.trw_layers.blockSignals(False)

        sorted_models = sorted(self.models_tree.keys())
        for model in sorted_models:
            children = []
            model_item = QTreeWidgetItem([model])

            # Filter by search text
            list_tables = self.filter_tables_by_search_text(
                self.models_tree[model].keys(), self.txt_search_text.text())
            sorted_tables = sorted(list_tables)

            for table in sorted_tables:
                current_table_info = self.models_tree[model][table]
                if current_table_info[QueryNames.KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_DOMAIN and not show_domains \
                   or current_table_info[QueryNames.KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_STRUCTURE and not show_structures \
                   or current_table_info[QueryNames.KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_ASSOCIATION and not show_associations:
                    continue

                table_item = QTreeWidgetItem([table])
                table_item.setData(0, Qt.UserRole,
                                   self.models_tree[model][table])
                geometry_type = QgsWkbTypes().geometryType(
                    QgsWkbTypes().parseType(current_table_info[
                        QueryNames.GEOMETRY_TYPE_MODEL_BAKER])
                ) if current_table_info[
                    QueryNames.GEOMETRY_TYPE_MODEL_BAKER] else None
                icon_name = self.icon_names[
                    3 if geometry_type is None else geometry_type]

                # Is the layer already loaded in canvas?
                if self.app.core.get_ladm_layer_from_qgis(
                        self._db,
                        current_table_info[QueryNames.TABLE_NAME_MODEL_BAKER],
                        EnumLayerRegistryType.IN_LAYER_TREE) is not None:
                    table_item.setText(
                        0, table + QCoreApplication.translate(
                            "LoadLayersDialog", " [already loaded]"))
                    table_item.setData(0, Qt.ForegroundRole,
                                       QBrush(Qt.lightGray))
                    table_item.setFlags(Qt.ItemIsEnabled)  # Not selectable
                else:  # Laye not in QGIS Layer Tree
                    if not current_table_info[
                            QueryNames.
                            KIND_SETTINGS_MODEL_BAKER]:  # This is a class
                        font = QFont()
                        font.setBold(True)
                        table_item.setData(0, Qt.FontRole, font)

                if current_table_info[
                        QueryNames.
                        KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_DOMAIN:
                    icon_name = self.icon_names[4]
                elif current_table_info[
                        QueryNames.
                        KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_STRUCTURE:
                    if geometry_type is None:
                        icon_name = self.icon_names[5]
                elif current_table_info[
                        QueryNames.
                        KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_ASSOCIATION:
                    icon_name = self.icon_names[6]
                icon = QIcon(":/Asistente-LADM-COL/resources/images/{}".format(
                    icon_name))
                table_item.setData(0, Qt.DecorationRole, icon)

                children.append(table_item)

            model_item.addChildren(children)
            self.trw_layers.addTopLevelItem(model_item)

        # Set selection
        iterator = QTreeWidgetItemIterator(self.trw_layers,
                                           QTreeWidgetItemIterator.Selectable)
        self.trw_layers.blockSignals(
            True)  # We don't want to get itemSelectionChanged here
        while iterator.value():
            item = iterator.value()
            if item.text(0) in self.selected_items_dict:
                item.setSelected(True)

            iterator += 1

        self.trw_layers.blockSignals(False)

        # Make model items non selectable
        # Set expand taking previous states into account
        for i in range(self.trw_layers.topLevelItemCount()):
            self.trw_layers.topLevelItem(i).setFlags(
                Qt.ItemIsEnabled)  # Not selectable
            self.trw_layers.topLevelItem(i).setExpanded(
                top_level_items_expanded_info[i]
                if top_level_items_expanded_info else True)

        self.trw_layers.setUpdatesEnabled(True)  # Now render!
Exemplo n.º 22
0
    def __init__(self):
        super(TestSelector, self).__init__()
        self.setupUi(self)

        self.tests = None

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

        allTests = defaultdict(list)
        for test in tests.tests:
            allTests[test.group].append(test)

        for group, groupTests in iteritems(allTests):
            groupItem = QTreeWidgetItem()
            groupItem.setText(0, group)
            groupItem.setFlags(groupItem.flags() | Qt.ItemIsTristate);
            unitItem = QTreeWidgetItem()
            unitItem.setText(0, "Fully automated tests")
            unitItem.setFlags(unitItem.flags() | Qt.ItemIsTristate);
            manualItem = QTreeWidgetItem()
            manualItem.setText(0, "Manual and semi-automated tests")
            manualItem.setFlags(manualItem.flags() | Qt.ItemIsTristate);
            unitTestsByCategories = defaultdict(list)
            manualTestsByCategories = defaultdict(list)
            for test in groupTests:
                if isinstance(test, UnitTestWrapper):
                    unitTestsByCategories[test.category].append(test)
                else:
                    manualTestsByCategories[test.category].append(test)
            for testsList, parentItem in [(unitTestsByCategories, unitItem), (manualTestsByCategories, manualItem)]:
                for cat, catTests in iteritems(testsList):
                    categoryItem = QTreeWidgetItem()
                    categoryItem.setText(0, cat)
                    categoryItem.setFlags(manualItem.flags() | Qt.ItemIsTristate);
                    for test in catTests:
                        testItem = QTreeWidgetItem()
                        testItem.setFlags(testItem.flags() | Qt.ItemIsUserCheckable);
                        testItem.setCheckState(0, Qt.Unchecked);
                        testItem.test = test
                        testItem.setText(0, test.name)
                        categoryItem.addChild(testItem)
                    parentItem.addChild(categoryItem)
            if manualItem.childCount():
                groupItem.addChild(manualItem)
            if unitItem.childCount():
                groupItem.addChild(unitItem)
            self.testsTree.addTopLevelItem(groupItem)
            groupItem.setExpanded(True)

        self.buttonBox.button(QDialogButtonBox.Ok).setText("Run selected tests")
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)

        self.selectAllLabel.linkActivated.connect(lambda: self.checkTests(lambda t: Qt.Checked))
        self.unselectAllLabel.linkActivated.connect(lambda: self.checkTests(lambda t: Qt.Unchecked))
        def _onlyManual(t):
            if isinstance(t, UnitTestWrapper):
                return Qt.Unchecked
            else:
                return Qt.Checked
        self.onlyManualLabel.linkActivated.connect(lambda: self.checkTests(_onlyManual))
        def _onlyUnit(t):
            if isinstance(t, UnitTestWrapper):
                return Qt.Checked
            else:
                return Qt.Unchecked
        self.onlyUnitLabel.linkActivated.connect(lambda: self.checkTests(_onlyUnit))

        filepath = os.path.expanduser("~/.testerplugin/failed.txt")
        if os.path.exists(filepath):
            with open(filepath) as f:
                failed = json.load(f)
        else:
            failed = []
        def _onlyLastFailures(t):
            if t.group in failed and t.name in failed[t.group]:
                return Qt.Checked
            else:
                return Qt.Unchecked
        self.onlyLastFailuresLabel.linkActivated.connect(lambda: self.checkTests(_onlyLastFailures))

        

        self.exportButton.clicked.connect(self.export)
Exemplo n.º 23
0
    def fillAlgorithmTreeUsingProviders(self):
        self.algorithmTree.clear()
        text = str(self.searchBox.text())
        search_strings = text.split(' ')
        qgis_groups = {}
        for provider in QgsApplication.processingRegistry().providers():
            if not provider.isActive():
                continue
            groups = {}

            # Add algorithms
            for alg in provider.algorithms():
                if alg.flags() & QgsProcessingAlgorithm.FlagHideFromModeler:
                    continue
                if alg.id() == self.model.id():
                    continue

                item_text = [alg.displayName().lower()]
                item_text.extend(alg.tags())

                show = not search_strings or all(
                    any(part in t for t in item_text)
                    for part in search_strings)

                if show:
                    if alg.group() in groups:
                        groupItem = groups[alg.group()]
                    elif provider.id() in (
                            'qgis', 'native') and alg.group() in qgis_groups:
                        groupItem = qgis_groups[alg.group()]
                    else:
                        groupItem = QTreeWidgetItem()
                        name = alg.group()
                        groupItem.setText(0, name)
                        groupItem.setToolTip(0, name)
                        groupItem.setFlags(Qt.ItemIsEnabled
                                           | Qt.ItemIsSelectable)
                        if provider.id() in ('qgis', 'native'):
                            groupItem.setIcon(0, provider.icon())
                            qgis_groups[alg.group()] = groupItem
                        else:
                            groups[alg.group()] = groupItem
                    algItem = TreeAlgorithmItem(alg)
                    groupItem.addChild(algItem)

            if len(groups) > 0:
                providerItem = QTreeWidgetItem()
                providerItem.setText(0, provider.name())
                providerItem.setToolTip(0, provider.name())
                providerItem.setIcon(0, provider.icon())
                providerItem.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
                for groupItem in list(groups.values()):
                    providerItem.addChild(groupItem)
                self.algorithmTree.addTopLevelItem(providerItem)
                providerItem.setExpanded(text != '')
                for groupItem in list(groups.values()):
                    if text != '':
                        groupItem.setExpanded(True)

        if len(qgis_groups) > 0:
            for groupItem in list(qgis_groups.values()):
                self.algorithmTree.addTopLevelItem(groupItem)
            for groupItem in list(qgis_groups.values()):
                if text != '':
                    groupItem.setExpanded(True)

        self.algorithmTree.sortItems(0, Qt.AscendingOrder)
Exemplo n.º 24
0
    def __init__(self):
        super(TestSelector, self).__init__()
        self.setupUi(self)

        self.tests = None

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

        allTests = defaultdict(list)
        for test in tests.tests:
            allTests[test.group].append(test)

        for group, groupTests in allTests.items():
            groupItem = QTreeWidgetItem()
            groupItem.setText(0, group)
            groupItem.setFlags(groupItem.flags() | Qt.ItemIsTristate)
            unitItem = QTreeWidgetItem()
            unitItem.setText(0, 'Fully Automated Tests')
            unitItem.setFlags(unitItem.flags() | Qt.ItemIsTristate)
            manualItem = QTreeWidgetItem()
            manualItem.setText(0, 'Manual and Semi-Automated Tests')
            manualItem.setFlags(manualItem.flags() | Qt.ItemIsTristate)
            unitTestsByCategories = defaultdict(list)
            manualTestsByCategories = defaultdict(list)
            for test in groupTests:
                if isinstance(test, UnitTestWrapper):
                    unitTestsByCategories[test.category].append(test)
                else:
                    manualTestsByCategories[test.category].append(test)
            for testsList, parentItem in [(unitTestsByCategories, unitItem),
                                          (manualTestsByCategories, manualItem)
                                          ]:
                for cat, catTests in testsList.items():
                    categoryItem = QTreeWidgetItem()
                    categoryItem.setText(0, cat)
                    categoryItem.setFlags(manualItem.flags()
                                          | Qt.ItemIsTristate)
                    for test in catTests:
                        testItem = QTreeWidgetItem()
                        testItem.setFlags(testItem.flags()
                                          | Qt.ItemIsUserCheckable)
                        testItem.setCheckState(0, Qt.Unchecked)
                        testItem.test = test
                        testItem.setText(0, test.name)
                        categoryItem.addChild(testItem)
                    parentItem.addChild(categoryItem)
            if manualItem.childCount():
                groupItem.addChild(manualItem)
            if unitItem.childCount():
                groupItem.addChild(unitItem)
            self.testsTree.addTopLevelItem(groupItem)
            groupItem.setExpanded(True)

        self.testsTree.itemChanged.connect(self.toggleRunButton)
        self.buttonBox.button(
            QDialogButtonBox.Ok).setText('Run Selected Tests')
        self.buttonBox.button(QDialogButtonBox.Ok).setEnabled(False)
        self.buttonBox.accepted.connect(self.okPressed)
        self.buttonBox.rejected.connect(self.cancelPressed)

        self.selectAllLabel.linkActivated.connect(
            lambda: self.checkTests(lambda t: Qt.Checked))
        self.unselectAllLabel.linkActivated.connect(
            lambda: self.checkTests(lambda t: Qt.Unchecked))

        def _onlyManual(t):
            if isinstance(t, UnitTestWrapper):
                return Qt.Unchecked
            else:
                return Qt.Checked

        self.onlyManualLabel.linkActivated.connect(
            lambda: self.checkTests(_onlyManual))

        def _onlyUnit(t):
            if isinstance(t, UnitTestWrapper):
                return Qt.Checked
            else:
                return Qt.Unchecked

        self.onlyUnitLabel.linkActivated.connect(
            lambda: self.checkTests(_onlyUnit))

        filepath = os.path.expanduser('~/.testerplugin/failed.txt')
        if os.path.exists(filepath):
            with open(filepath) as f:
                failed = json.load(f)
        else:
            failed = []

        def _onlyLastFailures(t):
            if t.group in failed and t.name in failed[t.group]:
                return Qt.Checked
            else:
                return Qt.Unchecked

        self.onlyLastFailuresLabel.linkActivated.connect(
            lambda: self.checkTests(_onlyLastFailures))

        self.exportButton.clicked.connect(self.export)