Esempio n. 1
0
class TreeItemWithLink(QTreeWidgetItem):

    def __init__(self, parent, tree, text, linkText, linkColor="blue", icon=None):
        QTreeWidgetItem.__init__(self, parent)
        self.parent = parent
        self.tree = tree
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.label = QLabel()
        if icon and os.path.exists(icon):
            svg_renderer = QSvgRenderer(icon)
            image = QImage(32, 32, QImage.Format_ARGB32)
            # Set the ARGB to 0 to prevent rendering artifacts
            image.fill(0x00000000)
            svg_renderer.render(QPainter(image))
            pixmap = QPixmap.fromImage(image)
            icon = QIcon(pixmap)
            self.setIcon(0, icon)
            self.setSizeHint(0, QSize(32, 32))
        self.label.setText(text)
        layout.addWidget(self.label)
        if linkText:
            self.linkLabel = QLabel()
            self.linkLabel.setText("<a href='#' style='color: %s;'> %s</a>" % (linkColor, linkText))
            self.linkLabel.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
            layout.addWidget(self.linkLabel)
            self.linkLabel.linkActivated.connect(self.linkClicked)
        w = QWidget()
        w.setLayout(layout)
        self.tree.setItemWidget(self, 0, w)
Esempio n. 2
0
 def create_heading_label(text: str) -> QLabel:
     label = QLabel(text)
     sp = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Maximum)
     sp.setHorizontalStretch(0)
     sp.setVerticalStretch(0)
     sp.setHeightForWidth(label.sizePolicy().hasHeightForWidth())
     label.setSizePolicy(sp)
     label.setStyleSheet(
         "padding: 2px; font-weight: bold; background-color: rgb(200, 200, 200);"
     )
     return label
Esempio n. 3
0
 def setupFields(self):
     """
     Setups up all fields and fill up with available data on the attribute
     map.
     """
     utils = Utils()
     row = 0  # in case no fields are provided
     for row, f in enumerate(self.fields):
         fName = f.name()
         fMap = self.attributeMap[fName] if fName in self.attributeMap \
                     else None
         if fName in self.attributeMap:
             fMap = self.attributeMap[fName]
             if fMap["ignored"]:
                 w = QLineEdit()
                 w.setText(self.tr("Field is set to be ignored"))
                 value = None
                 enabled = False
             else:
                 value = fMap["value"]
                 enabled = fMap["editable"]
             if fMap["isPk"]:
                 # visually identify primary key attributes
                 text = '<p>{0} <img src=":/plugins/DsgTools/icons/key.png" '\
                        'width="16" height="16"></p>'.format(fName)
             else:
                 text = fName
         else:
             value = None
             enabled = True
             text = fName
         if fName in self.attributeMap and self.attributeMap[fName][
                 "ignored"]:
             pass
         elif utils.fieldIsFloat(f):
             w = QDoubleSpinBox()
             w.setValue(0 if value is None else value)
         elif utils.fieldIsInt(f):
             w = QSpinBox()
             w.setValue(0 if value is None else value)
         else:
             w = QLineEdit()
             w.setText("" if value is None else value)
         w.setEnabled(enabled)
         # also to make easier to read data
         self._fieldsWidgets[fName] = w
         label = QLabel(text)
         label.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
         w.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
         self.widgetsLayout.addWidget(label, row, 0)
         self.widgetsLayout.addWidget(w, row, 1)
     self.widgetsLayout.addItem(
         QSpacerItem(20, 40, QSizePolicy.Expanding, QSizePolicy.Expanding),
         row + 1, 1, 1, 2)  # row, col, rowSpan, colSpan
Esempio n. 4
0
    def do_post_offline_convert_action(self):
        """
        Show an information label that the project has been copied
        with a nice link to open the result folder.
        """
        export_folder = self.get_export_folder_from_dialog()

        result_label = QLabel(self.tr(u'Finished creating the project at {result_folder}. Please copy this folder to '
                                      u'your QField device.').format(
            result_folder=u'<a href="{folder}">{folder}</a>'.format(folder=export_folder)))
        result_label.setTextFormat(Qt.RichText)
        result_label.setTextInteractionFlags(Qt.TextBrowserInteraction)
        result_label.linkActivated.connect(lambda: open_folder(export_folder))
        result_label.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Preferred)

        self.iface.messageBar().pushWidget(result_label, Qgis.Info, 0)
Esempio n. 5
0
    def setup_default_preset(self):
        """Setup the display of presets"""
        preset_folder = resources_path('map_preset')
        folders = os.listdir(preset_folder)

        for folder_name in folders:
            file_path = join(preset_folder, folder_name, folder_name + '.json')
            with open(file_path, encoding='utf8') as json_file:
                data = json.load(json_file, object_hook=as_enum)

            item = QListWidgetItem(self.dialog.list_default_mp)
            item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsUserCheckable
                          | Qt.ItemIsEnabled)
            self.dialog.list_default_mp.addItem(item)

            widget = QFrame()
            widget.setFrameStyle(QFrame.StyledPanel)
            widget.setStyleSheet('QFrame { margin: 3px; };')
            widget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
            hbox = QHBoxLayout()
            vbox = QVBoxLayout()
            picture = QLabel()
            icon_path = resources_path('map_preset', folder_name,
                                       folder_name + '_icon.png')
            if not os.path.isfile(icon_path):
                icon_path = resources_path('icons', 'QuickOSM.svg')
            icon = QPixmap(icon_path)
            icon.scaled(QSize(150, 250), Qt.KeepAspectRatio)
            picture.setPixmap(icon)
            picture.setStyleSheet(
                'max-height: 150px; max-width: 250px; margin-right: 50px;')
            hbox.addWidget(picture)
            title = QLabel(data['file_name'])
            title.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
            title.setStyleSheet('font: bold 20px; margin-bottom: 25px;')
            vbox.addWidget(title)
            for label in data['description']:
                if not label:
                    label = tr('No description')
                real_label = QLabel(label)
                real_label.setWordWrap(True)
                vbox.addWidget(real_label)
            hbox.addItem(vbox)
            widget.setLayout(hbox)

            item.setSizeHint(widget.minimumSizeHint())
            self.dialog.list_default_mp.setItemWidget(item, widget)
Esempio n. 6
0
    def do_post_offline_convert_action(self):
        """
        Show an information label that the project has been copied
        with a nice link to open the result folder.
        """
        export_folder = self.get_export_folder_from_dialog()

        result_label = QLabel(
            self.
            tr(u'Finished creating the project at {result_folder}. Please copy this folder to '
               u'your QField device.').format(
                   result_folder=u'<a href="{folder}">{folder}</a>'.format(
                       folder=export_folder)))
        result_label.setTextFormat(Qt.RichText)
        result_label.setTextInteractionFlags(Qt.TextBrowserInteraction)
        result_label.linkActivated.connect(lambda: open_folder(export_folder))
        result_label.setSizePolicy(QSizePolicy.MinimumExpanding,
                                   QSizePolicy.Preferred)

        self.iface.messageBar().pushWidget(result_label, QgsMessageBar.INFO, 0)
Esempio n. 7
0
    def _creaFila(self, text1, text2):
        lbl1 = QLabel(text1)
        lbl2 = QLabel(text2)

        # Per si hi ha algun enllaç
        lbl1.setOpenExternalLinks(True)
        lbl2.setOpenExternalLinks(True)

        # SizePolicy
        lbl1.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
        lbl2.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)

        # Fonts
        # Fem una còpia de la font dels textos per posar-la en negreta
        fontNoms = QFont(QvConstants.FONTTEXT)
        fontNoms.setBold(True)
        lbl1.setFont(fontNoms)
        lbl2.setFont(QvConstants.FONTTEXT)

        self._lay.addWidget(lbl1, self._i, 0, Qt.AlignTop | Qt.AlignRight)
        self._lay.addWidget(lbl2, self._i, 1, Qt.AlignTop)

        self._i += 1
Esempio n. 8
0
class TreeSettingItem(QTreeWidgetItem):

    comboStyle = '''QComboBox {
                 border: 1px solid gray;
                 border-radius: 3px;
                 padding: 1px 18px 1px 3px;
                 min-width: 6em;
             }

             QComboBox::drop-down {
                 subcontrol-origin: padding;
                 subcontrol-position: top right;
                 width: 15px;
                 border-left-width: 1px;
                 border-left-color: darkgray;
                 border-left-style: solid;
                 border-top-right-radius: 3px;
                 border-bottom-right-radius: 3px;
             }
            '''

    def _addTextEdit(self, editable=True):
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.textEdit = QTextEdit()
        if not editable:
            self.textEdit.setReadOnly(True)
        self.textEdit.setPlainText(self._value)
        layout.addWidget(self.textEdit)
        w = QWidget()
        w.setLayout(layout)
        self.tree.setItemWidget(self, 1, w)

    def _addTextBoxWithLink(self, text, func, editable=True):
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.lineEdit = QLineEdit()
        if not editable:
            self.lineEdit.setReadOnly(True)
        self.lineEdit.setText(self._value)
        layout.addWidget(self.lineEdit)
        if text:
            self.linkLabel = QLabel()
            self.linkLabel.setText("<a href='#'> %s</a>" % text)
            self.linkLabel.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
            layout.addWidget(self.linkLabel)
            self.linkLabel.linkActivated.connect(func)
        w = QWidget()
        w.setLayout(layout)
        self.tree.setItemWidget(self, 1, w)

    def __init__(self, parent, tree, setting, namespace, value):
        QTreeWidgetItem.__init__(self, parent)
        self.parent = parent
        self.namespace = namespace
        self.tree = tree
        self._value = value
        self.setting = setting
        self.name = setting["name"]
        self.labelText = setting["label"]
        self.settingType = setting["type"]
        self.setText(0, self.labelText)
        if self.settingType == CRS:
            def edit():
                selector = QgsProjectionSelectionDialog()
                selector.setCrs(value);
                if selector.exec_():
                    crs = selector.crs()
                    if crs.upper().startswith("EPSG:"):
                        self.lineEdit.setText(crs)
            self._addTextBoxWithLink("Edit", edit, False)
        elif self.settingType == FILES:
            def edit():
                f = QFileDialog.getOpenFileNames(parent.treeWidget(), "Select file", "", "*.*")
                if f:
                    self.lineEdit.setText(",".join(f))
            self._addTextBoxWithLink("Browse", edit, True)
        elif self.settingType == FILE:
            def edit():
                f = QFileDialog.getOpenFileName(parent.treeWidget(), "Select file", "", "*.*")
                if f:
                    self.lineEdit.setText(f)
            self._addTextBoxWithLink("Browse", edit, True)
        elif self.settingType == FOLDER:
            def edit():
                f = QFileDialog.getExistingDirectory(parent.treeWidget(), "Select folder", "")
                if f:
                    self.lineEdit.setText(f)
            self._addTextBoxWithLink("Browse", edit, True)
        elif self.settingType == BOOL:
            if value:
                self.setCheckState(1, Qt.Checked)
            else:
                self.setCheckState(1, Qt.Unchecked)
        elif self.settingType == CHOICE:
            self.combo = QComboBox()
            self.combo.setStyleSheet(self.comboStyle)
            for option in setting["options"]:
                self.combo.addItem(option)
            self.tree.setItemWidget(self, 1, self.combo)
            idx = self.combo.findText(str(value))
            self.combo.setCurrentIndex(idx)
        elif self.settingType == TEXT:
            self._addTextEdit()
        elif self.settingType == STRING:
            self._addTextBoxWithLink(None, None)
        elif self.settingType == AUTHCFG:
            def edit():
                currentAuthCfg = self.value()
                dlg = AuthConfigSelectDialog(parent.treeWidget(), authcfg=currentAuthCfg)
                ret = dlg.exec_()
                if ret:
                    self.lineEdit.setText(dlg.authcfg)
            self._addTextBoxWithLink("Select", edit, True)
        else:
            self.setFlags(self.flags() | Qt.ItemIsEditable)
            self.setText(1, unicode(value))

    def saveValue(self):
        value = self.value()
        setPluginSetting(self.name, value, self.namespace)

    def value(self):
        self.setBackgroundColor(0, Qt.white)
        self.setBackgroundColor(1, Qt.white)
        try:
            if self.settingType == BOOL:
                return self.checkState(1) == Qt.Checked
            elif self.settingType == NUMBER:
                v = float(self.text(1))
                return v
            elif self.settingType == CHOICE:
                return self.combo.currentText()
            elif self.settingType in [TEXT]:
                return self.textEdit.toPlainText()
            elif self.settingType in [CRS, STRING, FILES, FOLDER, AUTHCFG]:
                return self.lineEdit.text()
            else:
                return self.text(1)
        except:
            self.setBackgroundColor(0, Qt.yellow)
            self.setBackgroundColor(1, Qt.yellow)
            raise WrongValueException()

    def setValue(self, value):
        if self.settingType == BOOL:
            if value:
                self.setCheckState(1, Qt.Checked)
            else:
                self.setCheckState(1, Qt.Unchecked)
        elif self.settingType == CHOICE:
            idx = self.combo.findText(str(value))
            self.combo.setCurrentIndex(idx)
        elif self.settingType in [TEXT, CRS, STRING, FILES, FOLDER, AUTHCFG]:
            self.lineEdit.setText(value)
        else:
            self.setText(1, unicode(value))

    def resetDefault(self):
        self.setValue(self.setting["default"])
    def show_current_state(self):
        """Setup the UI for QTextEdit to show the current state."""
        right_panel_heading = QLabel(tr('Status'))
        right_panel_heading.setFont(big_font)
        right_panel_heading.setSizePolicy(
            QSizePolicy.Maximum, QSizePolicy.Maximum)
        self.right_layout.addWidget(right_panel_heading)

        message = m.Message()
        if self.layer_mode == layer_mode_continuous:
            title = tr('Thresholds')
        else:
            title = tr('Value maps')

        message.add(m.Heading(title, **INFO_STYLE))

        for i in range(len(self.exposures)):
            message.add(m.Text(self.exposure_labels[i]))

            classification = self.get_classification(
                self.exposure_combo_boxes[i])
            if self.layer_mode == layer_mode_continuous:
                thresholds = self.thresholds.get(self.exposures[i]['key'])
                if not thresholds or not classification:
                    message.add(m.Paragraph(tr('No classifications set.')))
                    continue
                table = m.Table(
                    style_class='table table-condensed table-striped')
                header = m.Row()
                header.add(m.Cell(tr('Class name')))
                header.add(m.Cell(tr('Minimum')))
                header.add(m.Cell(tr('Maximum')))
                table.add(header)
                classes = classification.get('classes')
                # Sort by value, put the lowest first
                classes = sorted(classes, key=lambda k: k['value'])
                for the_class in classes:
                    threshold = thresholds[classification['key']]['classes'][
                        the_class['key']]
                    row = m.Row()
                    row.add(m.Cell(the_class['name']))
                    row.add(m.Cell(threshold[0]))
                    row.add(m.Cell(threshold[1]))
                    table.add(row)
            else:
                value_maps = self.value_maps.get(self.exposures[i]['key'])
                if not value_maps or not classification:
                    message.add(m.Paragraph(tr('No classifications set.')))
                    continue
                table = m.Table(
                    style_class='table table-condensed table-striped')
                header = m.Row()
                header.add(m.Cell(tr('Class name')))
                header.add(m.Cell(tr('Value')))
                table.add(header)
                classes = classification.get('classes')
                # Sort by value, put the lowest first
                classes = sorted(classes, key=lambda k: k['value'])
                for the_class in classes:
                    value_map = value_maps[classification['key']][
                        'classes'].get(the_class['key'], [])
                    row = m.Row()
                    row.add(m.Cell(the_class['name']))
                    row.add(m.Cell(', '.join([str(v) for v in value_map])))
                    table.add(row)
            message.add(table)

        # status_text_edit = QTextBrowser(None)
        status_text_edit = QWebView(None)
        status_text_edit.setSizePolicy(
            QSizePolicy.Ignored,
            QSizePolicy.Ignored)

        status_text_edit.page().mainFrame().setScrollBarPolicy(
            Qt.Horizontal,
            Qt.ScrollBarAlwaysOff)
        html_string = html_header() + message.to_html() + html_footer()
        status_text_edit.setHtml(html_string)
        self.right_layout.addWidget(status_text_edit)
class GroupSelectParameterWidget(GenericParameterWidget):

    """Widget class for Group Select Parameter."""

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

        :param parameter: A GroupSelectParameter object.
        :type parameter: GroupSelectParameter
        """
        QWidget.__init__(self, parent)
        self._parameter = parameter

        # Store spin box
        self.spin_boxes = {}

        # Create elements
        # Label (name)
        self.label = QLabel(self._parameter.name)

        # Layouts
        self.main_layout = QVBoxLayout()
        self.input_layout = QVBoxLayout()

        # _inner_input_layout must be filled with widget in the child class
        self.inner_input_layout = QVBoxLayout()

        self.radio_button_layout = QGridLayout()

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

        # List widget
        self.list_widget = QListWidget()
        self.list_widget.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.list_widget.setDragDropMode(QAbstractItemView.DragDrop)
        self.list_widget.setDefaultDropAction(Qt.MoveAction)
        self.list_widget.setEnabled(False)
        self.list_widget.setSizePolicy(
            QSizePolicy.Maximum, QSizePolicy.Expanding)

        for i, key in enumerate(self._parameter.options):
            value = self._parameter.options[key]
            radio_button = QRadioButton(value.get('label'))
            self.radio_button_layout.addWidget(radio_button, i, 0)
            if value.get('type') == SINGLE_DYNAMIC:
                percentage_spin_box = PercentageSpinBox(self)
                self.radio_button_layout.addWidget(percentage_spin_box, i, 1)
                percentage_spin_box.setValue(value.get('value', 0))
                step = percentage_spin_box.singleStep()
                if step > 1:
                    precision = 0
                else:
                    precision = len(str(step).split('.')[1])
                    if precision > 3:
                        precision = 3
                percentage_spin_box.setDecimals(precision)
                self.spin_boxes[key] = percentage_spin_box

                # Enable spin box depends on the selected option
                if self._parameter.selected == key:
                    percentage_spin_box.setEnabled(True)
                else:
                    percentage_spin_box.setEnabled(False)

            elif value.get('type') == STATIC:
                static_value = value.get('value', 0)
                if static_value is not None:
                    self.radio_button_layout.addWidget(
                        QLabel(str(static_value * 100) + ' %'), i, 1)
            elif value.get('type') == MULTIPLE_DYNAMIC:
                if self._parameter.selected == key:
                    self.list_widget.setEnabled(True)
                else:
                    self.list_widget.setEnabled(False)

            self.input_button_group.addButton(radio_button, i)
            if self._parameter.selected == key:
                radio_button.setChecked(True)

        # Help text
        self.help_label = QLabel(self._parameter.help_text)
        self.help_label.setSizePolicy(
            QSizePolicy.Maximum, QSizePolicy.Expanding)
        self.help_label.setWordWrap(True)
        self.help_label.setAlignment(Qt.AlignTop)

        self.inner_input_layout.addLayout(self.radio_button_layout)
        self.inner_input_layout.addWidget(self.list_widget)

        # Put elements into layouts
        self.input_layout.addWidget(self.label)
        self.input_layout.addLayout(self.inner_input_layout)

        self.help_layout = QVBoxLayout()
        self.help_layout.addWidget(self.help_label)

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

        self.setLayout(self.main_layout)

        self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Expanding)

        # Update list widget
        self.update_list_widget()

        # Connect signal
        # noinspection PyUnresolvedReferences
        self.input_button_group.buttonClicked.connect(
            self.radio_buttons_clicked)

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

        :returns: A DefaultValueParameter from the current state of widget
        :rtype: DefaultValueParameter
        """
        # Set value for each key
        for key, value in list(self._parameter.options.items()):
            if value.get('type') == STATIC:
                continue
            elif value.get('type') == SINGLE_DYNAMIC:
                new_value = self.spin_boxes.get(key).value()
                self._parameter.set_value_for_key(key, new_value)
            elif value.get('type') == MULTIPLE_DYNAMIC:
                # Need to iterate through all items
                items = []
                for index in range(self.list_widget.count()):
                    items.append(self.list_widget.item(index))
                new_value = [i.text() for i in items]
                self._parameter.set_value_for_key(key, new_value)

        # Get selected radio button
        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.selected = None
        else:
            self._parameter.selected = list(self._parameter.options.keys())[
                radio_button_checked_id]

        return self._parameter

    def update_list_widget(self):
        """Update list widget when radio button is clicked."""
        # Get selected radio button
        radio_button_checked_id = self.input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id > -1:
            selected_dict = list(self._parameter.options.values())[
                radio_button_checked_id]
            if selected_dict.get('type') == MULTIPLE_DYNAMIC:
                for field in selected_dict.get('value'):
                    # Update list widget
                    field_item = QListWidgetItem(self.list_widget)
                    field_item.setFlags(
                        Qt.ItemIsEnabled
                        | Qt.ItemIsSelectable
                        | Qt.ItemIsDragEnabled)
                    field_item.setData(Qt.UserRole, field)
                    field_item.setText(field)
                    self.list_widget.addItem(field_item)

    def radio_buttons_clicked(self):
        """Handler when selected radio button changed."""
        # Disable all spin boxes
        for spin_box in list(self.spin_boxes.values()):
            spin_box.setEnabled(False)
        # Disable list widget
        self.list_widget.setEnabled(False)

        # Get selected radio button
        radio_button_checked_id = self.input_button_group.checkedId()

        if radio_button_checked_id > -1:
            selected_value = list(self._parameter.options.values())[
                radio_button_checked_id]
            if selected_value.get('type') == MULTIPLE_DYNAMIC:
                # Enable list widget
                self.list_widget.setEnabled(True)
            elif selected_value.get('type') == SINGLE_DYNAMIC:
                selected_key = list(self._parameter.options.keys())[
                    radio_button_checked_id]
                self.spin_boxes[selected_key].setEnabled(True)

    def select_radio_button(self, key):
        """Helper to select a radio button with key.

        :param key: The key of the radio button.
        :type key: str
        """
        key_index = list(self._parameter.options.keys()).index(key)
        radio_button = self.input_button_group.button(key_index)
        radio_button.click()
class QmsSearchResultItemWidget(QWidget):
    def __init__(self, geoservice, image_ba, parent=None, extent_renderer=None):
        QWidget.__init__(self, parent)

        self.extent_renderer = extent_renderer

        self.layout = QHBoxLayout(self)
        self.layout.setContentsMargins(5, 10, 5, 10)
        self.setLayout(self.layout)

        self.service_icon = QLabel(self)
        self.service_icon.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.service_icon.resize(24, 24)

        qimg = QImage.fromData(image_ba)
        pixmap = QPixmap.fromImage(qimg)
        self.service_icon.setPixmap(pixmap)
        self.layout.addWidget(self.service_icon)

        self.service_desc_layout = QGridLayout(self)
        self.service_desc_layout.setSpacing(0)
        self.layout.addLayout(self.service_desc_layout)

        self.service_name = QLabel(self)
        self.service_name.setTextFormat(Qt.RichText)
        self.service_name.setWordWrap(True)
        self.service_name.setText(u"   <strong> {} </strong>".format(geoservice.get('name', u"")))
        self.service_desc_layout.addWidget(self.service_name, 0, 0, 1, 3)

        self.service_type = QLabel(self)
        self.service_type.setTextFormat(Qt.RichText)
        self.service_type.setWordWrap(True)
        self.service_type.setText(geoservice.get('type', u"").upper() + " ")
        self.service_desc_layout.addWidget(self.service_type, 1, 0)

        self.service_deteils = QLabel(self)
        self.service_deteils.setTextFormat(Qt.RichText)
        self.service_deteils.setWordWrap(True)
        self.service_deteils.setOpenExternalLinks(True)
        self.service_deteils.setText(u"<a href=\"{0}\">{1}</a>, ".format(
            Client().geoservice_info_url(geoservice.get('id', u"")),
            self.tr('details')
        ))
        self.service_desc_layout.addWidget(self.service_deteils, 1, 1)

        self.service_report = QLabel(self)
        self.service_report.setTextFormat(Qt.RichText)
        self.service_report.setWordWrap(True)
        self.service_report.setOpenExternalLinks(True)
        self.service_report.setText(u"<a href=\"{0}\">{1}</a><div/>".format(
            Client().geoservice_report_url(geoservice.get('id', u"")),
            self.tr('report a problem')
        ))
        self.service_desc_layout.addWidget(self.service_report, 1, 2)
        self.service_desc_layout.setColumnStretch(2, 1)


        self.status_label = QLabel(self)
        self.status_label.setTextFormat(Qt.RichText)
        self.status_label.setText(u'\u2022')


        status = geoservice.get('cumulative_status', u'')
        if status == 'works':
            self.status_label.setStyleSheet("color: green; font-size: 30px")
        if status == 'failed':
            self.status_label.setStyleSheet("color: red; font-size: 30px")
        if status == 'problematic':
            self.status_label.setStyleSheet("color: yellow; font-size: 30px")
        self.layout.addWidget(self.status_label)


        self.addButton = QToolButton()
        self.addButton.setText(self.tr("Add"))
        self.addButton.clicked.connect(self.addToMap)
        self.layout.addWidget(self.addButton)
        
        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)

        self.geoservice = geoservice
        self.image_ba = image_ba

    def addToMap(self):
        try:
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            client = Client()
            client.set_proxy(*QGISSettings.get_qgis_proxy())
            geoservice_info = client.get_geoservice_info(self.geoservice)
            ds = DataSourceSerializer.read_from_json(geoservice_info)
            add_layer_to_map(ds)

            CachedServices().add_service(self.geoservice, self.image_ba)
        except Exception as ex:
            plPrint(unicode(ex))
            pass
        finally:
            QApplication.restoreOverrideCursor()

    def mouseDoubleClickEvent(self, event):
        self.addToMap()

    def enterEvent(self, event):
        extent = self.geoservice.get('extent', None)
        if self.extent_renderer and extent:
            if ';' in extent:
                extent = extent.split(';')[1]
            geom = QgsGeometry.fromWkt(extent)
            self.extent_renderer.show_feature(geom)

    def leaveEvent(self, event):
        if self.extent_renderer:
            self.extent_renderer.clear_feature()
Esempio n. 12
0
class PhotoViewer(QScrollArea):
    """
    Widget for viewing images by incorporating basic navigation options.
    """
    def __init__(self, parent=None, photo_path=""):
        QScrollArea.__init__(self, parent)
        self.setBackgroundRole(QPalette.Dark)

        self._printer = QPrinter()

        self._lbl_photo = QLabel()
        self._lbl_photo.setBackgroundRole(QPalette.Base)
        self._lbl_photo.setSizePolicy(QSizePolicy.Ignored, QSizePolicy.Ignored)
        self._lbl_photo.setScaledContents(True)

        self.setWidget(self._lbl_photo)

        self._photo_path = photo_path
        self._ph_image = None
        self._scale_factor = 1.0
        self._aspect_ratio = -1

        self._create_actions()

        if self._photo_path:
            self.load_document(self._photo_path)

    def _create_actions(self):
        """
        Create actions for basic image navigation.
        """
        self._zoom_in_act = QAction(
            QApplication.translate("PhotoViewer", "Zoom &In (25%)"), self)
        self._zoom_in_act.setShortcut(
            QApplication.translate("PhotoViewer", "Ctrl++"))
        self._zoom_in_act.setEnabled(False)
        self._zoom_in_act.triggered.connect(self.zoom_in)

        self._zoom_out_act = QAction(
            QApplication.translate("PhotoViewer", "Zoom &Out (25%)"), self)
        self._zoom_out_act.setShortcut(
            QApplication.translate("PhotoViewer", "Ctrl+-"))
        self._zoom_out_act.setEnabled(False)
        self._zoom_out_act.triggered.connect(self.zoom_out)

        self._normal_size_act = QAction(
            QApplication.translate("PhotoViewer", "&Normal Size"), self)
        self._normal_size_act.setShortcut(
            QApplication.translate("PhotoViewer", "Ctrl+S"))
        self._normal_size_act.setEnabled(False)
        self._normal_size_act.triggered.connect(self.normal_size)

        self._fit_to_window_act = QAction(
            QApplication.translate("PhotoViewer", "&Fit to Window"), self)
        self._fit_to_window_act.setShortcut(
            QApplication.translate("PhotoViewer", "Ctrl+F"))
        self._fit_to_window_act.setEnabled(False)
        self._fit_to_window_act.setCheckable(True)
        self._fit_to_window_act.triggered.connect(self.fit_to_window)

        self._print_act = QAction(
            QApplication.translate("PhotoViewer", "&Print"), self)
        self._print_act.setShortcut(
            QApplication.translate("PhotoViewer", "Ctrl+P"))
        self._print_act.setEnabled(False)
        self._print_act.triggered.connect(self.print_photo)

    def zoom_in(self):
        self.scale_photo(1.25)

    def zoom_out(self):
        self.scale_photo(0.8)

    def normal_size(self):
        self._lbl_photo.adjustSize()
        self._scale_factor = 1.0

    def fit_to_window(self):
        fit_to_win = self._fit_to_window_act.isChecked()
        self.setWidgetResizable(fit_to_win)

        if not fit_to_win:
            self.normal_size()

        self.update_actions()

    def print_photo(self):
        print_dialog = QPrintDialog(self._printer, self)

        if print_dialog.exec_() == QDialog.Accepted:
            painter = QPainter(self._printer)
            rect = painter.viewport()
            size = self._lbl_photo.pixmap().size()
            size.scale(rect.size(), Qt.KeepAspectRatio)
            painter.setViewport(rect.x(), rect.y(), size.width(),
                                size.height())
            painter.setWindow(self._lbl_photo.pixmap().rect())
            painter.drawPixmap(0, 0, self._lbl_photo.pixmap())

    def wheelEvent(self, event):
        """
        Zoom the image based on the mouse wheel rotation action.
        :param event: Event containing the wheel rotation info.
        :type event: QWheelEvent
        """
        degrees = event.delta() / 8
        num_steps = degrees / 15

        if num_steps < 0:
            abs_num_steps = abs(num_steps)
            zoom_factor = 1 + (abs_num_steps * 0.25)

        else:
            zoom_factor = 1 - (num_steps * 0.2)

        self.scale_photo(zoom_factor)

    def heightForWidth(self, width):
        if self._aspect_ratio != -1:
            return width / self._aspect_ratio

        else:
            return -1

    def resizeEvent(self, event):
        """
        Event for resizing the widget based on the pixmap's aspect ratio.
        :param event: Contains event parameters for the resize event.
        :type event: QResizeEvent
        """
        super(PhotoViewer, self).resizeEvent(event)

    def update_actions(self):
        self._zoom_out_act.setEnabled(not self._fit_to_window_act.isChecked())
        self._zoom_in_act.setEnabled(not self._fit_to_window_act.isChecked())
        self._normal_size_act.setEnabled(
            not self._fit_to_window_act.isChecked())

    def scale_photo(self, factor):
        """
        :param factor: Value by which the image will be increased/decreased in the view.
        :type factor: float
        """
        if not self._lbl_photo.pixmap().isNull():
            self._scale_factor *= factor
            self._lbl_photo.resize(self._scale_factor *
                                   self._lbl_photo.pixmap().size())

            self._adjust_scroll_bar(self.horizontalScrollBar(), factor)
            self._adjust_scroll_bar(self.verticalScrollBar(), factor)

            self._zoom_in_act.setEnabled(self._scale_factor < 3.0)
            self._zoom_out_act.setEnabled(self._scale_factor > 0.333)

    def _adjust_scroll_bar(self, scroll_bar, factor):
        scroll_bar.setValue(
            int(factor * scroll_bar.value() +
                ((factor - 1) * scroll_bar.pageStep() / 2)))

    def load_document(self, photo_path):
        if photo_path:
            self._ph_image = QImage(photo_path)

            if self._ph_image.isNull():
                return False

            self._photo_path = photo_path

            ph_pixmap = QPixmap.fromImage(self._ph_image)

            self._lbl_photo.setPixmap(ph_pixmap)
            self._scale_factor = 1.0

            self._aspect_ratio = ph_pixmap.width() / ph_pixmap.height()

            self._fit_to_window_act.setEnabled(True)
            self._print_act.setEnabled(True)
            self._fit_to_window_act.trigger()

            self.update_actions()
            return ph_pixmap

        return True

    def photo_location(self):
        """
        :returns: Absolute path of the photo in the central document repository.
        """
        return self._photo_path

    def set_actions(self, menu):
        """
        Add custom actions to the sub-window menu
        """
        menu.addSeparator()
        menu.addAction(self._zoom_in_act)
        menu.addAction(self._zoom_out_act)
        menu.addAction(self._normal_size_act)
        menu.addAction(self._fit_to_window_act)
        menu.addSeparator()
        menu.addAction(self._print_act)
Esempio n. 13
0
    def construct_form_param_system(self, row, pos):

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

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

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

                # Order Widgets
                if 'layoutname' in field:
                    if field['layoutname'] == 'lyt_topology':
                        self.order_widgets_system(field, self.topology_form,
                                                  lbl, widget)
                    elif field['layoutname'] == 'lyt_builder':
                        self.order_widgets_system(field, self.builder_form,
                                                  lbl, widget)
                    elif field['layoutname'] == 'lyt_review':
                        self.order_widgets_system(field, self.review_form, lbl,
                                                  widget)
                    elif field['layoutname'] == 'lyt_analysis':
                        self.order_widgets_system(field, self.analysis_form,
                                                  lbl, widget)
                    elif field['layoutname'] == 'lyt_system':
                        self.order_widgets_system(field, self.system_form, lbl,
                                                  widget)
Esempio n. 14
0
class QmsSearchResultItemWidget(QWidget):
    def __init__(self,
                 geoservice,
                 image_ba,
                 parent=None,
                 extent_renderer=None):
        QWidget.__init__(self, parent)

        self.extent_renderer = extent_renderer

        self.layout = QHBoxLayout(self)
        self.layout.setContentsMargins(5, 10, 5, 10)
        self.setLayout(self.layout)

        self.service_icon = QLabel(self)
        self.service_icon.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        self.service_icon.resize(24, 24)

        qimg = QImage.fromData(image_ba)
        pixmap = QPixmap.fromImage(qimg)
        self.service_icon.setPixmap(pixmap)
        self.layout.addWidget(self.service_icon)

        self.service_desc_layout = QGridLayout(self)
        self.service_desc_layout.setSpacing(0)
        self.layout.addLayout(self.service_desc_layout)

        self.service_name = QLabel(self)
        self.service_name.setTextFormat(Qt.RichText)
        self.service_name.setWordWrap(True)
        self.service_name.setText(u"   <strong> {} </strong>".format(
            geoservice.get('name', u"")))
        self.service_desc_layout.addWidget(self.service_name, 0, 0, 1, 3)

        self.service_type = QLabel(self)
        self.service_type.setTextFormat(Qt.RichText)
        self.service_type.setWordWrap(True)
        self.service_type.setText(geoservice.get('type', u"").upper() + " ")
        self.service_desc_layout.addWidget(self.service_type, 1, 0)

        self.service_deteils = QLabel(self)
        self.service_deteils.setTextFormat(Qt.RichText)
        self.service_deteils.setWordWrap(True)
        self.service_deteils.setOpenExternalLinks(True)
        self.service_deteils.setText(u"<a href=\"{0}\">{1}</a>, ".format(
            Client().geoservice_info_url(geoservice.get('id', u"")),
            self.tr('details')))
        self.service_desc_layout.addWidget(self.service_deteils, 1, 1)

        self.service_report = QLabel(self)
        self.service_report.setTextFormat(Qt.RichText)
        self.service_report.setWordWrap(True)
        self.service_report.setOpenExternalLinks(True)
        self.service_report.setText(u"<a href=\"{0}\">{1}</a><div/>".format(
            Client().geoservice_report_url(geoservice.get('id', u"")),
            self.tr('report a problem')))
        self.service_desc_layout.addWidget(self.service_report, 1, 2)
        self.service_desc_layout.setColumnStretch(2, 1)

        self.status_label = QLabel(self)
        self.status_label.setTextFormat(Qt.RichText)
        self.status_label.setText(u'\u2022')

        status = geoservice.get('cumulative_status', u'')
        if status == 'works':
            self.status_label.setStyleSheet("color: green; font-size: 30px")
        if status == 'failed':
            self.status_label.setStyleSheet("color: red; font-size: 30px")
        if status == 'problematic':
            self.status_label.setStyleSheet("color: yellow; font-size: 30px")
        self.layout.addWidget(self.status_label)

        self.addButton = QToolButton()
        self.addButton.setText(self.tr("Add"))
        self.addButton.clicked.connect(self.addToMap)
        self.layout.addWidget(self.addButton)

        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum)

        self.geoservice = geoservice
        self.image_ba = image_ba

    def addToMap(self):
        try:
            QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
            client = Client()
            client.set_proxy(*QGISSettings.get_qgis_proxy())
            geoservice_info = client.get_geoservice_info(self.geoservice)
            ds = DataSourceSerializer.read_from_json(geoservice_info)
            add_layer_to_map(ds)

            CachedServices().add_service(self.geoservice, self.image_ba)
        except Exception as ex:
            plPrint(unicode(ex))
            pass
        finally:
            QApplication.restoreOverrideCursor()

    def mouseDoubleClickEvent(self, event):
        self.addToMap()

    def enterEvent(self, event):
        extent = self.geoservice.get('extent', None)
        if self.extent_renderer and extent:
            if ';' in extent:
                extent = extent.split(';')[1]
            geom = QgsGeometry.fromWkt(extent)
            self.extent_renderer.show_feature(geom)

    def leaveEvent(self, event):
        if self.extent_renderer:
            self.extent_renderer.clear_feature()
    def show_current_state(self):
        """Setup the UI for QTextEdit to show the current state."""
        right_panel_heading = QLabel(tr('Status'))
        right_panel_heading.setFont(big_font)
        right_panel_heading.setSizePolicy(
            QSizePolicy.Maximum, QSizePolicy.Maximum)
        self.right_layout.addWidget(right_panel_heading)

        message = m.Message()
        if self.layer_mode == layer_mode_continuous:
            title = tr('Thresholds')
        else:
            title = tr('Value maps')

        message.add(m.Heading(title, **INFO_STYLE))

        for i in range(len(self.exposures)):
            message.add(m.Text(self.exposure_labels[i]))

            classification = self.get_classification(
                self.exposure_combo_boxes[i])
            if self.layer_mode == layer_mode_continuous:
                thresholds = self.thresholds.get(self.exposures[i]['key'])
                if not thresholds or not classification:
                    message.add(m.Paragraph(tr('No classifications set.')))
                    continue
                table = m.Table(
                    style_class='table table-condensed table-striped')
                header = m.Row()
                header.add(m.Cell(tr('Class name')))
                header.add(m.Cell(tr('Minimum')))
                header.add(m.Cell(tr('Maximum')))
                table.add(header)
                classes = classification.get('classes')
                # Sort by value, put the lowest first
                classes = sorted(classes, key=lambda k: k['value'])
                for the_class in classes:
                    threshold = thresholds[classification['key']]['classes'][
                        the_class['key']]
                    row = m.Row()
                    row.add(m.Cell(the_class['name']))
                    row.add(m.Cell(threshold[0]))
                    row.add(m.Cell(threshold[1]))
                    table.add(row)
            else:
                value_maps = self.value_maps.get(self.exposures[i]['key'])
                if not value_maps or not classification:
                    message.add(m.Paragraph(tr('No classifications set.')))
                    continue
                table = m.Table(
                    style_class='table table-condensed table-striped')
                header = m.Row()
                header.add(m.Cell(tr('Class name')))
                header.add(m.Cell(tr('Value')))
                table.add(header)
                classes = classification.get('classes')
                # Sort by value, put the lowest first
                classes = sorted(classes, key=lambda k: k['value'])
                for the_class in classes:
                    value_map = value_maps[classification['key']][
                        'classes'].get(the_class['key'], [])
                    row = m.Row()
                    row.add(m.Cell(the_class['name']))
                    row.add(m.Cell(', '.join([str(v) for v in value_map])))
                    table.add(row)
            message.add(table)

        # status_text_edit = QTextBrowser(None)
        status_text_edit = QWebView(None)
        status_text_edit.setSizePolicy(
            QSizePolicy.Ignored,
            QSizePolicy.Ignored)

        status_text_edit.page().mainFrame().setScrollBarPolicy(
            Qt.Horizontal,
            Qt.ScrollBarAlwaysOff)
        html_string = html_header() + message.to_html() + html_footer()
        status_text_edit.setHtml(html_string)
        self.right_layout.addWidget(status_text_edit)
Esempio n. 16
0
class Ui_DistroMap(object):
    def setupUi(self, DistroMap):
        DistroMap.setObjectName("DistroMap")
        DistroMap.resize(439, 657)
        self.gridLayout_3 = QGridLayout(DistroMap)
        self.gridLayout_3.setObjectName("gridLayout_3")
        self.scrollArea = QScrollArea(DistroMap)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QWidget()
        self.scrollAreaWidgetContents.setGeometry(QRect(0, 0, 419, 573))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.gridLayout_6 = QGridLayout(self.scrollAreaWidgetContents)
        self.gridLayout_6.setObjectName("gridLayout_6")
        self.verticalLayout = QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.label_5 = QLabel(self.scrollAreaWidgetContents)
        self.label_5.setObjectName("label_5")
        self.verticalLayout.addWidget(self.label_5)
        self.comboLocalities = QComboBox(self.scrollAreaWidgetContents)
        self.comboLocalities.setObjectName("comboLocalities")
        self.verticalLayout.addWidget(self.comboLocalities)
        self.gridLayout_6.addLayout(self.verticalLayout, 1, 0, 1, 1)
        self.horizontalLayout_6 = QHBoxLayout()
        self.horizontalLayout_6.setObjectName("horizontalLayout_6")
        self.verticalLayout_13 = QVBoxLayout()
        self.verticalLayout_13.setObjectName("verticalLayout_13")
        self.label_19 = QLabel(self.scrollAreaWidgetContents)
        self.label_19.setObjectName("label_19")
        self.verticalLayout_13.addWidget(self.label_19)
        self.horizontalLayout_3 = QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.spnOutWidth = QSpinBox(self.scrollAreaWidgetContents)
        self.spnOutWidth.setMaximum(999999)
        self.spnOutWidth.setProperty("value", 325)
        self.spnOutWidth.setObjectName("spnOutWidth")
        self.horizontalLayout_3.addWidget(self.spnOutWidth)
        self.label_20 = QLabel(self.scrollAreaWidgetContents)
        self.label_20.setAlignment(Qt.AlignCenter)
        self.label_20.setObjectName("label_20")
        self.horizontalLayout_3.addWidget(self.label_20)
        self.spnOutHeight = QSpinBox(self.scrollAreaWidgetContents)
        self.spnOutHeight.setMaximum(999999)
        self.spnOutHeight.setProperty("value", 299)
        self.spnOutHeight.setObjectName("spnOutHeight")
        self.horizontalLayout_3.addWidget(self.spnOutHeight)
        self.verticalLayout_13.addLayout(self.horizontalLayout_3)
        self.horizontalLayout_6.addLayout(self.verticalLayout_13)
        self.horizontalLayout_5 = QHBoxLayout()
        self.horizontalLayout_5.setObjectName("horizontalLayout_5")
        self.verticalLayout_14 = QVBoxLayout()
        self.verticalLayout_14.setObjectName("verticalLayout_14")
        self.label_21 = QLabel(self.scrollAreaWidgetContents)
        sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label_21.sizePolicy().hasHeightForWidth())
        self.label_21.setSizePolicy(sizePolicy)
        self.label_21.setAlignment(Qt.AlignRight|Qt.AlignTrailing|Qt.AlignVCenter)
        self.label_21.setObjectName("label_21")
        self.verticalLayout_14.addWidget(self.label_21)
        self.horizontalLayout_4 = QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        spacerItem = QSpacerItem(40, 20, QSizePolicy.Expanding, QSizePolicy.Minimum)
        self.horizontalLayout_4.addItem(spacerItem)
        self.btnColour = QPushButton(self.scrollAreaWidgetContents)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.btnColour.sizePolicy().hasHeightForWidth())
        self.btnColour.setSizePolicy(sizePolicy)
        self.btnColour.setObjectName("btnColour")
        self.horizontalLayout_4.addWidget(self.btnColour)
        self.verticalLayout_14.addLayout(self.horizontalLayout_4)
        self.horizontalLayout_5.addLayout(self.verticalLayout_14)
        self.frmColour = QFrame(self.scrollAreaWidgetContents)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.frmColour.sizePolicy().hasHeightForWidth())
        self.frmColour.setSizePolicy(sizePolicy)
        self.frmColour.setMinimumSize(QSize(45, 45))
        self.frmColour.setSizeIncrement(QSize(1, 1))
        self.frmColour.setBaseSize(QSize(0, 0))
        self.frmColour.setFrameShape(QFrame.StyledPanel)
        self.frmColour.setFrameShadow(QFrame.Raised)
        self.frmColour.setObjectName("frmColour")
        self.horizontalLayout_5.addWidget(self.frmColour)
        self.horizontalLayout_6.addLayout(self.horizontalLayout_5)
        self.gridLayout_6.addLayout(self.horizontalLayout_6, 4, 0, 1, 1)
        self.verticalLayout_2 = QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.label_6 = QLabel(self.scrollAreaWidgetContents)
        self.label_6.setObjectName("label_6")
        self.verticalLayout_2.addWidget(self.label_6)
        self.comboTaxonField = QComboBox(self.scrollAreaWidgetContents)
        self.comboTaxonField.setObjectName("comboTaxonField")
        self.verticalLayout_2.addWidget(self.comboTaxonField)
        self.gridLayout_6.addLayout(self.verticalLayout_2, 2, 0, 1, 1)
        self.verticalLayout_5 = QVBoxLayout()
        self.verticalLayout_5.setObjectName("verticalLayout_5")
        self.label_9 = QLabel(self.scrollAreaWidgetContents)
        self.label_9.setObjectName("label_9")
        self.verticalLayout_5.addWidget(self.label_9)
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.leOutDir = QLineEdit(self.scrollAreaWidgetContents)
        self.leOutDir.setPlaceholderText("")
        self.leOutDir.setObjectName("leOutDir")
        self.horizontalLayout.addWidget(self.leOutDir)
        self.btnBrowse = QPushButton(self.scrollAreaWidgetContents)
        self.btnBrowse.setObjectName("btnBrowse")
        self.horizontalLayout.addWidget(self.btnBrowse)
        self.verticalLayout_5.addLayout(self.horizontalLayout)
        self.gridLayout_6.addLayout(self.verticalLayout_5, 5, 0, 1, 1)
        self.verticalLayout_6 = QVBoxLayout()
        self.verticalLayout_6.setObjectName("verticalLayout_6")
        self.label = QLabel(self.scrollAreaWidgetContents)
        self.label.setObjectName("label")
        self.verticalLayout_6.addWidget(self.label)
        self.gridLayout = QGridLayout()
        self.gridLayout.setObjectName("gridLayout")
        self.label_2 = QLabel(self.scrollAreaWidgetContents)
        self.label_2.setObjectName("label_2")
        self.gridLayout.addWidget(self.label_2, 0, 0, 1, 1)
        self.comboSecondary = QComboBox(self.scrollAreaWidgetContents)
        self.comboSecondary.setObjectName("comboSecondary")
        self.gridLayout.addWidget(self.comboSecondary, 1, 1, 1, 1)
        self.comboSurface = QComboBox(self.scrollAreaWidgetContents)
        self.comboSurface.setObjectName("comboSurface")
        self.gridLayout.addWidget(self.comboSurface, 2, 1, 1, 1)
        self.label_3 = QLabel(self.scrollAreaWidgetContents)
        self.label_3.setObjectName("label_3")
        self.gridLayout.addWidget(self.label_3, 1, 0, 1, 1)
        self.label_4 = QLabel(self.scrollAreaWidgetContents)
        self.label_4.setObjectName("label_4")
        self.gridLayout.addWidget(self.label_4, 2, 0, 1, 1)
        self.comboBase = QComboBox(self.scrollAreaWidgetContents)
        self.comboBase.setObjectName("comboBase")
        self.gridLayout.addWidget(self.comboBase, 0, 1, 1, 1)
        self.gridLayout.setColumnStretch(0, 1)
        self.gridLayout.setColumnStretch(1, 3)
        self.verticalLayout_6.addLayout(self.gridLayout)
        self.gridLayout_6.addLayout(self.verticalLayout_6, 0, 0, 1, 1)
        self.verticalLayout_3 = QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.label_7 = QLabel(self.scrollAreaWidgetContents)
        self.label_7.setObjectName("label_7")
        self.verticalLayout_3.addWidget(self.label_7)
        self.comboGrid = QComboBox(self.scrollAreaWidgetContents)
        self.comboGrid.setObjectName("comboGrid")
        self.verticalLayout_3.addWidget(self.comboGrid)
        self.verticalLayout_4 = QVBoxLayout()
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.label_8 = QLabel(self.scrollAreaWidgetContents)
        self.label_8.setObjectName("label_8")
        self.verticalLayout_4.addWidget(self.label_8)
        self.gridLayout_2 = QGridLayout()
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.leMaxY = QLineEdit(self.scrollAreaWidgetContents)
        self.leMaxY.setObjectName("leMaxY")
        self.gridLayout_2.addWidget(self.leMaxY, 0, 1, 1, 1)
        self.leMinX = QLineEdit(self.scrollAreaWidgetContents)
        self.leMinX.setObjectName("leMinX")
        self.gridLayout_2.addWidget(self.leMinX, 1, 0, 1, 1)
        self.leMaxX = QLineEdit(self.scrollAreaWidgetContents)
        self.leMaxX.setObjectName("leMaxX")
        self.gridLayout_2.addWidget(self.leMaxX, 1, 2, 1, 1)
        self.leMinY = QLineEdit(self.scrollAreaWidgetContents)
        self.leMinY.setObjectName("leMinY")
        self.gridLayout_2.addWidget(self.leMinY, 2, 1, 1, 1)
        self.btnExtent = QPushButton(self.scrollAreaWidgetContents)
        self.btnExtent.setObjectName("btnExtent")
        self.gridLayout_2.addWidget(self.btnExtent, 1, 1, 1, 1)
        self.verticalLayout_4.addLayout(self.gridLayout_2)
        self.verticalLayout_3.addLayout(self.verticalLayout_4)
        self.gridLayout_6.addLayout(self.verticalLayout_3, 3, 0, 1, 1)
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.gridLayout_3.addWidget(self.scrollArea, 0, 0, 1, 1)
        self.buttonBox = QDialogButtonBox(DistroMap)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        self.gridLayout_3.addWidget(self.buttonBox, 2, 0, 1, 1)
        self.progressBar = QProgressBar(DistroMap)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setObjectName("progressBar")
        self.gridLayout_3.addWidget(self.progressBar, 1, 0, 1, 1)

        self.retranslateUi(DistroMap)
        self.buttonBox.rejected.connect(DistroMap.reject)
        QMetaObject.connectSlotsByName(DistroMap)

    def retranslateUi(self, DistroMap):
        DistroMap.setWindowTitle(QApplication.translate("DistroMap", "Distribution Map Generator", None))
        self.label_5.setText(QApplication.translate("DistroMap", "Point localities layer", None))
        self.label_19.setText(QApplication.translate("DistroMap", "Output resolution", None))
        self.label_20.setText(QApplication.translate("DistroMap", "x", None))
        self.label_21.setText(QApplication.translate("DistroMap", "Map background", None))
        self.btnColour.setText(QApplication.translate("DistroMap", "Change", None))
        self.label_6.setText(QApplication.translate("DistroMap", "Taxon identifier field", None))
        self.label_9.setText(QApplication.translate("DistroMap", "Output directory", None))
        self.btnBrowse.setText(QApplication.translate("DistroMap", "Browse...", None))
        self.label.setText(QApplication.translate("DistroMap", "Background layers:", None))
        self.label_2.setText(QApplication.translate("DistroMap", "Base", None))
        self.label_3.setText(QApplication.translate("DistroMap", "Secondary", None))
        self.label_4.setText(QApplication.translate("DistroMap", "Surface", None))
        self.label_7.setText(QApplication.translate("DistroMap", "Grid layer", None))
        self.label_8.setText(QApplication.translate("DistroMap", "Output extent:", None))
        self.leMaxY.setText(QApplication.translate("DistroMap", "-21.00", None))
        self.leMinX.setText(QApplication.translate("DistroMap", "14.75", None))
        self.leMaxX.setText(QApplication.translate("DistroMap", "34.00", None))
        self.leMinY.setText(QApplication.translate("DistroMap", "-36.00", None))
        self.btnExtent.setText(QApplication.translate("DistroMap", "Use current", None))
Esempio n. 17
0
class LayerItem(QTreeWidgetItem):

    NOT_EXPORTED, NOT_IN_SYNC, IN_SYNC = list(range(3))

    def __init__(self, tree, parent, repo, layer, branch, branchCommitId):
        QTreeWidgetItem.__init__(self, parent)
        self.repo = repo
        self.tree = tree
        self.layer = layer
        self.branch = branch
        self.currentCommitId = None
        self.setIcon(0, layerIcon)

        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.label = QLabel()
        self.label.setText(layer)
        self.labelLinks = QLabel()
        self.labelLinks.setText("<a href='#'>Add to QGIS</a>")
        self.label.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        layout.addWidget(self.label)
        layout.addWidget(self.labelLinks)
        layout.addStretch()

        def add():
            if self.status == self.NOT_IN_SYNC:
                msgBox = QMessageBox()
                msgBox.setText(
                    "This layer was exported already at a different version.\nWhich version would you like to add to your QGIS project?"
                )
                msgBox.addButton(QPushButton('Use exported version'),
                                 QMessageBox.YesRole)
                msgBox.addButton(QPushButton('Use version from this branch'),
                                 QMessageBox.NoRole)
                msgBox.addButton(QPushButton('Cancel'), QMessageBox.RejectRole)
                QApplication.restoreOverrideCursor()
                ret = msgBox.exec_()
                if ret == 0:
                    checkoutLayer(self.repo, self.layer, None,
                                  self.currentCommitId)
                elif ret == 1:
                    try:
                        layer = checkoutLayer(self.repo, self.layer, None,
                                              branchCommitId)
                        repoWatcher.layerUpdated.emit(layer)
                    except HasLocalChangesError:
                        QMessageBox.warning(
                            config.iface.mainWindow(), 'Cannot change version',
                            "There are local changes that would be overwritten.\n"
                            "Revert them before changing version.",
                            QMessageBox.Ok)
            else:
                checkoutLayer(self.repo, self.layer, None, branchCommitId)

        self.labelLinks.linkActivated.connect(add)
        w = QWidget()
        w.setLayout(layout)
        self.tree.setItemWidget(self, 0, w)

        self.status = self.NOT_EXPORTED
        trackedlayer = getTrackingInfoForGeogigLayer(self.repo.url, layer)
        if trackedlayer:
            try:
                con = sqlite3.connect(trackedlayer.geopkg)
                cursor = con.cursor()
                cursor.execute(
                    "SELECT commit_id FROM geogig_audited_tables WHERE table_name='%s';"
                    % layer)
                self.currentCommitId = cursor.fetchone()[0]
                cursor.close()
                con.close()
                if branchCommitId == self.currentCommitId:
                    self.status = self.IN_SYNC
                else:
                    self.status = self.NOT_IN_SYNC
                    self.label.setText("<font color='orange'>%s</font>" %
                                       layer)
            except:
                pass
Esempio n. 18
0
class ProgressDialog(QDialog):
    """ Progress dialog shows progress bar for algorithm.
    """

    def __init__(self, iface):
        QDialog.__init__(self, iface.mainWindow())
        self.workerThread = None
        self.state = False
        self.resultStatus = None
        self.doReRun = False
        self.wasCanceled = False
        self.wasSuccessful = False
        self.savedProj = None
        self.result = None
        self.messageTxt = {
            'msg_optimierung': self.tr('Berechnung der optimalen Stuetzenpositionen...'),
            'msg_seillinie': self.tr('Berechnung der optimale Seillinie...')
        }
        
        # Build GUI Elements
        self.setWindowTitle(self.tr("SEILAPLAN wird ausgefuehrt"))
        self.resize(500, 100)
        self.container = QVBoxLayout()
        self.progressBar = QProgressBar(self)
        self.progressBar.setMinimumWidth(500)
        self.statusLabel = QLabel(self)
        self.hbox = QHBoxLayout()
        self.cancelButton = QDialogButtonBox()
        self.closeButton = QDialogButtonBox()
        self.resultLabel = QLabel(self)
        self.resultLabel.setMaximumWidth(500)
        self.resultLabel.setSizePolicy(
            QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding))
        self.resultLabel.setWordWrap(True)
        spacer1 = QSpacerItem(20, 20, QSizePolicy.Fixed,
                              QSizePolicy.Fixed)
        self.rerunButton = QPushButton(self.tr("zurueck zum Startfenster"))
        self.rerunButton.setVisible(False)
        spacer2 = QSpacerItem(40, 20, QSizePolicy.Expanding,
                             QSizePolicy.Minimum)
        self.cancelButton.setStandardButtons(QDialogButtonBox.Cancel)
        self.cancelButton.button(QDialogButtonBox.Cancel).setText(self.tr("Abbrechen"))
        self.cancelButton.clicked.connect(self.onAbort)
        self.closeButton.setStandardButtons(QDialogButtonBox.Close)
        self.closeButton.button(QDialogButtonBox.Close).setText(self.tr("Schliessen"))
        self.closeButton.clicked.connect(self.onClose)
        self.hbox.addWidget(self.rerunButton)
        self.hbox.addItem(spacer2)
        self.hbox.addWidget(self.cancelButton)
        self.hbox.setAlignment(self.cancelButton, Qt.AlignHCenter)
        self.hbox.addWidget(self.closeButton)
        self.hbox.setAlignment(self.closeButton, Qt.AlignHCenter)
        self.closeButton.hide()
        
        self.container.addWidget(self.progressBar)
        self.container.addWidget(self.statusLabel)
        self.container.addWidget(self.resultLabel)
        self.container.addItem(spacer1)
        self.container.addLayout(self.hbox)
        self.container.setSizeConstraint(QLayout.SetFixedSize)
        self.setLayout(self.container)

    # noinspection PyMethodMayBeStatic
    def tr(self, message, **kwargs):
        """Get the translation for a string using Qt translation API.
        We implement this ourselves since we do not inherit QObject.

        :param message: String for translation.
        :type message: str, QString

        :returns: Translated version of message.
        :rtype: QString

        Parameters
        ----------
        **kwargs
        """
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate(type(self).__name__, message)
        
    def setThread(self, workerThread):
        self.workerThread = workerThread
        self.connectThreadSignals()
    
    def connectThreadSignals(self):
        # Connect signals of thread
        self.workerThread.sig_jobEnded.connect(self.jobEnded)
        self.workerThread.sig_jobError.connect(self.onError)
        self.workerThread.sig_value.connect(self.valueFromThread)
        self.workerThread.sig_range.connect(self.rangeFromThread)
        self.workerThread.sig_text.connect(self.textFromThread)
        self.workerThread.sig_result.connect(self.resultFromThread)
        self.rerunButton.clicked.connect(self.onRerun)
        
    def run(self):
        # Show modal dialog window (QGIS is still responsive)
        self.show()
        # start event loop
        self.exec()
    
    def jobEnded(self, success):
        self.setWindowTitle("SEILAPLAN")
        if success:
            self.progressBar.setValue(self.progressBar.maximum())
            self.wasSuccessful = True
            # Close progress dialog so that adjustment window can be opened
            self.close()
        else:  # If there was an abort by the user
            self.statusLabel.setText(self.tr("Berechnungen abgebrochen."))
            self.progressBar.setValue(self.progressBar.minimum())
            self.finallyDo()
    
    def valueFromThread(self, value):
        self.progressBar.setValue(int(value))
    
    def rangeFromThread(self, range_vals):
        self.progressBar.setRange(int(round(range_vals[0])), int(round(range_vals[1])))
    
    def maxFromThread(self, max):
        self.progressBar.setValue(self.progressBar.maximum())
    
    def textFromThread(self, message):
        self.statusLabel.setText(self.messageTxt[message])
    
    def resultFromThread(self, resultStatus):
        self.resultStatus = resultStatus
        # resultStatus:
        #   1 = Optimization successful
        #   2 = Cable takes off from support
        #   3 = Optimization partially successful
    
    def onAbort(self):
        self.setWindowTitle('SEILAPLAN')
        self.statusLabel.setText(self.tr(
            'Laufender Prozess wird abgebrochen...'))
        self.workerThread.cancel()  # Terminates process cleanly
        self.wasCanceled = True
    
    def onError(self, exception_string):
        self.setWindowTitle(self.tr('SEILAPLAN: Berechnung fehlgeschlagen'))
        self.statusLabel.setText(self.tr('Ein Fehler ist aufgetreten:'))
        self.resultLabel.setText(self.tr(exception_string))
        self.resultLabel.setHidden(False)
        self.progressBar.setValue(self.progressBar.minimum())
        self.setLayout(self.container)
        self.finallyDo()
    
    def onRerun(self):
        self.doReRun = True
        self.onClose()
    
    def finallyDo(self):
        self.rerunButton.setVisible(True)
        self.cancelButton.hide()
        self.closeButton.show()
    
    def onClose(self):
        self.close()
Esempio n. 19
0
    def construct_form_param_user(self, row, pos):

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

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

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

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

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

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

                widget.setObjectName(field['widgetname'])

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

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

        self.tab = tab

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

                    if self.tab == 'user':
                        self.chk = QCheckBox()
                        self.chk.setObjectName('chk_' + field['widgetname'])
                        if field['checked'] in ('true', 'True', 'TRUE', True):
                            self.chk.setChecked(True)
                        elif field['checked'] in ('false', 'False', 'FALSE',
                                                  False):
                            self.chk.setChecked(False)
                        self.chk.setSizePolicy(QSizePolicy.Fixed,
                                               QSizePolicy.Fixed)

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

                    elif field['widgettype'] == 'textarea':
                        widget = QTextEdit()
                        widget.setText(field['value'])
                        widget.editingFinished.connect(
                            partial(self._get_dialog_changed_values, widget,
                                    self.tab, self.chk))
                        widget.setSizePolicy(QSizePolicy.Expanding,
                                             QSizePolicy.Fixed)

                    elif field['widgettype'] == 'combo':
                        widget = QComboBox()
                        self._fill_combo(widget, field)
                        widget.currentIndexChanged.connect(
                            partial(self._get_dialog_changed_values, widget,
                                    self.tab, self.chk))
                        widget.setSizePolicy(QSizePolicy.Expanding,
                                             QSizePolicy.Fixed)

                    elif field['widgettype'] == 'check':
                        self.chk = QCheckBox()
                        self.chk.setObjectName(field['widgetname'])
                        if self.tab == 'user' and field['checked'] in (
                                'true', 'True', 'TRUE', True):
                            self.chk.setChecked(True)
                        elif self.tab == 'user' and field['checked'] in (
                                'false', 'False', 'FALSE', False):
                            self.chk.setChecked(False)
                        elif field['value'] in ('true', 'True', 'TRUE', True):
                            self.chk.setChecked(True)
                        elif field['value'] in ('false', 'False', 'FALSE',
                                                False):
                            self.chk.setChecked(False)
                        self.chk.setSizePolicy(QSizePolicy.Fixed,
                                               QSizePolicy.Fixed)
                        self.chk.stateChanged.connect(
                            partial(self._get_dialog_changed_values, self.chk,
                                    self.tab, self.chk))

                    elif field['widgettype'] == 'datetime':
                        widget = QgsDateTimeEdit()
                        widget.setAllowNull(True)
                        widget.setCalendarPopup(True)
                        widget.setDisplayFormat('dd/MM/yyyy')
                        if global_vars.date_format in ("dd/MM/yyyy",
                                                       "dd-MM-yyyy",
                                                       "yyyy/MM/dd",
                                                       "yyyy-MM-dd"):
                            widget.setDisplayFormat(global_vars.date_format)
                        if field['value']:
                            field['value'] = field['value'].replace('/', '-')
                        date = QDate.fromString(field['value'], 'yyyy-MM-dd')
                        if date:
                            widget.setDate(date)
                        else:
                            widget.clear()

                        widget.valueChanged.connect(
                            partial(self._get_dialog_changed_values, widget,
                                    self.tab, self.chk))
                        widget.setSizePolicy(QSizePolicy.Expanding,
                                             QSizePolicy.Fixed)

                    elif field['widgettype'] == 'spinbox':
                        widget = QDoubleSpinBox()
                        if 'value' in field and field['value'] is not None:
                            value = float(str(field['value']))
                            widget.setValue(value)
                        widget.valueChanged.connect(
                            partial(self._get_dialog_changed_values, widget,
                                    self.tab, self.chk))
                        widget.setSizePolicy(QSizePolicy.Expanding,
                                             QSizePolicy.Fixed)

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

                    # Set signals
                    if self.tab == 'user' and widget is not None:
                        self.chk.stateChanged.connect(
                            partial(self._get_dialog_changed_values, widget,
                                    self.tab, self.chk))

                    if widget is None:
                        widget = self.chk

                    self._order_widgets(field, lbl, widget)

            except Exception as e:
                msg = f"{type(e).__name__} {e}. widgetname='{field['widgetname']}' AND widgettype='{field['widgettype']}'"
                tools_qgis.show_message(msg, 2)
Esempio n. 21
0
    def construct_form_param_system(self, row, pos):

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

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

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

                # Order Widgets
                if field['layout_id'] == 1:
                    self.order_widgets_system(field, self.basic_form, lbl,
                                              widget)
                elif field['layout_id'] == 2:
                    self.order_widgets_system(field, self.om_form, lbl, widget)
                elif field['layout_id'] == 3:
                    self.order_widgets_system(field, self.workcat_form, lbl,
                                              widget)
                elif field['layout_id'] == 4:
                    self.order_widgets_system(field, self.mapzones_form, lbl,
                                              widget)
                elif field['layout_id'] == 5:
                    self.order_widgets_system(field, self.cad_form, lbl,
                                              widget)
                elif field['layout_id'] == 6:
                    self.order_widgets_system(field, self.epa_form, lbl,
                                              widget)
                elif field['layout_id'] == 7:
                    self.order_widgets_system(field, self.masterplan_form, lbl,
                                              widget)
                elif field['layout_id'] == 8:
                    self.order_widgets_system(field, self.other_form, lbl,
                                              widget)
                elif field['layout_id'] == 9:
                    self.order_widgets_system(field, self.node_type_form, lbl,
                                              widget)
                elif field['layout_id'] == 10:
                    self.order_widgets_system(field, self.cat_form, lbl,
                                              widget)
                elif field['layout_id'] == 11:
                    self.order_widgets_system(field, self.utils_form, lbl,
                                              widget)
                elif field['layout_id'] == 12:
                    self.order_widgets_system(field, self.connec_form, lbl,
                                              widget)
                elif field['layout_id'] == 13:
                    self.order_widgets_system(field, self.topology_form, lbl,
                                              widget)
                elif field['layout_id'] == 14:
                    self.order_widgets_system(field, self.builder_form, lbl,
                                              widget)
                elif field['layout_id'] == 15:
                    self.order_widgets_system(field, self.review_form, lbl,
                                              widget)
                elif field['layout_id'] == 16:
                    self.order_widgets_system(field, self.analysis_form, lbl,
                                              widget)
                elif field['layout_id'] == 17:
                    self.order_widgets_system(field, self.system_form, lbl,
                                              widget)
class ParamDxf2Rfu(QWidget, gui_dlg_dxf2rfu):

    send_nw_params = pyqtSignal(dict)
    
    def __init__(self, dwg_lyrs, dwg_blocks, typo_nature_som, typo_nature_lim, precision_class, auth_creator, user, parent=None):

        super(ParamDxf2Rfu, self).__init__(parent)
        self.setupUi(self)
        # Initialization of the closing method (False= quit by red cross)
        self.quit_valid = False
        self.param_dxf = {}
        self.valid_btn.clicked.connect(self.butt_ok)
        # Delete Widget on close event..
        # self.setAttribute(Qt.WA_DeleteOnClose, True)
        # Load the original parameters
        try:
            self.params_path = os.path.join(os.path.dirname(__file__), r"import_dxf2rfu_param.json")
        except IOError as error:
            raise error
        with codecs.open(self.params_path, encoding='utf-8', mode='r') as json_file:
            self.json_params = json.load(json_file)
            self.old_params = self.json_params[r"dxfparams"]
        # Manage delim_pub_chk text
        self.delim_pub_chk.stateChanged.connect(self.settext_delim_pub_chk)
        # Create sorted list of the names of dwg layers
        self.dwg_lyrs = dwg_lyrs
        lyr_names = []
        for lyr in self.dwg_lyrs:
            lyr_names.append(str(lyr.name))
        lyr_names.sort()
        # Create sorted list of the names of blocks
        self.dwg_blocks = dwg_blocks
        blk_names = []
        for blk_def in self.dwg_blocks:
            if len(blk_def.name) > 0:
                if (not blk_def.is_xref) and (not blk_def.is_anonymous) and blk_def.name[0] != '*':
                    blk_names.append(str(blk_def.name))
        blk_names.sort()
        self.typo_nature_som = typo_nature_som
        self.typo_nature_lim = typo_nature_lim
        self.precision_class = precision_class
        self.auth_creator = auth_creator
        self.user = user
        # Fill the delim_pub checkbox
        if "delim_pub" in self.old_params:
            if self.old_params["delim_pub"] == 'true':
                self.delim_pub_chk.setChecked(True)
            else:
                self.delim_pub_chk.setChecked(False)
        # Populate createur list
        creat_param = False
        for i, e in enumerate(self.auth_creator):
            self.createur_cmb.addItem("%s (%s)" % (e[1], e[0]))
            # Find the creator in the params
            if "createur" in self.old_params:
                if self.old_params["createur"] == e[0]:
                    self.createur_cmb.setCurrentIndex(i)
                    creat_param = True 
            # Set current user as the creator by default
            if self.user == e[0] and not creat_param:
                self.createur_cmb.setCurrentIndex(i)
        # Populate the precision class list
        prec_class_dft = None
        prec_class_curidx = 0
        prec_class_dft_exist = False
        if "prec_class" in self.old_params:
            prec_class_dft = self.old_params["prec_class"]
            for (idx, prec_val) in enumerate(self.precision_class):
                if prec_class_dft == self.precision_class[idx][1]:
                    prec_class_curidx = idx
                    prec_class_dft_exist = True
            if not prec_class_dft_exist:
                self.precision_class_cmb.addItem(prec_class_dft)
                self.precision_class_cmb.setItemData(0, QColor("red"), Qt.TextColorRole)
        for prec_class in self.precision_class:
            self.precision_class_cmb.addItem(prec_class[1])
        self.precision_class_cmb.setCurrentIndex(prec_class_curidx)
        # Populate the layer list (for vertices)
        vtx_lyr_dft = None
        vtx_curidx = 0
        if "vtx_lyr" in self.old_params:
            vtx_lyr_dft = self.old_params["vtx_lyr"]
        else:
            vtx_lyr_dft = "0"
        if vtx_lyr_dft in lyr_names:
            vtx_curidx = lyr_names.index(vtx_lyr_dft)
        else:
            self.vtx_lyr_cmb.addItem(vtx_lyr_dft)
            self.vtx_lyr_cmb.setItemData(0, QColor("red"), Qt.TextColorRole)
 

        for lyr_name in lyr_names:
            self.vtx_lyr_cmb.addItem(lyr_name)

        self.vtx_lyr_cmb.setCurrentIndex(vtx_curidx)

        # Populate the different types of points
        for idx, pt_type in enumerate (self.typo_nature_som):
            self.symb_corr_lab = QLabel(self.pt_type_gpb)
            sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(self.symb_corr_lab.sizePolicy().hasHeightForWidth())
            self.symb_corr_lab.setSizePolicy(sizePolicy)
            self.symb_corr_lab.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            self.symb_corr_lab.setMinimumSize(QSize(160, 25))
            self.symb_corr_lab.setMaximumSize(QSize(160, 25))
            self.symb_corr_lab.setObjectName("symb_corr_lab" + str(idx))
            self.symb_corr_lab.setText(str(pt_type))
            self.corr_grid_lay.addWidget(self.symb_corr_lab, (idx), 0, 1, 1)
            self.symb_corr_cmb = QComboBox(self.pt_type_gpb)
            self.symb_corr_cmb.setMinimumSize(QSize(0, 25))
            self.symb_corr_cmb.setMaximumSize(QSize(16777215, 25))
            self.symb_corr_cmb.setObjectName("symb_corr_cmb" + str(idx))
            self.corr_grid_lay.addWidget(self.symb_corr_cmb, (idx), 1, 1, 1)
            self.cur_cmb = self.findChild(QComboBox, "symb_corr_cmb" + str(idx))
            # Manage the background color of the comboboxes
            self.cur_cmb.currentTextChanged.connect(partial(self.chk_cmb_bkgrd, self.cur_cmb))
            # Add specific values (all block and no none block)
            self.cur_cmb.addItem(no_blk)
            self.cur_cmb.setItemData(0, QColor(111,111,111), Qt.TextColorRole)
            self.cur_cmb.addItem(all_blks)
            self.cur_cmb.setItemData(1, QColor(42,195,124), Qt.TextColorRole)
            blk_dft = None
            blk_curidx = 0
            # Manage v2.1 new config.json structure
            if "blk_corrs" in self.old_params:
                blks_params = self.old_params["blk_corrs"]
            # Manage old config.json structure
            else:
                blks_params = self.old_params
            # Find the correct param
            if str(pt_type) in blks_params:
                blk_dft = blks_params[str(pt_type)]
            if blk_dft in blk_names :
                blk_curidx = blk_names.index(blk_dft) + 2
            else:
                if blk_dft == no_blk:
                    blk_curidx = 0
                elif blk_dft == all_blks:
                    blk_curidx = 1
                else:
                    self.cur_cmb.addItem(blk_dft)
                    blk_curidx = 2
                    self.cur_cmb.setItemData(2, QColor("red"), Qt.TextColorRole)
            for blk_name in blk_names:
                self.cur_cmb.addItem(blk_name)
            self.cur_cmb.setCurrentIndex(blk_curidx)
                
        sp_item1 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.corr_grid_lay.addItem(sp_item1, (idx + 1), 0, 1, 1)
        # Adapt the size of the dlg
        self.pt_type_gpb.setMinimumSize(QSize(470, 56+29*(idx+1)))
        
        # Populate the different types of limits
        for idx, lim_type in enumerate (self.typo_nature_lim):
            self.lim_corr_lab = QLabel(self.lim_type_gpb)
            sizePolicy = QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
            sizePolicy.setHorizontalStretch(0)
            sizePolicy.setVerticalStretch(0)
            sizePolicy.setHeightForWidth(self.lim_corr_lab.sizePolicy().hasHeightForWidth())
            self.lim_corr_lab.setSizePolicy(sizePolicy)
            self.lim_corr_lab.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
            self.lim_corr_lab.setMinimumSize(QSize(160, 25))
            self.lim_corr_lab.setMaximumSize(QSize(160, 25))
            self.lim_corr_lab.setObjectName("lim_corr_lab" + str(idx))
            self.lim_corr_lab.setText(str(lim_type))
            self.lim_grid_lay.addWidget(self.lim_corr_lab, (idx), 0, 1, 1)
            self.lim_corr_cmb = QComboBox(self.lim_type_gpb)
            self.lim_corr_cmb.setMinimumSize(QSize(0, 25))
            self.lim_corr_cmb.setMaximumSize(QSize(16777215, 25))
            self.lim_corr_cmb.setObjectName("lim_corr_cmb" + str(idx))
            self.lim_grid_lay.addWidget(self.lim_corr_cmb, (idx), 1, 1, 1)
            self.cur_cmb = self.findChild(QComboBox, "lim_corr_cmb" + str(idx))
            # Manage the background color of the comboboxes
            self.cur_cmb.currentTextChanged.connect(partial(self.chk_cmb_bkgrd, self.cur_cmb))
            # Add specific value (none layer)
            self.cur_cmb.addItem(no_lyr)
            self.cur_cmb.setItemData(0, QColor(111,111,111), Qt.TextColorRole)
            lyr_dft = None
            lyr_cur_idx = 0
            # Manage v2.1 new config.json structure
            if "lim_lyrs" in self.old_params:
                lim_lyrs_params = self.old_params["lim_lyrs"]
            # Manage old config.json structure
            else:
                lim_lyrs_params = self.old_params  
            # Find the correct param
            if str(lim_type) in lim_lyrs_params:
                lyr_dft = lim_lyrs_params[str(lim_type)]
            else:
                lyr_dft = "0"
            if lyr_dft in lyr_names:
                lyr_cur_idx = lyr_names.index(lyr_dft) + 1
            else:
                if lyr_dft == no_lyr:
                    lyr_cur_idx = 0
                else:
                    self.cur_cmb.addItem(lyr_dft)
                    lyr_cur_idx = 1
                    self.cur_cmb.setItemData(1, QColor("red"), Qt.TextColorRole)
            for lyr_name in lyr_names:
                self.cur_cmb.addItem(lyr_name)
            self.cur_cmb.setCurrentIndex(lyr_cur_idx)
                       
        sp_item2 = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.lim_grid_lay.addItem(sp_item2, (idx + 1), 0, 1, 1)
        # Adapt the size of the dlg
        self.lim_type_gpb.setMinimumSize(QSize(470, 56+29*(idx+1)))
        
    # Change the text of the delim_pub checkbox
    def settext_delim_pub_chk(self):
        if self.delim_pub_chk.isChecked():
            self.delim_pub_chk.setText('oui')
        else:
            self.delim_pub_chk.setText('non')
        
    # Manage the background color of comboboxes
    # (depends on the color of the current item)
    # And the all block sate -> only one block combobox with this state
    def chk_cmb_bkgrd(self, combo):

        sel_col = "QComboBox QAbstractItemView {selection-background-color: lightgray;}"
        std_bkg_col = "QComboBox:on {background-color: rgb(240, 240, 240);}"
        if combo.itemData(combo.currentIndex(), Qt.TextColorRole) == QColor("red"):
            css = "QComboBox {background-color: rgb(255, 189, 189);}" + sel_col + std_bkg_col
            combo.setStyleSheet(css)
        elif combo.itemData(combo.currentIndex(), Qt.TextColorRole) ==  QColor(42,195,124):
            css = "QComboBox {background-color: rgb(208, 255, 222);}" + sel_col + std_bkg_col
            combo.setStyleSheet(css) 
            for idx, pt_type in enumerate(self.typo_nature_som):
                type_cmb = self.findChild(QComboBox, "symb_corr_cmb" + str(idx))
                if type_cmb:
                    if type_cmb != combo:
                        type_cmb.setCurrentText(no_blk)             
        elif combo.itemData(combo.currentIndex(), Qt.TextColorRole) ==  QColor(111,111,111):
            css = "QComboBox {background-color: rgb(144, 144, 144);}" + sel_col + std_bkg_col
            combo.setStyleSheet(css) 
        else:
            css = ""
            combo.setStyleSheet(css)
            # Deactivate the all_blks combobox if another combox is used
            change = False
            for idx, pt_type in enumerate(self.typo_nature_som):
                type_cmb = self.findChild(QComboBox, "symb_corr_cmb" + str(idx))
                if type_cmb:
                    if type_cmb.currentText() != all_blks and type_cmb.currentText() != no_blk:
                        change = True
            if change:
                for idx, pt_type in enumerate(self.typo_nature_som):
                    type_cmb = self.findChild(QComboBox, "symb_corr_cmb" + str(idx))
                    if type_cmb:
                        if type_cmb.currentText() == all_blks:
                            type_cmb.setCurrentText(no_blk)
    
    # Close the window when clicking on the OK button
    def butt_ok(self):
        self.quit_valid = True
        self.close()
        
    # Send the parameters when the windows is quit
    def closeEvent(self, event):
        if self.quit_valid:
            # Save the different parameters
            self.param_dxf["createur"] = self.createur_cmb.currentText()[-6:-1]
            self.param_dxf["vtx_lyr"] = self.vtx_lyr_cmb.currentText()
            self.param_dxf["prec_class"] = self.precision_class_cmb.currentText()
            # Transform the delim_pub checkbox into the correct value
            self.param_dxf["delim_pub"] = chkbox_to_truefalse(self.delim_pub_chk)
            blk_def = {}
            for idx, pt_type in enumerate(self.typo_nature_som):
                type_cmb = self.findChild(QComboBox, "symb_corr_cmb" + str(idx))
                blk_def[str(pt_type)] = str(type_cmb.currentText())
            self.param_dxf["blk_corrs"] = blk_def
            lim_def = {}
            for idx, lim_type in enumerate(self.typo_nature_lim):
                type_cmb = self.findChild(QComboBox, "lim_corr_cmb" + str(idx))
                lim_def[str(lim_type)] = str(type_cmb.currentText())
            self.param_dxf["lim_lyrs"] = lim_def
            self.hide()
            # Update the new parameters in the json file
            json_params = {}
            json_params["dxfparams"] = self.param_dxf
            with codecs.open(self.params_path, encoding='utf-8', mode='w') as json_file:
                json_file.write(json.dumps(json_params, indent=4, separators=(',', ': '), ensure_ascii=False))
            # Send the parameters
            self.send_nw_params.emit(self.param_dxf)
        else:
            # Hide the window
            self.hide()
class GroupSelectParameterWidget(GenericParameterWidget):
    """Widget class for Group Select Parameter."""
    def __init__(self, parameter, parent=None):
        """Constructor.

        :param parameter: A GroupSelectParameter object.
        :type parameter: GroupSelectParameter
        """
        QWidget.__init__(self, parent)
        self._parameter = parameter

        # Store spin box
        self.spin_boxes = {}

        # Create elements
        # Label (name)
        self.label = QLabel(self._parameter.name)

        # Layouts
        self.main_layout = QVBoxLayout()
        self.input_layout = QVBoxLayout()

        # _inner_input_layout must be filled with widget in the child class
        self.inner_input_layout = QVBoxLayout()

        self.radio_button_layout = QGridLayout()

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

        # List widget
        self.list_widget = QListWidget()
        self.list_widget.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.list_widget.setDragDropMode(QAbstractItemView.DragDrop)
        self.list_widget.setDefaultDropAction(Qt.MoveAction)
        self.list_widget.setEnabled(False)
        self.list_widget.setSizePolicy(QSizePolicy.Maximum,
                                       QSizePolicy.Expanding)

        for i, key in enumerate(self._parameter.options):
            value = self._parameter.options[key]
            radio_button = QRadioButton(value.get('label'))
            self.radio_button_layout.addWidget(radio_button, i, 0)
            if value.get('type') == SINGLE_DYNAMIC:
                percentage_spin_box = PercentageSpinBox(self)
                self.radio_button_layout.addWidget(percentage_spin_box, i, 1)
                percentage_spin_box.setValue(value.get('value', 0))
                step = percentage_spin_box.singleStep()
                if step > 1:
                    precision = 0
                else:
                    precision = len(str(step).split('.')[1])
                    if precision > 3:
                        precision = 3
                percentage_spin_box.setDecimals(precision)
                self.spin_boxes[key] = percentage_spin_box

                # Enable spin box depends on the selected option
                if self._parameter.selected == key:
                    percentage_spin_box.setEnabled(True)
                else:
                    percentage_spin_box.setEnabled(False)

            elif value.get('type') == STATIC:
                static_value = value.get('value', 0)
                if static_value is not None:
                    self.radio_button_layout.addWidget(
                        QLabel(str(static_value * 100) + ' %'), i, 1)
            elif value.get('type') == MULTIPLE_DYNAMIC:
                if self._parameter.selected == key:
                    self.list_widget.setEnabled(True)
                else:
                    self.list_widget.setEnabled(False)

            self.input_button_group.addButton(radio_button, i)
            if self._parameter.selected == key:
                radio_button.setChecked(True)

        # Help text
        self.help_label = QLabel(self._parameter.help_text)
        self.help_label.setSizePolicy(QSizePolicy.Maximum,
                                      QSizePolicy.Expanding)
        self.help_label.setWordWrap(True)
        self.help_label.setAlignment(Qt.AlignTop)

        self.inner_input_layout.addLayout(self.radio_button_layout)
        self.inner_input_layout.addWidget(self.list_widget)

        # Put elements into layouts
        self.input_layout.addWidget(self.label)
        self.input_layout.addLayout(self.inner_input_layout)

        self.help_layout = QVBoxLayout()
        self.help_layout.addWidget(self.help_label)

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

        self.setLayout(self.main_layout)

        self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Expanding)

        # Update list widget
        self.update_list_widget()

        # Connect signal
        # noinspection PyUnresolvedReferences
        self.input_button_group.buttonClicked.connect(
            self.radio_buttons_clicked)

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

        :returns: A DefaultValueParameter from the current state of widget
        :rtype: DefaultValueParameter
        """
        # Set value for each key
        for key, value in list(self._parameter.options.items()):
            if value.get('type') == STATIC:
                continue
            elif value.get('type') == SINGLE_DYNAMIC:
                new_value = self.spin_boxes.get(key).value()
                self._parameter.set_value_for_key(key, new_value)
            elif value.get('type') == MULTIPLE_DYNAMIC:
                # Need to iterate through all items
                items = []
                for index in range(self.list_widget.count()):
                    items.append(self.list_widget.item(index))
                new_value = [i.text() for i in items]
                self._parameter.set_value_for_key(key, new_value)

        # Get selected radio button
        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.selected = None
        else:
            self._parameter.selected = list(
                self._parameter.options.keys())[radio_button_checked_id]

        return self._parameter

    def update_list_widget(self):
        """Update list widget when radio button is clicked."""
        # Get selected radio button
        radio_button_checked_id = self.input_button_group.checkedId()
        # No radio button checked, then default value = None
        if radio_button_checked_id > -1:
            selected_dict = list(
                self._parameter.options.values())[radio_button_checked_id]
            if selected_dict.get('type') == MULTIPLE_DYNAMIC:
                for field in selected_dict.get('value'):
                    # Update list widget
                    field_item = QListWidgetItem(self.list_widget)
                    field_item.setFlags(Qt.ItemIsEnabled
                                        | Qt.ItemIsSelectable
                                        | Qt.ItemIsDragEnabled)
                    field_item.setData(Qt.UserRole, field)
                    field_item.setText(field)
                    self.list_widget.addItem(field_item)

    def radio_buttons_clicked(self):
        """Handler when selected radio button changed."""
        # Disable all spin boxes
        for spin_box in list(self.spin_boxes.values()):
            spin_box.setEnabled(False)
        # Disable list widget
        self.list_widget.setEnabled(False)

        # Get selected radio button
        radio_button_checked_id = self.input_button_group.checkedId()

        if radio_button_checked_id > -1:
            selected_value = list(
                self._parameter.options.values())[radio_button_checked_id]
            if selected_value.get('type') == MULTIPLE_DYNAMIC:
                # Enable list widget
                self.list_widget.setEnabled(True)
            elif selected_value.get('type') == SINGLE_DYNAMIC:
                selected_key = list(
                    self._parameter.options.keys())[radio_button_checked_id]
                self.spin_boxes[selected_key].setEnabled(True)

    def select_radio_button(self, key):
        """Helper to select a radio button with key.

        :param key: The key of the radio button.
        :type key: str
        """
        key_index = list(self._parameter.options.keys()).index(key)
        radio_button = self.input_button_group.button(key_index)
        radio_button.click()
    def initialize_widgets(self):
        """Dynamically set up widgets based on detected files."""
        self.widgets_per_file.clear()
        files_widgets = [
            self.widget_general,
            self.widget_terrain_model,
            self.widget_simple_infiltration,
            self.widget_groundwater,
            self.widget_interflow,
        ]
        files_info_collection = [
            self.general_files,
            self.terrain_model_files,
            self.simple_infiltration_files,
            self.groundwater_files,
            self.interflow_files,
        ]
        for widget in files_widgets:
            widget.hide()

        current_main_layout_row = 1
        for widget, files_info in zip(files_widgets, files_info_collection):
            widget_layout = widget.layout()
            for field_name, name in files_info.items():
                try:
                    file_state = self.detected_files[field_name]
                except KeyError:
                    continue
                status = file_state["status"]
                widget.show()
                name_label = QLabel(name)
                name_label.setSizePolicy(QSizePolicy.Preferred,
                                         QSizePolicy.Preferred)
                widget_layout.addWidget(name_label, current_main_layout_row, 0)

                status_label = QLabel(status.value)
                status_label.setSizePolicy(QSizePolicy.Preferred,
                                           QSizePolicy.Preferred)
                widget_layout.addWidget(status_label, current_main_layout_row,
                                        1)

                empty_label = QLabel()
                widget_layout.addWidget(empty_label, current_main_layout_row,
                                        2)

                no_action_pb_name = "Ignore"
                if status == UploadFileStatus.DELETED_LOCALLY:
                    action_pb_name = "Delete online"
                else:
                    action_pb_name = "Upload"
                # Add valid reference widgets
                all_actions_widget = QWidget()
                actions_sublayout = QGridLayout()
                all_actions_widget.setLayout(actions_sublayout)

                valid_ref_widget = QWidget()
                valid_ref_sublayout = QGridLayout()
                valid_ref_widget.setLayout(valid_ref_sublayout)
                no_action_pb = QPushButton(no_action_pb_name)
                no_action_pb.setCheckable(True)
                no_action_pb.setAutoExclusive(True)
                no_action_pb.clicked.connect(
                    partial(self.toggle_action, field_name, False))

                action_pb = QPushButton(action_pb_name)
                action_pb.setCheckable(True)
                action_pb.setAutoExclusive(True)
                action_pb.setChecked(True)
                action_pb.clicked.connect(
                    partial(self.toggle_action, field_name, True))

                valid_ref_sublayout.addWidget(no_action_pb, 0, 0)
                valid_ref_sublayout.addWidget(action_pb, 0, 1)

                # Add invalid reference widgets
                invalid_ref_widget = QWidget()
                invalid_ref_sublayout = QGridLayout()
                invalid_ref_widget.setLayout(invalid_ref_sublayout)

                filepath_sublayout = QGridLayout()
                filepath_line_edit = QLineEdit()
                filepath_line_edit.setSizePolicy(QSizePolicy.Minimum,
                                                 QSizePolicy.Minimum)
                browse_pb = QPushButton("...")
                browse_pb.clicked.connect(
                    partial(self.browse_for_raster, field_name))
                filepath_sublayout.addWidget(filepath_line_edit, 0, 0)
                filepath_sublayout.addWidget(browse_pb, 0, 1)
                invalid_ref_sublayout.addLayout(filepath_sublayout, 0, 0)

                update_ref_pb = QPushButton("Update reference")
                update_ref_pb.clicked.connect(
                    partial(self.update_raster_reference, field_name))
                invalid_ref_sublayout.addWidget(update_ref_pb, 0, 1)

                actions_sublayout.addWidget(valid_ref_widget, 0, 0)
                actions_sublayout.addWidget(invalid_ref_widget, 0, 1)
                # Add all actions widget into the main widget layout
                widget_layout.addWidget(all_actions_widget,
                                        current_main_layout_row, 2)
                # Hide some of the widgets based on files states
                if status == UploadFileStatus.NO_CHANGES_DETECTED:
                    all_actions_widget.hide()
                elif status == UploadFileStatus.INVALID_REFERENCE:
                    valid_ref_widget.hide()
                else:
                    invalid_ref_widget.hide()
                self.widgets_per_file[field_name] = (
                    name_label,
                    status_label,
                    valid_ref_widget,
                    action_pb,
                    invalid_ref_widget,
                    filepath_line_edit,
                )
                current_main_layout_row += 1