def __init__(self, parameter, parent=None):
        """Constructor.

        :param parameter: A DefaultValueParameter object.
        :type parameter: DefaultValueParameter

        """
        super(DefaultValueParameterWidget, self).__init__(parameter, parent)

        self.radio_button_layout = QHBoxLayout()

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

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

            radio_button = QRadioButton(label)
            self.radio_button_layout.addWidget(radio_button)
            self.input_button_group.addButton(radio_button, i)
            if self._parameter.value == \
                    self._parameter.options[i]:
                radio_button.setChecked(True)

        # Create double spin box for custom value
        self.custom_value = QDoubleSpinBox()
        self.custom_value.setSingleStep(0.1)
        if self._parameter.options[-1]:
            self.custom_value.setValue(self._parameter.options[-1])
        self.radio_button_layout.addWidget(self.custom_value)

        self.toggle_custom_value()

        self.inner_input_layout.addLayout(self.radio_button_layout)

        # Connect
        # noinspection PyUnresolvedReferences
        self.input_button_group.buttonClicked.connect(
            self.toggle_custom_value)
class DefaultValueParameterWidget(GenericParameterWidget):

    """Widget class for Default Value Parameter."""

    def __init__(self, parameter, parent=None):
        """Constructor.

        :param parameter: A DefaultValueParameter object.
        :type parameter: DefaultValueParameter

        """
        super(DefaultValueParameterWidget, self).__init__(parameter, parent)

        self.radio_button_layout = QHBoxLayout()

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

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

            radio_button = QRadioButton(label)
            self.radio_button_layout.addWidget(radio_button)
            self.input_button_group.addButton(radio_button, i)
            if self._parameter.value == \
                    self._parameter.options[i]:
                radio_button.setChecked(True)

        # Create double spin box for custom value
        self.custom_value = QDoubleSpinBox()
        self.custom_value.setSingleStep(0.1)
        if self._parameter.options[-1]:
            self.custom_value.setValue(self._parameter.options[-1])
        self.radio_button_layout.addWidget(self.custom_value)

        self.toggle_custom_value()

        self.inner_input_layout.addLayout(self.radio_button_layout)

        # Connect
        # noinspection PyUnresolvedReferences
        self.input_button_group.buttonClicked.connect(
            self.toggle_custom_value)

    def raise_invalid_type_exception(self):
        """Raise invalid type."""
        message = 'Expecting element type of %s' % (
            self._parameter.element_type.__name__)
        err = ValueError(message)
        return err

    def get_parameter(self):
        """Obtain list parameter object from the current widget state.

        :returns: A DefaultValueParameter from the current state of widget
        :rtype: DefaultValueParameter
        """
        radio_button_checked_id = self.input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id == -1:
            self._parameter.value = None
        # The last radio button (custom) is checked, get the value from the
        # line edit
        elif radio_button_checked_id == len(self._parameter.options) - 1:
            self._parameter.options[radio_button_checked_id] = \
                self.custom_value.value()
            self._parameter.value = self.custom_value.value()
        else:
            self._parameter.value = self._parameter.options[
                radio_button_checked_id]

        return self._parameter

    def set_value(self, value):
        """Set value by item's string.

        :param value: The value.
        :type value: str, int

        :returns: True if success, else False.
        :rtype: bool
        """
        # Find index of choice
        try:
            value_index = self._parameter.options.index(value)
            self.input_button_group.button(value_index).setChecked(True)
        except ValueError:
            last_index = len(self._parameter.options) - 1
            self.input_button_group.button(last_index).setChecked(
                True)
            self.custom_value.setValue(value)

        self.toggle_custom_value()

    def toggle_custom_value(self):
        """Enable or disable the custom value line edit."""
        radio_button_checked_id = self.input_button_group.checkedId()
        if (radio_button_checked_id
                == len(self._parameter.options) - 1):
            self.custom_value.setDisabled(False)
        else:
            self.custom_value.setDisabled(True)
Example #3
0
    def set_widgets(self):
        """Set widgets on the Threshold tab."""
        clear_layout(self.gridLayoutThreshold)

        # Set text in the label
        layer_purpose = self.parent.step_kw_purpose.selected_purpose()
        layer_subcategory = self.parent.step_kw_subcategory.\
            selected_subcategory()
        classification = self.parent.step_kw_classification. \
            selected_classification()

        if is_raster_layer(self.parent.layer):
            statistics = self.parent.layer.dataProvider().bandStatistics(
                1, QgsRasterBandStats.All, self.parent.layer.extent(), 0)
            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)
            text = continuous_vector_question % (
                layer_purpose['name'],
                layer_subcategory['name'],
                field_name,
                classification['name'],
                min_value_layer,
                max_value_layer)
        self.lblThreshold.setText(text)

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

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

        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(the_class['key']):
                min_value_input.setValue(thresholds[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)
            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(the_class['key']):
                max_value_input.setValue(thresholds[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)
            max_value_input.setSingleStep(0.1)

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

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

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

        self.gridLayoutThreshold.setSpacing(0)

        def min_max_changed(index, the_string):
            """Slot when min or max value change.

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

            :param the_string: The flag to indicate the min or max value.
            :type the_string: str
            """
            if the_string == 'Max value':
                current_max_value = list(self.classes.values())[index][1]
                target_min_value = list(self.classes.values())[index + 1][0]
                if current_max_value.value() != target_min_value.value():
                    target_min_value.setValue(current_max_value.value())
            elif the_string == 'Min value':
                current_min_value = list(self.classes.values())[index][0]
                target_max_value = list(self.classes.values())[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.classes.items()):
            index = list(self.classes.keys()).index(k)
            if index < len(self.classes) - 1:
                # Max value changed
                v[1].valueChanged.connect(partial(
                    min_max_changed, index=index, the_string='Max value'))
            if index > 0:
                # Min value
                v[0].valueChanged.connect(partial(
                    min_max_changed, index=index, the_string='Min value'))
    def testLinkedWidgets(self):
        """ test linking spin boxes to combobox"""
        w = qgis.gui.QgsLayoutUnitsComboBox()
        self.assertFalse(w.converter())
        c = QgsLayoutMeasurementConverter()
        w.setConverter(c)
        self.assertEqual(w.converter(), c)

        spin = QDoubleSpinBox()
        spin.setMaximum(1000000)
        spin.setValue(100)
        w.setUnit(QgsUnitTypes.LayoutCentimeters)
        w.linkToWidget(spin)
        w.setUnit(QgsUnitTypes.LayoutMeters)
        self.assertAlmostEqual(spin.value(), 1.0, 2)
        w.setUnit(QgsUnitTypes.LayoutMillimeters)
        self.assertAlmostEqual(spin.value(), 1000.0, 2)

        spin2 = QDoubleSpinBox()
        spin2.setValue(50)
        spin2.setMaximum(1000000)
        w.linkToWidget(spin2)
        w.setUnit(QgsUnitTypes.LayoutCentimeters)
        self.assertAlmostEqual(spin.value(), 100.0, 2)
        self.assertAlmostEqual(spin2.value(), 5.0, 2)

        # no crash!
        del spin
        w.setUnit(QgsUnitTypes.LayoutMeters)
        self.assertAlmostEqual(spin2.value(), 0.05, 2)
Example #5
0
    def testLinkedWidgets(self):
        """ test linking spin boxes to combobox"""
        w = qgis.gui.QgsRatioLockButton()

        spin_width = QDoubleSpinBox()
        spin_width.setMaximum(100000)
        spin_height = QDoubleSpinBox()
        spin_height.setMaximum(100000)

        w.setWidthSpinBox(spin_width)
        spin_width.setValue(1000)
        self.assertEqual(spin_width.value(), 1000)

        w.setLocked(True)
        spin_width.setValue(2000)
        self.assertEqual(spin_width.value(), 2000)
        w.setLocked(False)

        w.setHeightSpinBox(spin_height)
        spin_width.setValue(1000)
        self.assertEqual(spin_width.value(), 1000)
        self.assertEqual(spin_height.value(), 0)

        w.setLocked(True)
        spin_width.setValue(2000)
        self.assertEqual(spin_width.value(), 2000)
        self.assertEqual(spin_height.value(), 0)

        spin_height.setValue(1000)
        self.assertEqual(spin_width.value(), 2000)
        self.assertEqual(spin_height.value(), 1000)

        # ok, that was all setup tests... let's check the real thing now
        spin_width.setValue(1000)
        self.assertEqual(spin_width.value(), 1000)
        self.assertEqual(spin_height.value(), 500)
        spin_height.setValue(1000)
        self.assertEqual(spin_width.value(), 2000)
        self.assertEqual(spin_height.value(), 1000)

        w.setLocked(False)
        spin_width.setValue(1000)
        self.assertEqual(spin_width.value(), 1000)
        self.assertEqual(spin_height.value(), 1000)
        spin_height.setValue(2000)
        self.assertEqual(spin_width.value(), 1000)
        self.assertEqual(spin_height.value(), 2000)

        w.setLocked(True)
        spin_height.setValue(1000)
        self.assertEqual(spin_width.value(), 500)
        self.assertEqual(spin_height.value(), 1000)

        # setting to 0 should "break" lock
        spin_height.setValue(0)
        self.assertEqual(spin_width.value(), 500)
        self.assertEqual(spin_height.value(), 0)
        spin_width.setValue(1000)
        self.assertEqual(spin_width.value(), 1000)
        self.assertEqual(spin_height.value(), 0)
        spin_height.setValue(100)
        self.assertEqual(spin_width.value(), 1000)
        self.assertEqual(spin_height.value(), 100)

        spin_width.setValue(0)
        self.assertEqual(spin_width.value(), 0)
        self.assertEqual(spin_height.value(), 100)
        spin_height.setValue(1000)
        self.assertEqual(spin_width.value(), 0)
        self.assertEqual(spin_height.value(), 1000)
        spin_width.setValue(200)
        self.assertEqual(spin_width.value(), 200)
        self.assertEqual(spin_height.value(), 1000)
Example #6
0
    def testResetRatio(self):
        w = qgis.gui.QgsRatioLockButton()

        spin_width = QDoubleSpinBox()
        spin_width.setMaximum(100000)
        spin_height = QDoubleSpinBox()
        spin_height.setMaximum(100000)

        spin_width.setValue(1000)
        w.setWidthSpinBox(spin_width)
        spin_height.setValue(500)
        w.setHeightSpinBox(spin_height)

        w.setLocked(True)
        spin_width.setValue(2000)
        self.assertEqual(spin_height.value(), 1000)

        spin_width.blockSignals(True)
        spin_width.setValue(1000)
        spin_width.blockSignals(False)

        spin_height.setValue(2000)
        self.assertEqual(spin_width.value(), 4000)  # signals were blocked, so ratio wasn't updated

        spin_width.blockSignals(True)
        spin_width.setValue(2000)
        spin_width.blockSignals(False)
        w.resetRatio() # since signals were blocked, we need to manually reset ratio
        spin_height.setValue(1000)
        self.assertEqual(spin_width.value(), 1000)
class Ui_Dialog(object):
    """
    def __init__(self, iface):
        self.iface = iface
    """
    def setupUi(self, Dialog):
        self.iface = iface
        Dialog.setObjectName("Dialog")
        Dialog.resize(
            QtCore.QSize(QtCore.QRect(0, 0, 350, 250).size()).expandedTo(
                Dialog.minimumSizeHint()))
        Dialog.setWindowTitle("GroupPointsWithinDistance")

        # QLabel lancer recherche
        self.label10 = QLabel(Dialog)
        self.label10.setGeometry(QtCore.QRect(15, 15, 320, 18))
        self.label10.setObjectName("label10")
        self.label10.setText("Select a layer with points to regroup:  ")

        ListeCouchesPoint = [""]
        NbCouches = self.iface.mapCanvas().layerCount()
        if NbCouches == 0:
            QMessageBox.information(None, "information:", "No layers ! ")
        else:
            for i in range(0, NbCouches):
                couche = self.iface.mapCanvas().layer(i)
                # 0 pour point
                if couche.geometryType() == 0 or couche.geometryType() == 3:
                    if couche.isValid():
                        ListeCouchesPoint.append(couche.name())
                    else:
                        QMessageBox.information(None, "information:",
                                                "No layers with points ! ")
                        return None
        self.ComboBoxPoints = QComboBox(Dialog)
        self.ComboBoxPoints.setMinimumSize(QtCore.QSize(320, 25))
        self.ComboBoxPoints.setMaximumSize(QtCore.QSize(320, 25))
        self.ComboBoxPoints.setGeometry(QtCore.QRect(10, 35, 320, 25))
        self.ComboBoxPoints.setObjectName("ComboBoxPoints")
        for i in range(len(ListeCouchesPoint)):
            self.ComboBoxPoints.addItem(ListeCouchesPoint[i])

        # QLabel entrer Enter distance of recherch
        self.labelResearchDistance = QLabel(Dialog)
        self.labelResearchDistance.setGeometry(QtCore.QRect(15, 80, 240, 23))
        self.labelResearchDistance.setObjectName(" ResearchDistance")
        self.labelResearchDistance.setText("Enter distance of research :")

        #Exemple de QDoubleSpinBox
        self.dsbResearchDistance = QDoubleSpinBox(Dialog)
        self.dsbResearchDistance.setMinimumSize(QtCore.QSize(70, 23))
        self.dsbResearchDistance.setMaximumSize(QtCore.QSize(70, 23))
        self.dsbResearchDistance.setGeometry(QtCore.QRect(180, 80, 70, 23))
        self.dsbResearchDistance.setObjectName("dsb")
        #self.dsbResearchDistance.setValue(10.0)
        self.dsbResearchDistance.setDecimals(1)
        self.dsbResearchDistance.setSingleStep(10.0)
        self.dsbResearchDistance.setRange(0, 1000000)
        self.dsbResearchDistance.setProperty("value", 100.0)

        #self.dsbResearchDistance.valueChanged.connect(self.onValueChanged)

        #Exemple de QPushButton
        self.DoButton = QPushButton(Dialog)
        self.DoButton.setMinimumSize(QtCore.QSize(280, 20))
        self.DoButton.setMaximumSize(QtCore.QSize(280, 20))
        self.DoButton.setGeometry(QtCore.QRect(15, 120, 280, 20))
        self.DoButton.setObjectName("DoButton")
        self.DoButton.setText(" Let's make aggregates - being patient !")

        #Exemple de QLCDNumber
        self.progressBar = QProgressBar(Dialog)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setMinimumSize(QtCore.QSize(260, 15))
        self.progressBar.setMaximumSize(QtCore.QSize(260, 15))
        self.progressBar.setGeometry(QtCore.QRect(30, 155, 260, 15))
        self.progressBar.setAlignment(QtCore.Qt.AlignCenter)
        self.progressBar.setTextVisible(True)
        self.progressBar.setObjectName("progressBar")
        self.progressBar.setStyleSheet(
            """QProgressBar {border: 2px solid grey; border-radius: 5px; text-align: center;}"""
            """QProgressBar::chunk {background-color: #6C96C6; width: 20px;}"""
        )
        #Pose a minima une valeur de la barre de progression / slide contrĂ´le
        self.progressBar.setValue(0)

        #Exemple de QPushButton
        self.aboutButton = QPushButton(Dialog)
        self.aboutButton.setMinimumSize(QtCore.QSize(70, 20))
        self.aboutButton.setMaximumSize(QtCore.QSize(70, 20))
        self.aboutButton.setGeometry(QtCore.QRect(30, 195, 70, 23))
        self.aboutButton.setObjectName("aboutButton")
        self.aboutButton.setText(" Read me ")

        self.PushButton = QPushButton(Dialog)
        self.PushButton.setMinimumSize(QtCore.QSize(100, 20))
        self.PushButton.setMaximumSize(QtCore.QSize(100, 20))
        self.PushButton.setGeometry(QtCore.QRect(185, 195, 100, 20))
        self.PushButton.setObjectName("PushButton")
        self.PushButton.setText("Close")

        self.PushButton.clicked.connect(Dialog.reject)
        self.ComboBoxPoints.activated[str].connect(self.onComboP)
        self.aboutButton.clicked.connect(self.doAbout)
        self.DoButton.clicked.connect(self.Run)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def onComboP(self):
        global SelectionP
        SelectionP = self.ComboBoxPoints.currentText()

    def doAbout(self):
        d = doAboutGroupPointsWithinDistance.Dialog()
        d.exec_()

    def Run(self):
        D = 0.0
        D = self.dsbResearchDistance.value()
        #QMessageBox.information(None,"information:"," D : "+str(D))
        DicoP1 = {}
        DicoA = {}
        counterProgess = 0
        compteur_pt = 0
        layerP = fonctionsGPWD.getVectorLayerByName(SelectionP)
        # on parcourt la couche de points et on stocke dans les dictionnaire DicoP1  les points
        # the points of the point laye are put into a dictionnary
        for featP in layerP.getFeatures():
            Point_id = featP.id()
            geomP1 = featP.geometry()
            Point1 = geomP1.asPoint()
            DicoP1[Point_id] = [Point1]
            compteur_pt += 1

        if D == 0:
            QMessageBox.information(None, "information:",
                                    "Zero is not a value for D !")

        #zdim est le compteur de la progress bar
        zDim = compteur_pt
        counterProgess = 0
        cpt_agg = 1
        nb = 0
        liste_id = []
        liste_pt = []
        liste_aggreg_pt = []
        DicoSegments = {}
        firstDicoSegments = True
        T = True
        while len(DicoP1) != 0:
            first = True
            zPercent = int(100 * counterProgess / zDim)
            self.progressBar.setValue(zPercent)
            nb = 0
            for keyD1 in list(DicoP1.keys()):
                P1 = DicoP1[keyD1][0]
            if first:
                # we pick a first point and delete it from the dictionnary we point are stored
                T = True
                first = False
                nb += 1
                liste_id = [keyD1]
                liste_pt = [P1]
                counterProgess += 1
                del DicoP1[keyD1]
            while T:
                # We are generating an aggregates and making it grows
                # by adding points at distance from the point it contains
                # and repeating the research all over again as soon a poitn is added
                # untill none are added
                for pt in liste_pt:
                    compteur_corresP = 0
                    for keyD1 in list(DicoP1.keys()):
                        P1 = DicoP1[keyD1][0]
                        if fonctionsGPWD.mag(fonctionsGPWD.vect(
                                pt, P1)) < D:  # one point at distance found
                            compteur_corresId = 0
                            for idp in liste_id:
                                if keyD1 == idp:  # is this point already added in the aggregate
                                    compteur_corresId += 1
                            if compteur_corresId == 0:  # if not let s add it
                                nb += 1
                                liste_id.append(keyD1)
                                liste_pt.append(P1)
                                compteur_corresP += 1
                                counterProgess += 1
                                # boucle des segments
                                # interpoint line loop
                                idseg = ''  # a segment as an id made of the points id order ordered id: smallerid-biggerid
                                idseg = str(keyD1) + '-' + str(idp)
                                idseg_reverse = str(idp) + '-' + str(keyD1)
                                if firstDicoSegments:
                                    firstDicoSegments = False
                                    if int(keyD1) > int(idp):
                                        idseg = idseg_reverse
                                        DicoSegments[idseg] = [[pt, P1], idp,
                                                               keyD1, cpt_agg]
                                    else:
                                        DicoSegments[idseg] = [[P1, pt], keyD1,
                                                               idp, cpt_agg]
                                else:
                                    for idseg_cheack in list(
                                            DicoSegments.keys()):
                                        if idseg == idseg_cheack or idseg_reverse == idseg_cheack:
                                            pass
                                        else:
                                            if int(keyD1) > int(idp):
                                                idseg = idseg_reverse
                                                DicoSegments[idseg] = [[
                                                    pt, P1
                                                ], idp, keyD1, cpt_agg]
                                            else:
                                                DicoSegments[idseg] = [[
                                                    P1, pt
                                                ], keyD1, idp, cpt_agg]

                if compteur_corresP == 0:  # if no more points are find then we are over with the previous aggregate
                    T = False

                    DicoA[cpt_agg] = [nb, liste_id, liste_pt, DicoSegments]
                    cpt_agg += 1
                    for id in liste_id:
                        for keyD1 in list(DicoP1.keys()):
                            if id == keyD1:
                                del DicoP1[keyD1]

        # on fabrique un polygone buffer de D/100
        # du convexHull de tous les points de l'agregat
        # pour les operateur Pyqgis
        # voir http://www.qgis.org/api/classQgsGeometry.html#a1699b205d01c365a50ead2d0bf2bbcfb
        DicoP4 = {}

        for key2 in list(DicoA.keys()):
            list_pt = []
            list_pt = DicoA[key2][2]
            nb_pt = 0
            nb_pt = DicoA[key2][0]
            Liste_id = []
            Liste_id = DicoA[key2][1]
            buff = 0.0
            first = True
            for pt in list_pt:
                if first:
                    first = False
                    #https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/geometry.html
                    g0 = QgsGeometry().fromPointXY(pt)
                else:
                    g0 = QgsGeometry().fromPointXY(pt).combine(
                        g0)  # combine pour union car union reserve C++
            buff = D / 100
            P = g0.convexHull()
            B = P.buffer(buff, 5)
            DicoP4[key2] = [B, Liste_id, nb_pt]

        zPercent = int(100 * counterProgess / zDim)
        self.progressBar.setValue(zPercent)
        self.iface.mapCanvas().refresh()

        STATIONS = QgsVectorLayer(
            "MultiPolygon", "Polygons_under_AGGREGATES_D" + str(D) + "_OF_" +
            str(layerP.name()), "memory")
        QgsProject.instance().addMapLayer(STATIONS)
        prSTATIONS = STATIONS.dataProvider()
        listFieldsS = []
        listFieldsS.append(QgsField("NumAggreg", QVariant.String))
        listFieldsS.append(QgsField("List_Pts", QVariant.String))
        listFieldsS.append(QgsField("Nb_Pts", QVariant.Int))
        prSTATIONS.addAttributes(listFieldsS)

        STATIONS.startEditing()
        newfeatSTATIONS = QgsFeature()
        for keyP4 in DicoP4.keys():
            GeomPoly = DicoP4[keyP4][0]
            newfeatSTATIONS = QgsFeature()
            newfeatSTATIONS.setGeometry(GeomPoly)
            toto = ''
            first = True
            for t in DicoP4[keyP4][1]:
                if first:
                    first = False
                    toto = str(t)
                else:
                    toto = toto + ' - ' + str(t)
            NbObs = DicoP4[keyP4][2]
            ValuesSTATIONS = [keyP4]
            ValuesSTATIONS.append(toto)
            ValuesSTATIONS.append(NbObs)
            newfeatSTATIONS.setAttributes(ValuesSTATIONS)
            prSTATIONS.addFeatures([newfeatSTATIONS])
        STATIONS.commitChanges()
        iface.mapCanvas().refresh()

        SEGMENTS = QgsVectorLayer(
            "MultiLineString",
            "Lines_from_" + str(layerP.name()) + "_Aggregates_with_D" + str(D),
            "memory")
        QgsProject.instance().addMapLayer(SEGMENTS)
        prSEGMENTS = SEGMENTS.dataProvider()
        listFields = []
        listFields.append(QgsField("NumAgregat", QVariant.String))
        listFields.append(QgsField("Nb_Pts", QVariant.Int))
        prSEGMENTS.addAttributes(listFields)
        SEGMENTS.startEditing()
        newfeatSEGMENTS = QgsFeature()
        attributs = []
        for keyA in DicoA.keys():
            DicoSeg = DicoA[keyA][3]
            NbObs = DicoA[keyA][0]
            firstSEG = True
            MultiLine = []
            GeomLine = QgsGeometry
            for keyPair in DicoSeg.keys():
                if DicoSeg[keyPair][3] == keyA:
                    if firstSEG:
                        firstSEG = False
                        MultiLine = []
                        MultiLine = [DicoSeg[keyPair][0]]
                    else:
                        MultiLine.append(DicoSeg[keyPair][0])

            GeomLine = QgsGeometry.fromMultiPolylineXY(MultiLine)
            NumAg = keyA
            newfeatSEGMENTS = QgsFeature()
            newfeatSEGMENTS.setGeometry(GeomLine)
            ValuesSEGMENTS = [NumAg]
            ValuesSEGMENTS.append(NbObs)
            newfeatSEGMENTS.setAttributes(ValuesSEGMENTS)
            prSEGMENTS.addFeatures([newfeatSEGMENTS])
        SEGMENTS.commitChanges()
        iface.mapCanvas().refresh()

        # modification de la table de point initiale pour ajout d un numero d agregat
        # making of the modified point layer with aggregates code
        AGGREGATS = QgsVectorLayer(
            "Point",
            str(layerP.name()) + "_aggregated_with_D" + str(D), "memory")
        QgsProject.instance().addMapLayer(AGGREGATS)
        prAGGREGATS = AGGREGATS.dataProvider()
        fieldsP = layerP.fields()
        listFields = []
        for f in fieldsP:
            znameField = f.name()
            Type = str(f.typeName())
            if Type == 'Integer':
                listFields.append(QgsField(znameField, QVariant.Int))
            if Type == 'Real':
                listFields.append(QgsField(znameField, QVariant.Double))
            if Type == 'String':
                listFields.append(QgsField(znameField, QVariant.String))
            else:
                listFields.append(QgsField(znameField, QVariant.String))
        listFields.append(QgsField("Point_id", QVariant.String))
        listFields.append(QgsField("NumAggreg", QVariant.String))
        listFields.append(QgsField("Nb_Pts", QVariant.Int))
        listFields.append(QgsField("List_Pts", QVariant.String))
        prAGGREGATS.addAttributes(listFields)
        AGGREGATS.startEditing()
        newfeatAGGREGATS = QgsFeature()
        attributs = []
        for featP in layerP.getFeatures():
            attributs = featP.attributes()
            Point_id = featP.id()
            geomP1 = featP.geometry()
            NbObs = 1
            NumAgregat = 0
            for keyP4 in DicoP4.keys():
                #GeomPoly=DicoP4[keyP4][0]
                #if geomP1.intersects(GeomPoly):
                for ptid in DicoP4[keyP4][1]:
                    if Point_id == ptid:
                        NbObs = DicoP4[keyP4][2]
                        toto = ''
                        first = True
                        for t in DicoP4[keyP4][1]:
                            if first:
                                first = False
                                toto = str(t)
                            else:
                                toto = toto + ' - ' + str(t)
                        list_id = toto
                        NumAgregat = keyP4
            newfeatAGGREGATS = QgsFeature()
            newfeatAGGREGATS.setGeometry(geomP1)
            ValuesAGGREGATS = attributs
            ValuesAGGREGATS.append(Point_id)
            ValuesAGGREGATS.append(NumAgregat)
            ValuesAGGREGATS.append(NbObs)
            ValuesAGGREGATS.append(list_id)
            newfeatAGGREGATS.setAttributes(ValuesAGGREGATS)
            prAGGREGATS.addFeatures([newfeatAGGREGATS])
        AGGREGATS.commitChanges()
        iface.mapCanvas().refresh()
Example #8
0
    def testLinkedWidgets(self):
        """ test linking spin boxes to combobox"""
        w = qgis.gui.QgsRatioLockButton()

        spin_width = QDoubleSpinBox()
        spin_width.setMaximum(100000)
        spin_height = QDoubleSpinBox()
        spin_height.setMaximum(100000)

        w.setWidthSpinBox(spin_width)
        spin_width.setValue(1000)
        self.assertEqual(spin_width.value(), 1000)

        w.setLocked(True)
        spin_width.setValue(2000)
        self.assertEqual(spin_width.value(), 2000)
        w.setLocked(False)

        w.setHeightSpinBox(spin_height)
        spin_width.setValue(1000)
        self.assertEqual(spin_width.value(), 1000)
        self.assertEqual(spin_height.value(), 0)

        w.setLocked(True)
        spin_width.setValue(2000)
        self.assertEqual(spin_width.value(), 2000)
        self.assertEqual(spin_height.value(), 0)

        spin_height.setValue(1000)
        self.assertEqual(spin_width.value(), 2000)
        self.assertEqual(spin_height.value(), 1000)

        # ok, that was all setup tests... let's check the real thing now
        spin_width.setValue(1000)
        self.assertEqual(spin_width.value(), 1000)
        self.assertEqual(spin_height.value(), 500)
        spin_height.setValue(1000)
        self.assertEqual(spin_width.value(), 2000)
        self.assertEqual(spin_height.value(), 1000)

        w.setLocked(False)
        spin_width.setValue(1000)
        self.assertEqual(spin_width.value(), 1000)
        self.assertEqual(spin_height.value(), 1000)
        spin_height.setValue(2000)
        self.assertEqual(spin_width.value(), 1000)
        self.assertEqual(spin_height.value(), 2000)

        w.setLocked(True)
        spin_height.setValue(1000)
        self.assertEqual(spin_width.value(), 500)
        self.assertEqual(spin_height.value(), 1000)

        # setting to 0 should "break" lock
        spin_height.setValue(0)
        self.assertEqual(spin_width.value(), 500)
        self.assertEqual(spin_height.value(), 0)
        spin_width.setValue(1000)
        self.assertEqual(spin_width.value(), 1000)
        self.assertEqual(spin_height.value(), 0)
        spin_height.setValue(100)
        self.assertEqual(spin_width.value(), 1000)
        self.assertEqual(spin_height.value(), 100)

        spin_width.setValue(0)
        self.assertEqual(spin_width.value(), 0)
        self.assertEqual(spin_height.value(), 100)
        spin_height.setValue(1000)
        self.assertEqual(spin_width.value(), 0)
        self.assertEqual(spin_height.value(), 1000)
        spin_width.setValue(200)
        self.assertEqual(spin_width.value(), 200)
        self.assertEqual(spin_height.value(), 1000)
Example #9
0
class DefaultValueParameterWidget(GenericParameterWidget):
    """Widget class for Default Value Parameter."""
    def __init__(self, parameter, parent=None):
        """Constructor.

        :param parameter: A DefaultValueParameter object.
        :type parameter: DefaultValueParameter

        """
        super(DefaultValueParameterWidget, self).__init__(parameter, parent)

        self.radio_button_layout = QHBoxLayout()

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

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

            radio_button = QRadioButton(label)
            self.radio_button_layout.addWidget(radio_button)
            self.input_button_group.addButton(radio_button, i)
            if self._parameter.value == \
                    self._parameter.options[i]:
                radio_button.setChecked(True)

        # Create double spin box for custom value
        self.custom_value = QDoubleSpinBox()
        self.custom_value.setSingleStep(0.1)
        if self._parameter.options[-1]:
            self.custom_value.setValue(self._parameter.options[-1])
        self.radio_button_layout.addWidget(self.custom_value)

        self.toggle_custom_value()

        self.inner_input_layout.addLayout(self.radio_button_layout)

        # Connect
        # noinspection PyUnresolvedReferences
        self.input_button_group.buttonClicked.connect(self.toggle_custom_value)

    def raise_invalid_type_exception(self):
        """Raise invalid type."""
        message = 'Expecting element type of %s' % (
            self._parameter.element_type.__name__)
        err = ValueError(message)
        return err

    def get_parameter(self):
        """Obtain list parameter object from the current widget state.

        :returns: A DefaultValueParameter from the current state of widget
        :rtype: DefaultValueParameter
        """
        radio_button_checked_id = self.input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id == -1:
            self._parameter.value = None
        # The last radio button (custom) is checked, get the value from the
        # line edit
        elif radio_button_checked_id == len(self._parameter.options) - 1:
            self._parameter.options[radio_button_checked_id] = \
                self.custom_value.value()
            self._parameter.value = self.custom_value.value()
        else:
            self._parameter.value = self._parameter.options[
                radio_button_checked_id]

        return self._parameter

    def set_value(self, value):
        """Set value by item's string.

        :param value: The value.
        :type value: str, int

        :returns: True if success, else False.
        :rtype: bool
        """
        # Find index of choice
        try:
            value_index = self._parameter.options.index(value)
            self.input_button_group.button(value_index).setChecked(True)
        except ValueError:
            last_index = len(self._parameter.options) - 1
            self.input_button_group.button(last_index).setChecked(True)
            self.custom_value.setValue(value)

        self.toggle_custom_value()

    def toggle_custom_value(self):
        """Enable or disable the custom value line edit."""
        radio_button_checked_id = self.input_button_group.checkedId()
        if (radio_button_checked_id == len(self._parameter.options) - 1):
            self.custom_value.setDisabled(False)
        else:
            self.custom_value.setDisabled(True)
    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)
    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)
class DefaultSelectParameterWidget(SelectParameterWidget):
    """Widget class for Default Select Parameter."""
    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 raise_invalid_type_exception(self):
        message = 'Expecting element type of %s' % (
            self._parameter.element_type.__name__)
        err = ValueError(message)
        return err

    def get_parameter(self):
        """Obtain list parameter object from the current widget state.

        :returns: A DefaultSelectParameter from the current state of widget.
        """
        current_index = self.input.currentIndex()
        selected_value = self.input.itemData(current_index, Qt.UserRole)
        if hasattr(selected_value, 'toPyObject'):
            selected_value = selected_value.toPyObject()

        try:
            self._parameter.value = selected_value
        except ValueError:
            err = self.raise_invalid_type_exception()
            raise err

        radio_button_checked_id = self.default_input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id == -1:
            self._parameter.default = None
        # The last radio button (custom) is checked, get the value from the
        # line edit
        elif (radio_button_checked_id == len(self._parameter.default_values) -
              1):
            self._parameter.default_values[radio_button_checked_id] \
                = self.custom_value.value()
            self._parameter.default = self.custom_value.value()
        else:
            self._parameter.default = self._parameter.default_values[
                radio_button_checked_id]

        return self._parameter

    def set_default(self, default):
        """Set default value by item's string.

        :param default: The default.
        :type default: str, int

        :returns: True if success, else False.
        :rtype: bool
        """
        # Find index of choice
        try:
            default_index = self._parameter.default_values.index(default)
            self.default_input_button_group.button(default_index).setChecked(
                True)
        except ValueError:
            last_index = len(self._parameter.default_values) - 1
            self.default_input_button_group.button(last_index).setChecked(True)
            self.custom_value.setValue(default)

        self.toggle_custom_value()

    def toggle_custom_value(self):
        radio_button_checked_id = self.default_input_button_group.checkedId()
        if (radio_button_checked_id == len(self._parameter.default_values) -
                1):
            self.custom_value.setDisabled(False)
        else:
            self.custom_value.setDisabled(True)

    def toggle_input(self):
        """Change behaviour of radio button based on input."""
        current_index = self.input.currentIndex()
        # If current input is not a radio button enabler, disable radio button.
        if self.input.itemData(current_index,
                               Qt.UserRole) != (self.radio_button_enabler):
            self.disable_radio_button()
        # Otherwise, enable radio button.
        else:
            self.enable_radio_button()

    def set_selected_radio_button(self):
        """Set selected radio button to 'Do not report'."""
        dont_use_button = self.default_input_button_group.button(
            len(self._parameter.default_values) - 2)
        dont_use_button.setChecked(True)

    def disable_radio_button(self):
        """Disable radio button group and custom value input area."""
        checked = self.default_input_button_group.checkedButton()
        if checked:
            self.default_input_button_group.setExclusive(False)
            checked.setChecked(False)
            self.default_input_button_group.setExclusive(True)
        for button in self.default_input_button_group.buttons():
            button.setDisabled(True)
        self.custom_value.setDisabled(True)

    def enable_radio_button(self):
        """Enable radio button and custom value input area then set selected
        radio button to 'Do not report'.
        """
        for button in self.default_input_button_group.buttons():
            button.setEnabled(True)
        self.set_selected_radio_button()
        self.custom_value.setEnabled(True)
def extra_keywords_to_widgets(extra_keyword_definition):
    """Create widgets for extra keyword.

    :param extra_keyword_definition: An extra keyword definition.
    :type extra_keyword_definition: dict

    :return: QCheckBox and The input widget
    :rtype: (QCheckBox, QWidget)
    """
    # Check box
    check_box = QCheckBox(extra_keyword_definition['name'])
    check_box.setToolTip(extra_keyword_definition['description'])
    check_box.setChecked(True)

    # Input widget
    if extra_keyword_definition['type'] == float:
        input_widget = QDoubleSpinBox()
        input_widget.setMinimum(extra_keyword_definition['minimum'])
        input_widget.setMaximum(extra_keyword_definition['maximum'])
        input_widget.setSuffix(extra_keyword_definition['unit_string'])
    elif extra_keyword_definition['type'] == int:
        input_widget = QSpinBox()
        input_widget.setMinimum(extra_keyword_definition['minimum'])
        input_widget.setMaximum(extra_keyword_definition['maximum'])
        input_widget.setSuffix(extra_keyword_definition['unit_string'])
    elif extra_keyword_definition['type'] == str:
        if extra_keyword_definition.get('options'):
            input_widget = QComboBox()
            options = extra_keyword_definition['options']
            for option in options:
                input_widget.addItem(
                    option['name'],
                    option['key'],
                )
            default_option_index = input_widget.findData(
                extra_keyword_definition['default_option'])
            input_widget.setCurrentIndex(default_option_index)
        else:
            input_widget = QLineEdit()
    elif extra_keyword_definition['type'] == datetime:
        input_widget = QDateTimeEdit()
        input_widget.setCalendarPopup(True)
        input_widget.setDisplayFormat('hh:mm:ss, d MMM yyyy')
        input_widget.setDateTime(datetime.now())
    else:
        raise Exception
    input_widget.setToolTip(extra_keyword_definition['description'])

    # Signal
    # noinspection PyUnresolvedReferences
    check_box.stateChanged.connect(input_widget.setEnabled)

    return check_box, input_widget
 def getSpinBoxOffset(wgt, value):
   sp = QDoubleSpinBox( wgt)
   sp.setRange(0.0, 50.0)
   sp.setSingleStep(12.5)
   sp.setDecimals(2)
   sp.setSuffix(' %')
   sp.setValue(value)
   return sp
    def setupUi(self, Dialog):
        self.iface = iface
        Dialog.setObjectName("Dialog")
        Dialog.resize(
            QtCore.QSize(QtCore.QRect(0, 0, 350, 250).size()).expandedTo(
                Dialog.minimumSizeHint()))
        Dialog.setWindowTitle("GroupPointsWithinDistance")

        # QLabel lancer recherche
        self.label10 = QLabel(Dialog)
        self.label10.setGeometry(QtCore.QRect(15, 15, 320, 18))
        self.label10.setObjectName("label10")
        self.label10.setText("Select a layer with points to regroup:  ")

        ListeCouchesPoint = [""]
        NbCouches = self.iface.mapCanvas().layerCount()
        if NbCouches == 0:
            QMessageBox.information(None, "information:", "No layers ! ")
        else:
            for i in range(0, NbCouches):
                couche = self.iface.mapCanvas().layer(i)
                # 0 pour point
                if couche.geometryType() == 0 or couche.geometryType() == 3:
                    if couche.isValid():
                        ListeCouchesPoint.append(couche.name())
                    else:
                        QMessageBox.information(None, "information:",
                                                "No layers with points ! ")
                        return None
        self.ComboBoxPoints = QComboBox(Dialog)
        self.ComboBoxPoints.setMinimumSize(QtCore.QSize(320, 25))
        self.ComboBoxPoints.setMaximumSize(QtCore.QSize(320, 25))
        self.ComboBoxPoints.setGeometry(QtCore.QRect(10, 35, 320, 25))
        self.ComboBoxPoints.setObjectName("ComboBoxPoints")
        for i in range(len(ListeCouchesPoint)):
            self.ComboBoxPoints.addItem(ListeCouchesPoint[i])

        # QLabel entrer Enter distance of recherch
        self.labelResearchDistance = QLabel(Dialog)
        self.labelResearchDistance.setGeometry(QtCore.QRect(15, 80, 240, 23))
        self.labelResearchDistance.setObjectName(" ResearchDistance")
        self.labelResearchDistance.setText("Enter distance of research :")

        #Exemple de QDoubleSpinBox
        self.dsbResearchDistance = QDoubleSpinBox(Dialog)
        self.dsbResearchDistance.setMinimumSize(QtCore.QSize(70, 23))
        self.dsbResearchDistance.setMaximumSize(QtCore.QSize(70, 23))
        self.dsbResearchDistance.setGeometry(QtCore.QRect(180, 80, 70, 23))
        self.dsbResearchDistance.setObjectName("dsb")
        #self.dsbResearchDistance.setValue(10.0)
        self.dsbResearchDistance.setDecimals(1)
        self.dsbResearchDistance.setSingleStep(10.0)
        self.dsbResearchDistance.setRange(0, 1000000)
        self.dsbResearchDistance.setProperty("value", 100.0)

        #self.dsbResearchDistance.valueChanged.connect(self.onValueChanged)

        #Exemple de QPushButton
        self.DoButton = QPushButton(Dialog)
        self.DoButton.setMinimumSize(QtCore.QSize(280, 20))
        self.DoButton.setMaximumSize(QtCore.QSize(280, 20))
        self.DoButton.setGeometry(QtCore.QRect(15, 120, 280, 20))
        self.DoButton.setObjectName("DoButton")
        self.DoButton.setText(" Let's make aggregates - being patient !")

        #Exemple de QLCDNumber
        self.progressBar = QProgressBar(Dialog)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setMinimumSize(QtCore.QSize(260, 15))
        self.progressBar.setMaximumSize(QtCore.QSize(260, 15))
        self.progressBar.setGeometry(QtCore.QRect(30, 155, 260, 15))
        self.progressBar.setAlignment(QtCore.Qt.AlignCenter)
        self.progressBar.setTextVisible(True)
        self.progressBar.setObjectName("progressBar")
        self.progressBar.setStyleSheet(
            """QProgressBar {border: 2px solid grey; border-radius: 5px; text-align: center;}"""
            """QProgressBar::chunk {background-color: #6C96C6; width: 20px;}"""
        )
        #Pose a minima une valeur de la barre de progression / slide contrĂ´le
        self.progressBar.setValue(0)

        #Exemple de QPushButton
        self.aboutButton = QPushButton(Dialog)
        self.aboutButton.setMinimumSize(QtCore.QSize(70, 20))
        self.aboutButton.setMaximumSize(QtCore.QSize(70, 20))
        self.aboutButton.setGeometry(QtCore.QRect(30, 195, 70, 23))
        self.aboutButton.setObjectName("aboutButton")
        self.aboutButton.setText(" Read me ")

        self.PushButton = QPushButton(Dialog)
        self.PushButton.setMinimumSize(QtCore.QSize(100, 20))
        self.PushButton.setMaximumSize(QtCore.QSize(100, 20))
        self.PushButton.setGeometry(QtCore.QRect(185, 195, 100, 20))
        self.PushButton.setObjectName("PushButton")
        self.PushButton.setText("Close")

        self.PushButton.clicked.connect(Dialog.reject)
        self.ComboBoxPoints.activated[str].connect(self.onComboP)
        self.aboutButton.clicked.connect(self.doAbout)
        self.DoButton.clicked.connect(self.Run)
        QtCore.QMetaObject.connectSlotsByName(Dialog)
def extra_keywords_to_widgets(extra_keyword_definition):
    """Create widgets for extra keyword.

    :param extra_keyword_definition: An extra keyword definition.
    :type extra_keyword_definition: dict

    :return: QCheckBox and The input widget
    :rtype: (QCheckBox, QWidget)
    """
    # Check box
    check_box = QCheckBox(extra_keyword_definition['name'])
    check_box.setToolTip(extra_keyword_definition['description'])
    check_box.setChecked(True)

    # Input widget
    if extra_keyword_definition['type'] == float:
        input_widget = QDoubleSpinBox()
        input_widget.setMinimum(extra_keyword_definition['minimum'])
        input_widget.setMaximum(extra_keyword_definition['maximum'])
        input_widget.setSuffix(extra_keyword_definition['unit_string'])
    elif extra_keyword_definition['type'] == int:
        input_widget = QSpinBox()
        input_widget.setMinimum(extra_keyword_definition['minimum'])
        input_widget.setMaximum(extra_keyword_definition['maximum'])
        input_widget.setSuffix(extra_keyword_definition['unit_string'])
    elif extra_keyword_definition['type'] == str:
        if extra_keyword_definition.get('options'):
            input_widget = QComboBox()
            options = extra_keyword_definition['options']
            for option in options:
                input_widget.addItem(
                    option['name'],
                    option['key'],
                )
            default_option_index = input_widget.findData(
                extra_keyword_definition['default_option'])
            input_widget.setCurrentIndex(default_option_index)
        else:
            input_widget = QLineEdit()
    elif extra_keyword_definition['type'] == datetime:
        input_widget = QDateTimeEdit()
        input_widget.setCalendarPopup(True)
        input_widget.setDisplayFormat('hh:mm:ss, d MMM yyyy')
        input_widget.setDateTime(datetime.now())
    else:
        raise Exception
    input_widget.setToolTip(extra_keyword_definition['description'])

    # Signal
    # noinspection PyUnresolvedReferences
    check_box.stateChanged.connect(input_widget.setEnabled)

    return check_box, input_widget
Example #17
0
    def testResetRatio(self):
        w = qgis.gui.QgsRatioLockButton()

        spin_width = QDoubleSpinBox()
        spin_width.setMaximum(100000)
        spin_height = QDoubleSpinBox()
        spin_height.setMaximum(100000)

        spin_width.setValue(1000)
        w.setWidthSpinBox(spin_width)
        spin_height.setValue(500)
        w.setHeightSpinBox(spin_height)

        w.setLocked(True)
        spin_width.setValue(2000)
        self.assertEqual(spin_height.value(), 1000)

        spin_width.blockSignals(True)
        spin_width.setValue(1000)
        spin_width.blockSignals(False)

        spin_height.setValue(2000)
        self.assertEqual(spin_width.value(), 4000)  # signals were blocked, so ratio wasn't updated

        spin_width.blockSignals(True)
        spin_width.setValue(2000)
        spin_width.blockSignals(False)
        w.resetRatio() # since signals were blocked, we need to manually reset ratio
        spin_height.setValue(1000)
        self.assertEqual(spin_width.value(), 1000)
    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)
    def testLinkedWidgets(self):
        """ test linking spin boxes to combobox"""
        w = qgis.gui.QgsLayoutUnitsComboBox()
        self.assertFalse(w.converter())
        c = QgsLayoutMeasurementConverter()
        w.setConverter(c)
        self.assertEqual(w.converter(), c)

        spin = QDoubleSpinBox()
        spin.setMaximum(1000000)
        spin.setValue(100)
        w.setUnit(QgsUnitTypes.LayoutCentimeters)
        w.linkToWidget(spin)
        w.setUnit(QgsUnitTypes.LayoutMeters)
        self.assertAlmostEqual(spin.value(), 1.0, 2)
        w.setUnit(QgsUnitTypes.LayoutMillimeters)
        self.assertAlmostEqual(spin.value(), 1000.0, 2)

        spin2 = QDoubleSpinBox()
        spin2.setValue(50)
        spin2.setMaximum(1000000)
        w.linkToWidget(spin2)
        w.setUnit(QgsUnitTypes.LayoutCentimeters)
        self.assertAlmostEqual(spin.value(), 100.0, 2)
        self.assertAlmostEqual(spin2.value(), 5.0, 2)

        # no crash!
        del spin
        w.setUnit(QgsUnitTypes.LayoutMeters)
        self.assertAlmostEqual(spin2.value(), 0.05, 2)
Example #20
0
 def valueWidget(self, field, data):
     """
     Retrieves correct widget for a given field based on its type.
     :param field: (QgsField) field to be represented.
     :param data: (float/int/str/bool) initial data to be set to widget.
     :return: (QDoubleSpinBox/QSpinBox/QLineEdit/QCheckBox) the adequate
              widget for field.
     """
     if utils.fieldIsBool(field):
         # vWidget = QCheckBox()
         vWidget = self.centeredCheckBox()
         if not data is None:
             vWidget.cb.setChecked(data)
     elif utils.fieldIsFloat(field):
         vWidget = QDoubleSpinBox()
         vWidget.setMaximum(99999999)
         vWidget.setMinimum(-99999999)
         if data is not None:
             vWidget.setValue(data)
     elif utils.fieldIsInt(field):
         vWidget = QSpinBox()
         vWidget.setMaximum(99999999)
         vWidget.setMinimum(-99999999)
         if data is not None:
             vWidget.setValue(data)
     else:
         vWidget = QLineEdit()
         vWidget.setPlaceholderText(
             self.tr("Type the value for {0}").format(field.name()))
         if data is not None:
             vWidget.setText(data)
     return vWidget