def getSpinRemoveAreaPixels(wgt, value):
     sp = QSpinBox(wgt)
     sp.setRange(0, 1000)
     sp.setSingleStep(1)
     sp.setSuffix(' pixels')
     sp.setValue(value)
     return sp
Exemplo n.º 2
0
 def valueWidget(self, field, data):
     """
     Retrieves correct widget for a given field based on its type.
     :param field: (QgsField) field to be represented.
     :param data: (float/int/str/bool) initial data to be set to widget.
     :return: (QDoubleSpinBox/QSpinBox/QLineEdit/QCheckBox) the adequate
              widget for field.
     """
     if utils.fieldIsBool(field):
         # vWidget = QCheckBox()
         vWidget = self.centeredCheckBox()
         if not data is None:
             vWidget.cb.setChecked(data)
     elif utils.fieldIsFloat(field):
         vWidget = QDoubleSpinBox()
         vWidget.setMaximum(99999999)
         vWidget.setMinimum(-99999999)
         if data is not None:
             vWidget.setValue(data)
     elif utils.fieldIsInt(field):
         vWidget = QSpinBox()
         vWidget.setMaximum(99999999)
         vWidget.setMinimum(-99999999)
         if data is not None:
             vWidget.setValue(data)
     else:
         vWidget = QLineEdit()
         vWidget.setPlaceholderText(
             self.tr("Type the value for {0}").format(field.name()))
         if data is not None:
             vWidget.setText(data)
     return vWidget
 def getSpinBoxAzimuth(wgt, value):
     sp = QSpinBox(wgt)
     sp.setRange(0, 45)
     sp.setSingleStep(1)
     sp.setSuffix(' degrees')
     sp.setValue(value)
     msg = QCoreApplication.translate(
         'GimpSelectionFeature',
         'Degrees of azimuth between vertexs')
     sp.setToolTip(msg)
     return sp
Exemplo n.º 4
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
Exemplo n.º 5
0
    def _create_widget(cls, c, parent, host=None):
        sb = QSpinBox(parent)
        sb.setObjectName('{0}_{1}'.format(cls._TYPE_PREFIX, c.name))

        # Set ranges
        c_min = sb.valueFromText(str(c.minimum))
        c_max = sb.valueFromText(str(c.maximum))
        sb.setMinimum(c.minimum)
        sb.setMaximum(c.maximum)

        return sb
Exemplo n.º 6
0
def extra_keywords_to_widgets(extra_keyword_definition):
    """Create widgets for extra keyword.

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

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

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

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

    return check_box, input_widget
 def getSpinBoxIteration(wgt, value):
     sp = QSpinBox(wgt)
     sp.setRange(0, 3)
     sp.setSingleStep(1)
     sp.setValue(value)
     return sp
Exemplo n.º 8
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)
Exemplo n.º 9
0
    def __init__(self, minimum: int = 0, maximum: int = 100000000,
                 step: int = 1, width: int = 300,
                 lockable: bool = False, locked: bool = False, **kwargs):
        '''
        Parameters
        ----------
        width : int, optional
            width of slider in pixels, defaults to 300 pixels
        minimum : int, optional
            minimum value that the user can set
        maximum : int, optional
            maximum value that the user can set
        step : int, optional
            the tick intervall of the slider and single step of the number
            input, defaults to 1
        lockable : bool, optional
            the slider and number input can be locked by a checkbox that will
            be displayed next to them if True, defaults to not lockable
        locked : bool, optional
            initial lock-state of inputs, only applied if lockable is True,
            defaults to inputs being not locked
        '''
        super().__init__(**kwargs)
        self.minimum = minimum
        self.maximum = maximum
        self.lockable = lockable
        self.step = step
        self.slider = QSlider(Qt.Horizontal)
        self.slider.setMinimum(minimum)
        self.slider.setMaximum(maximum)
        self.slider.setTickInterval(step)
        self.slider.setFixedWidth(width)
        self.spinbox = QSpinBox()
        self.spinbox.setMinimum(minimum)
        self.spinbox.setMaximum(maximum)
        self.spinbox.setSingleStep(step)
        self.registerFocusEvent(self.spinbox)
        self.registerFocusEvent(self.slider)

        if lockable:
            self.lock_button = QPushButton()
            self.lock_button.setCheckable(True)
            self.lock_button.setChecked(locked)
            self.lock_button.setSizePolicy(
                QSizePolicy.Fixed, QSizePolicy.Fixed)

            def toggle_icon(emit=True):
                is_locked = self.lock_button.isChecked()
                fn = '20190619_iconset_mob_lock_locked_02.png' if is_locked \
                    else '20190619_iconset_mob_lock_unlocked_03.png'
                self.slider.setEnabled(not is_locked)
                self.spinbox.setEnabled(not is_locked)
                icon_path = os.path.join(settings.IMAGE_PATH, 'iconset_mob', fn)
                icon = QIcon(icon_path)
                self.lock_button.setIcon(icon)
                self.locked.emit(is_locked)
            toggle_icon(emit=False)
            self.lock_button.clicked.connect(lambda: toggle_icon(emit=True))

        self.slider.valueChanged.connect(
            lambda: self.set_value(self.slider.value()))
        self.spinbox.valueChanged.connect(
            lambda: self.set_value(self.spinbox.value()))
        self.slider.valueChanged.connect(
            lambda: self.changed.emit(self.get_value()))
        self.spinbox.valueChanged.connect(
            lambda: self.changed.emit(self.get_value())
        )
Exemplo n.º 10
0
    def __init__(self, llegenda, capa=None, amplada=500):
        super().__init__(llegenda, amplada)
        if capa is None:
            self.capa = llegenda.currentLayer()
        else:
            self.capa = capa
        self.info = None
        if not self.iniParams():
            return

        self.setWindowTitle('Modificar mapa simbòlic ' + self.renderParams.tipusMapa.lower())

        self.layout = QVBoxLayout()
        self.layout.setSpacing(14)
        self.setLayout(self.layout)

        self.color = QComboBox(self)
        self.color.setEditable(False)
        self.comboColors(self.color)

        self.contorn = QComboBox(self)
        self.contorn.setEditable(False)
        self.comboColors(self.contorn, mv.MAP_CONTORNS)

        self.color.currentIndexChanged.connect(self.canviaContorns)

        self.metode = QComboBox(self)
        self.metode.setEditable(False)
        if self.renderParams.numCategories > 1:
            self.metode.addItems(mv.MAP_METODES_MODIF.keys())
        else:
            self.metode.addItems(mv.MAP_METODES.keys())
        self.metode.setCurrentIndex(-1)
        self.metode.currentIndexChanged.connect(self.canviaMetode)

        self.nomIntervals = QLabel("Nombre d'intervals:", self)
        self.intervals = QSpinBox(self)
        self.intervals.setMinimum(min(2, self.renderParams.numCategories))
        self.intervals.setMaximum(max(mv.MAP_MAX_CATEGORIES, self.renderParams.numCategories))
        self.intervals.setSingleStep(1)
        self.intervals.setValue(4)
        if self.renderParams.tipusMapa == 'Àrees':
            self.intervals.setSuffix("  (depèn del mètode)")
        # self.intervals.valueChanged.connect(self.deselectValue)

        self.nomTamany = QLabel("Tamany cercle:", self)
        self.tamany = QSpinBox(self)
        self.tamany.setMinimum(1)
        self.tamany.setMaximum(12)
        self.tamany.setSingleStep(1)
        self.tamany.setValue(4)

        self.bInfo = QPushButton('Info')
        self.bInfo.clicked.connect(self.veureInfo)

        self.buttons = QDialogButtonBox()
        self.buttons.addButton(QDialogButtonBox.Ok)
        self.buttons.accepted.connect(self.accept)
        self.buttons.addButton(QDialogButtonBox.Cancel)
        self.buttons.rejected.connect(self.cancel)
        self.buttons.addButton(self.bInfo, QDialogButtonBox.ResetRole)

        self.gSimb = QGroupBox('Simbologia del mapa')
        self.lSimb = QFormLayout()
        self.lSimb.setSpacing(14)
        self.gSimb.setLayout(self.lSimb)

        self.lSimb.addRow('Color base:', self.color)
        self.lSimb.addRow('Color contorn:', self.contorn)
        if self.renderParams.tipusMapa == 'Àrees':
            self.lSimb.addRow('Mètode classificació:', self.metode)
            self.lSimb.addRow(self.nomIntervals, self.intervals)
            self.nomTamany.setVisible(False)
            self.tamany.setVisible(False)
        else:
            self.metode.setVisible(False)
            self.nomIntervals.setVisible(False)
            self.intervals.setVisible(False)
            self.lSimb.addRow(self.nomTamany, self.tamany)

        self.wInterval = []
        for w in self.iniIntervals():
            self.wInterval.append(w)
        self.gInter = self.grupIntervals()

        self.layout.addWidget(self.gSimb)
        if self.renderParams.tipusMapa == 'Àrees':
            self.layout.addWidget(self.gInter)
        self.layout.addWidget(self.buttons)

        self.valorsInicials()
Exemplo n.º 11
0
    def __init__(self, llegenda, amplada=500, mapificacio=None, simple=True):
        super().__init__(llegenda, amplada)

        self.fCSV = mapificacio
        self.simple = simple
        self.taulaMostra = None

        self.setWindowTitle('Afegir capa amb mapa simbòlic')

        self.layout = QVBoxLayout()
        self.layout.setSpacing(14)
        self.setLayout(self.layout)

        if self.fCSV is None:
            self.arxiu = QgsFileWidget()
            self.arxiu.setStorageMode(QgsFileWidget.GetFile)
            self.arxiu.setDialogTitle('Selecciona fitxer de dades…')
            self.arxiu.setDefaultRoot(RUTA_LOCAL)
            self.arxiu.setFilter('Arxius CSV (*.csv)')
            self.arxiu.setSelectedFilter('Arxius CSV (*.csv)')
            self.arxiu.lineEdit().setReadOnly(True)
            self.arxiu.fileChanged.connect(self.arxiuSeleccionat)

        self.zona = QComboBox(self)
        self.zona.setEditable(False)
        self.zona.addItem('Selecciona zona…')
        self.zona.currentIndexChanged.connect(self.canviaZona)

        self.mapa = QComboBox(self)
        self.mapa.setEditable(False)
        self.mapa.setIconSize(QSize(126, 126))
        self.mapa.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Expanding)
        self.mapa.setSizeAdjustPolicy(QComboBox.AdjustToContents)
        self.mapa.addItem(QIcon(os.path.join(imatgesDir, 'Àrees.PNG')), 'Àrees')
        self.mapa.addItem(QIcon(os.path.join(imatgesDir, 'Cercles.PNG')), 'Cercles')

        self.capa = QLineEdit(self)
        self.capa.setMaxLength(40)

        self.tipus = QComboBox(self)
        self.tipus.setEditable(False)
        self.tipus.addItem('Selecciona tipus…')
        self.tipus.addItems(mv.MAP_AGREGACIO.keys())
        self.tipus.currentIndexChanged.connect(self.canviaTipus)

        self.distribucio = QComboBox(self)
        self.distribucio.setEditable(False)
        self.distribucio.addItem(next(iter(mv.MAP_DISTRIBUCIO.keys())))

        self.calcul = QvComboBoxCamps(self)
        self.filtre = QvComboBoxCamps(self, multiple=True)

        self.color = QComboBox(self)
        self.color.setEditable(False)
        self.comboColors(self.color)

        self.metode = QComboBox(self)
        self.metode.setEditable(False)
        self.metode.addItems(mv.MAP_METODES.keys())

        self.intervals = QSpinBox(self)
        self.intervals.setMinimum(2)
        self.intervals.setMaximum(mv.MAP_MAX_CATEGORIES)
        self.intervals.setSingleStep(1)
        self.intervals.setValue(4)
        self.intervals.setSuffix("  (depèn del mètode)")
        # self.intervals.valueChanged.connect(self.deselectValue)

        self.bTaula = QPushButton('Veure arxiu')
        self.bTaula.setEnabled(False)
        self.bTaula.clicked.connect(self.veureArxiu)

        self.buttons = QDialogButtonBox()
        self.buttons.addButton(QDialogButtonBox.Ok)
        self.buttons.accepted.connect(self.accept)
        self.buttons.addButton(QDialogButtonBox.Cancel)
        self.buttons.rejected.connect(self.cancel)
        self.buttons.addButton(self.bTaula, QDialogButtonBox.ResetRole)

        self.gDades = QGroupBox('Agregació de dades')
        self.lDades = QFormLayout()
        self.lDades.setSpacing(14)
        self.gDades.setLayout(self.lDades)

        if self.fCSV is None:
            self.lDades.addRow('Arxiu de dades:', self.arxiu)
        self.lDades.addRow('Zona:', self.zona)
        self.lDades.addRow("Tipus d'agregació:", self.tipus)
        self.lDades.addRow('Camp de càlcul:', self.calcul)
        if self.simple:
            self.filtre.setVisible(False)
            self.distribucio.setVisible(False)
        else:
            self.lDades.addRow('Filtre:', self.filtre)
            self.lDades.addRow('Distribució:', self.distribucio)

        self.gMapa = QGroupBox('Definició del mapa simbòlic')
        self.lMapa = QFormLayout()
        self.lMapa.setSpacing(14)
        self.gMapa.setLayout(self.lMapa)

        self.lMapa.addRow('Nom de capa:', self.capa)
        self.lMapa.addRow('Tipus de mapa:', self.mapa)

        self.gSimb = QGroupBox('Simbologia del mapa')
        self.lSimb = QFormLayout()
        self.lSimb.setSpacing(14)
        self.gSimb.setLayout(self.lSimb)

        self.lSimb.addRow('Color base:', self.color)
        self.lSimb.addRow('Mètode classificació:', self.metode)
        self.lSimb.addRow("Nombre d'intervals:", self.intervals)

        self.layout.addWidget(self.gDades)
        self.layout.addWidget(self.gMapa)
        if self.simple:
            self.gSimb.setVisible(False)
        else:
            self.layout.addWidget(self.gSimb)
        self.layout.addWidget(self.buttons)

        self.adjustSize()

        self.nouArxiu()
Exemplo n.º 12
0
 def create_eid_selector(self):
     self.eid_lbl = QLabel('Event ID')
     self.eid_sbx = QSpinBox()
     self.eid_sbx.setEnabled(False)
     self.vlayout.addWidget(self.eid_lbl)
     self.vlayout.addWidget(self.eid_sbx)
Exemplo n.º 13
0
        elif no == 2:
            self._angle2 = -9999.9
        else:
            self._angle = -9999.9
            self._angle2 = -9999.9
        self.update()


if __name__ == "__main__":
    from qgis.PyQt.Qt import QApplication

    app = QApplication(sys.argv)

    window = QWidget()
    compass = CompassWidget()
    spinBox = QSpinBox()
    spinBox.setRange(0, 719)
    spinBox.valueChanged.connect(compass.setAngle)
    spinBox2 = QSpinBox()
    spinBox2.setRange(0, 719)
    spinBox2.valueChanged.connect(compass.setAngle2)

    layout = QVBoxLayout()
    layout.addWidget(compass)
    layout.addWidget(spinBox)
    layout.addWidget(spinBox2)
    window.setLayout(layout)

    window.show()
    sys.exit(app.exec_())
    def __init__(self, iface):
        QtWidgets.QDialog.__init__(self)
        self.iface = iface
        self.setupUi(self)

        self.error = None

        self.error = None
        self.data_path, self.data_type = GetOutputFileName(
            self, 'AequilibraE custom formats',
            ["Aequilibrae dataset(*.aed)", "Aequilibrae matrix(*.aem)"],
            '.aed', standard_path())

        if self.data_type is None:
            self.error = 'Path provided is not a valid dataset'
            self.exit_with_error()

        self.data_type = self.data_type.upper()

        if self.data_type == 'AED':
            self.data_to_show = AequilibraEData()
        elif self.data_type == 'AEM':
            self.data_to_show = AequilibraeMatrix()

        try:
            self.data_to_show.load(self.data_path)
        except:
            self.error = 'Could not load dataset'
            self.exit_with_error()

        # Elements that will be used during the displaying
        self._layout = QVBoxLayout()
        self.table = QTableView()
        self._layout.addWidget(self.table)

        # Settings for displaying
        self.show_layout = QHBoxLayout()

        # Thousand separator
        self.thousand_separator = QCheckBox()
        self.thousand_separator.setChecked(True)
        self.thousand_separator.setText('Thousands separator')
        self.thousand_separator.toggled.connect(self.format_showing)
        self.show_layout.addWidget(self.thousand_separator)

        self.spacer = QSpacerItem(5, 0, QtWidgets.QSizePolicy.Expanding,
                                  QtWidgets.QSizePolicy.Minimum)
        self.show_layout.addItem(self.spacer)

        # Decimals
        txt = QLabel()
        txt.setText('Decimal places')
        self.show_layout.addWidget(txt)
        self.decimals = QSpinBox()
        self.decimals.valueChanged.connect(self.format_showing)
        self.decimals.setMinimum(0)
        self.decimals.setValue(4)
        self.decimals.setMaximum(10)

        self.show_layout.addWidget(self.decimals)
        self._layout.addItem(self.show_layout)

        # differentiates between matrix and dataset
        if self.data_type == 'AEM':
            self.data_to_show.computational_view([self.data_to_show.names[0]])
            # Matrices need cores and indices to be set as well
            self.mat_layout = QHBoxLayout()
            self.mat_list = QComboBox()
            for n in self.data_to_show.names:
                self.mat_list.addItem(n)

            self.mat_list.currentIndexChanged.connect(self.change_matrix_cores)
            self.mat_layout.addWidget(self.mat_list)

            self.idx_list = QComboBox()
            for i in self.data_to_show.index_names:
                self.idx_list.addItem(i)
            self.idx_list.currentIndexChanged.connect(self.change_matrix_cores)
            self.mat_layout.addWidget(self.idx_list)
            self._layout.addItem(self.mat_layout)
            self.change_matrix_cores()

        self.but_export = QPushButton()
        self.but_export.setText('Export')
        self.but_export.clicked.connect(self.export)

        self.but_close = QPushButton()
        self.but_close.clicked.connect(self.exit_procedure)
        self.but_close.setText('Close')

        self.but_layout = QHBoxLayout()
        self.but_layout.addWidget(self.but_export)
        self.but_layout.addWidget(self.but_close)

        self._layout.addItem(self.but_layout)

        # We chose to use QTableView. However, if we want to allow the user to edit the dataset
        # The we need to allow them to switch to the slower QTableWidget
        # Code below

        # self.table = QTableWidget(self.data_to_show.entries, self.data_to_show.num_fields)
        # self.table.setHorizontalHeaderLabels(self.data_to_show.fields)
        # self.table.setObjectName('data_viewer')
        #
        # self.table.setVerticalHeaderLabels([str(x) for x in self.data_to_show.index[:]])
        # self.table.clearContents()
        #
        # for i in range(self.data_to_show.entries):
        #     for j, f in enumerate(self.data_to_show.fields):
        #         item1 = QTableWidgetItem(str(self.data_to_show.data[f][i]))
        #         item1.setFlags(Qt.ItemIsEnabled | Qt.ItemIsSelectable)
        #         self.table.setItem(i, j, item1)

        self.resize(700, 500)
        self.setLayout(self._layout)
        self.format_showing()
Exemplo n.º 15
0
    def createWidget(self):
        self.scrollwidget = QtWidgets.QScrollArea()
        self.scrollwidget.setWidgetResizable(True)
        self.tabs = QtWidgets.QTabWidget()
        self.scrollwidget.setWidget(self.tabs)
        self.names = [
            'Settings', 'DTM', 'Slope', '2D-Approximation',
            'Topologic correction', 'Editing', '3D-Modelling', 'Editing (3D)',
            'Export'
        ]
        self.widgets = {}
        self.settings = {}
        self.modules = {}

        for idx, name in enumerate(self.names):
            self.widgets[name] = QtWidgets.QDialog()
            ls = QtWidgets.QFormLayout()
            # Tab-specific options
            if name == "Settings":
                desc = QtWidgets.QLabel(
                    "Welcome to the qpals LineModeler GUI! \nThis tool will help you to detect and "
                    "model breaklines based on a DTM and/or a point cloud using the opals module "
                    "opalsLineModeler.\nThe process includes manual editing in QGIS (\"Editing\") "
                    "as well as automatic dectection and modelling.\n\n"
                    "To begin, please enter some basic information.")
                desc.setWordWrap(True)
                ls.addRow(desc)
                boxRun = QtWidgets.QGroupBox(
                    "Run multiple steps automatically:")
                boxVL = QtWidgets.QVBoxLayout()
                boxRun.setLayout(boxVL)
                self.settings['settings'] = OrderedDict([
                    ('name', QtWidgets.QLineEdit()),
                    ('inFile',
                     QpalsDropTextbox.QpalsDropTextbox(
                         layerlist=self.layerlist)),
                    ('tempFolder', QpalsDropTextbox.QpalsDropTextbox()),
                    ('outFolder', QpalsDropTextbox.QpalsDropTextbox()),
                    ('chkDTM', QtWidgets.QCheckBox("DTM")),
                    ('chkSlope', QtWidgets.QCheckBox("Slope")),
                    ('chk2D', QtWidgets.QCheckBox("2D-Approximation")),
                    ('chktopo2D',
                     QtWidgets.QCheckBox("Topological correction")),
                    ('chkEditing2d',
                     QtWidgets.QLabel(
                         "--- Manual editing of 2D-Approximations ---")),
                    ('chk3Dmodel', QtWidgets.QCheckBox("3D-Modelling")),
                    ('chkEditing3d',
                     QtWidgets.QLabel("--- Manual editing of 3D-Lines ---")),
                    ('chkExport', QtWidgets.QCheckBox("Export")),
                ])
                for key, value in list(self.settings['settings'].items()):
                    if isinstance(value, QpalsDropTextbox.QpalsDropTextbox):
                        value.setMinimumContentsLength(20)
                        value.setSizeAdjustPolicy(
                            QtWidgets.QComboBox.AdjustToMinimumContentsLength)
                    if key.startswith("chk"):
                        boxVL.addWidget(value)

                ls.addRow(QtWidgets.QLabel("Project name"),
                          self.settings['settings']['name'])
                hbox_wrap = QtWidgets.QHBoxLayout()
                hbox_wrap.addWidget(self.settings['settings']['inFile'],
                                    stretch=1)
                ls.addRow(QtWidgets.QLabel("Input file (TIFF/LAS/ODM)"),
                          hbox_wrap)
                hbox_wrap = QtWidgets.QHBoxLayout()
                hbox_wrap.addWidget(self.settings['settings']['tempFolder'],
                                    stretch=1)
                self.settings['settings']['tempFolder'].setPlaceholderText(
                    "drop folder here (will be created if not exists)")
                ls.addRow(QtWidgets.QLabel("Folder for temporary files"),
                          hbox_wrap)
                hbox_wrap = QtWidgets.QHBoxLayout()
                self.settings['settings']['outFolder'].setPlaceholderText(
                    "drop folder here (will be created if not exists)")
                hbox_wrap.addWidget(self.settings['settings']['outFolder'],
                                    stretch=1)
                ls.addRow(QtWidgets.QLabel("Folder for output files"),
                          hbox_wrap)
                ls.addRow(QtWidgets.QLabel(""))
                boxBtnRun = QtWidgets.QPushButton("Run selected steps now")
                boxBtnRun.clicked.connect(lambda: self.run_step("all"))
                boxBtnExp = QtWidgets.QPushButton(
                    "Export selected steps to .bat")
                boxBtnExp.clicked.connect(self.createBatFile)
                # saveBtn = QtWidgets.QPushButton("Save to project file")
                # saveBtn.clicked.connect(self.save)
                boxVL.addWidget(boxBtnRun)
                boxVL.addWidget(boxBtnExp)
                # boxVL.addWidget(saveBtn)
                ls.addRow(boxRun)

            if name == "DTM":
                desc = QtWidgets.QLabel(
                    "This first step will create a digital terrain model (DTM) from your point cloud data. "
                    "Also, a shading of your DTM "
                    "will be created for visualisation purposes. If the input file is not an ODM, one has to be "
                    "created for the modelling process later on.")
                desc.setWordWrap(True)
                ls.addRow(desc)

                impmod, impscroll = QpalsModuleBase.QpalsModuleBase.createGroupBox(
                    "opalsImport", "opalsImport", self.project,
                    {'outFile': 'pointcloud.odm'}, ["inFile", "outFile"])
                self.modules['dtmImp'] = impmod
                self.widgets['dtmImp'] = impscroll
                ls.addRow(impscroll)

                dtmmod, dtmscroll = QpalsModuleBase.QpalsModuleBase.createGroupBox(
                    "opalsGrid", "opalsGrid", self.project, {
                        'interpolation': 'movingPlanes',
                        'gridSize': '1',
                        'outFile': 'DTM_1m.tif'
                    }, [
                        "inFile", "outFile", "neighbours", "searchRadius",
                        "interpolation"
                    ])
                self.modules['dtmGrid'] = dtmmod
                self.widgets['dtmGrid'] = dtmscroll
                dtmmod.afterRun = self.addDtm
                ls.addRow(dtmscroll)

                shdmod, shdscroll = QpalsModuleBase.QpalsModuleBase.createGroupBox(
                    "opalsShade", "opalsShade", self.project, {
                        'inFile': 'DTM_1m.tif',
                        'outFile': 'DTM_1m_shd.tif'
                    }, [
                        "inFile",
                        "outFile",
                    ])
                self.modules['dtmShade'] = shdmod
                shdmod.afterRun = self.addShd
                ls.addRow(shdscroll)

            if name == "Slope":
                desc = QtWidgets.QLabel(
                    "To automatically detect breaklines, a slope map is calculated. This map uses the neighboring 9"
                    " pixels to estimate a plane. The gradient (steepest slope) is then taken, converted to a slope"
                    "in degrees, and assigned to the pixel.")
                desc.setWordWrap(True)
                ls.addRow(desc)

                gfmod, gfscroll = QpalsModuleBase.QpalsModuleBase.createGroupBox(
                    "opalsGridFeature", "opalsGridFeature", self.project, {
                        'feature': 'slpDeg',
                        'inFile': 'DTM_1m.tif',
                        'outFile': 'DTM_1m_slope.tif'
                    }, ["inFile", "outFile", "feature"])
                self.modules['slope'] = gfmod
                ls.addRow(gfscroll)

            if name == "2D-Approximation":
                desc = QtWidgets.QLabel(
                    "The slope map is used to detect breaklines. For this, the algorithm by Canny (1986) is used.\n"
                    "First, the slope map is convoluted with a gaussian kernel for smoothing, then the derivative "
                    "is calculated. The two threshold parameters represent the upper and lower values for the "
                    "binarization of the derivative map. Edges that have at least one pixel > upper threshold will be "
                    "followed until they have a pixel < lower threshold.")
                desc.setWordWrap(True)
                ls.addRow(desc)

                edgeDmod, edgeDscroll = QpalsModuleBase.QpalsModuleBase.createGroupBox(
                    "opalsEdgeDetect", "opalsEdgeDetect", self.project, {
                        'threshold': '2;4',
                        'sigmaSmooth': '1.8',
                        'inFile': 'DTM_1m_slope_slpDeg.tif',
                        'outFile': 'detected_edges.tif'
                    }, ["inFile", "outFile", "threshold", "sigmaSmooth"])
                self.modules['edgeDetect'] = edgeDmod
                ls.addRow(edgeDscroll)

                desc = QtWidgets.QLabel(
                    "Since the output of opalsEdgeDetect is still a raster, we need to vectorize it:"
                )
                desc.setWordWrap(True)
                ls.addRow(desc)

                vecmod, vecscroll = QpalsModuleBase.QpalsModuleBase.createGroupBox(
                    "opalsVectorize", "opalsVectorize", self.project, {
                        'inFile': 'detected_edges.tif',
                        'outFile': 'detected_edges.shp'
                    }, ["inFile", "outFile"])
                self.modules['vectorize'] = vecmod
                ls.addRow(vecscroll)

            if name == "Topologic correction":
                desc = QtWidgets.QLabel(
                    "Vectorized binary rasters usually need some topological cleaning. Here, this is done in three steps: \n"
                    "1) Find the longest line and remove all lines < 10m\n"
                    "2) Merge lines iteratively\n"
                    "3) Clean up")
                desc.setWordWrap(True)
                ls.addRow(desc)

                lt1mod, lt1scroll = QpalsModuleBase.QpalsModuleBase.createGroupBox(
                    "opalsLineTopology", "opalsLineTopology (1)", self.project,
                    {
                        'method': 'longest',
                        'minLength': '10',
                        'snapRadius': '0',
                        'maxTol': '0.5',
                        'maxAngleDev': '75;15',
                        'avgDist': '3',
                        'inFile': 'detected_edges.shp',
                        'outFile': 'edges1.shp'
                    }, ["inFile", "outFile", "method", "minLength", "maxTol"])
                self.modules['lt1'] = lt1mod
                ls.addRow(lt1scroll)

                lt2mod, lt2scroll = QpalsModuleBase.QpalsModuleBase.createGroupBox(
                    "opalsLineTopology", "opalsLineTopology (2)", self.project,
                    {
                        'method': 'merge',
                        'minLength': '10',
                        'snapRadius': '3',
                        'maxTol': '0',
                        'maxAngleDev': '150;15',
                        'avgDist': '3',
                        'merge.minWeight': '0.75',
                        'merge.relWeightLead': '0',
                        'merge.maxIter': '10',
                        'merge.revertDist': '5',
                        'merge.revertInterval': '1',
                        'merge.searchGeneration': '4',
                        'merge.preventIntersection': '1',
                        'inFile': 'edges1.shp',
                        'outFile': 'edges2.shp'
                    }, [
                        "inFile", "outFile", "method", "maxAngleDev",
                        "snapRadius", "merge\..*"
                    ])
                lt2scroll.setFixedHeight(lt2scroll.height() - 200)
                self.modules['lt2'] = lt2mod
                ls.addRow(lt2scroll)

                lt3mod, lt3scroll = QpalsModuleBase.QpalsModuleBase.createGroupBox(
                    "opalsLineTopology", "opalsLineTopology (3)", self.project,
                    {
                        'method': 'longest',
                        'minLength': '25',
                        'snapRadius': '0',
                        'maxTol': '0',
                        'maxAngleDev': '90;15',
                        'avgDist': '3',
                        'inFile': 'edges2.shp',
                        'outFile': 'edges3.shp'
                    }, ["inFile", "outFile", "method", "minLength", "maxTol"])
                self.modules['lt3'] = lt3mod
                ls.addRow(lt3scroll)
                lt3mod.afterRun = self.add2DLines

            if name == "Editing":
                desc = QtWidgets.QLabel(
                    "Please start editing the 2D approximations that have been loaded into qgis. Here are some tools "
                    "that might help:")
                desc.setWordWrap(True)
                ls.addRow(desc)

                box1 = QtWidgets.QGroupBox("QuickLineModeller")
                from . import QpalsQuickLM
                self.quicklm = QpalsQuickLM.QpalsQuickLM(
                    project=self.project,
                    layerlist=self.layerlist,
                    iface=self.iface)
                box1.setLayout(self.quicklm.fl)
                ls.addRow(box1)
                box2 = QtWidgets.QGroupBox("qpalsSection")
                from . import QpalsSection
                self.section = QpalsSection.QpalsSection(
                    project=self.project,
                    layerlist=self.layerlist,
                    iface=self.iface)
                self.section.createWidget()
                box2.setLayout(self.section.ls)
                box2.setSizePolicy(QtWidgets.QSizePolicy.Expanding,
                                   QtWidgets.QSizePolicy.Expanding)
                ls.addRow(box2)

            if name == "3D-Modelling":
                desc = QtWidgets.QLabel(
                    "The 2D approximations can now be used to model 3D breaklines in the pointcloud/the DTM."
                )
                desc.setWordWrap(True)
                ls.addRow(desc)

                lmmod, lmscroll = QpalsModuleBase.QpalsModuleBase.createGroupBox(
                    "opalsLineModeler",
                    "opalsLineModeler",
                    self.project,
                    {  #"filter": "Class[Ground]",
                        "approxFile": "edges3.shp",
                        "outFile": "modelled_lines.shp"
                    },
                    [
                        "inFile", "approxFile", "outFile", "filter",
                        "patchLength", "patchWidth", "overlap", "angle",
                        "minLength", "pointCount", "sigmaApriori"
                    ])
                self.modules['lm'] = lmmod
                ls.addRow(lmscroll)

                lmmod.afterRun = self.add3DLines

            if name == "Editing (3D)":
                desc = QtWidgets.QLabel(
                    "Before exporting the final product, there are a few tools to check the "
                    "quality of the result. This includes a topological check as well as a search"
                    "for points that have a big height difference to the DTM - and might be erraneous."
                )

                desc.setWordWrap(True)
                ls.addRow(desc)

                self.startQualityCheckBtn = QtWidgets.QPushButton(
                    "Start calculation")
                self.startQualityCheckBtn.clicked.connect(
                    self.runProblemSearchAsync)
                self.QualityCheckbar = QtWidgets.QProgressBar()
                self.QualityCheckDtm = QgsMapLayerComboBox()
                self.QualityCheckDtm.setFilters(
                    QgsMapLayerProxyModel.RasterLayer)
                self.QualityCheckThreshold = QtWidgets.QLineEdit("0.5")
                ls.addRow(
                    QtWidgets.QLabel("DTM Layer to compare heights with"),
                    self.QualityCheckDtm)
                ls.addRow(
                    QtWidgets.QLabel("Set height difference threshold [m]"),
                    self.QualityCheckThreshold)
                hb = QtWidgets.QHBoxLayout()
                hb.addWidget(self.QualityCheckbar)
                hb.addWidget(self.startQualityCheckBtn)
                ls.addRow(hb)
                line = QtWidgets.QFrame()
                line.setFrameShape(QtWidgets.QFrame.HLine)
                line.setFrameShadow(QtWidgets.QFrame.Sunken)
                ls.addRow(line)

                self.editingls = ls

                self.edit3d_linelayerbox = QgsMapLayerComboBox()
                self.edit3d_linelayerbox.setFilters(
                    QgsMapLayerProxyModel.LineLayer)
                self.edit3d_pointlayerbox = QgsMapLayerComboBox()
                self.edit3d_pointlayerbox.setFilters(
                    QgsMapLayerProxyModel.PointLayer)
                self.edit3d_dtmlayerbox = QgsMapLayerComboBox()
                self.edit3d_dtmlayerbox.setFilters(
                    QgsMapLayerProxyModel.RasterLayer)
                self.edit3d_pointlayerbox.currentIndexChanged.connect(
                    self.nodeLayerChanged)

                self.edit3d_currPointId = QSpinBox()
                self.edit3d_currPointId.setMinimum(0)
                self.edit3d_currPointId.valueChanged.connect(
                    self.showProblemPoint)

                ls.addRow("Select Line Layer:", self.edit3d_linelayerbox)
                ls.addRow("Select Problem Point layer:",
                          self.edit3d_pointlayerbox)

                self.selectNodeBtn = QtWidgets.QPushButton("Next point")
                self.selectNodeBtn.clicked.connect(
                    lambda: self.edit3d_currPointId.setValue(
                        self.edit3d_currPointId.value() + 1))

                self.selectPrevNodeBtn = QtWidgets.QPushButton("Prev point")
                self.selectPrevNodeBtn.clicked.connect(
                    lambda: self.edit3d_currPointId.setValue(
                        self.edit3d_currPointId.value() - 1))
                self.edit3d_countLabel = QtWidgets.QLabel()

                self.snapToDtmBtn = QtWidgets.QPushButton("Snap to:")
                self.snapToDtmBtn.clicked.connect(self.snapToDtm)
                self.remonveNodeBtn = QtWidgets.QPushButton("Remove")
                self.remonveNodeBtn.clicked.connect(self.removeNode)

                nextBox = QtWidgets.QHBoxLayout()
                nextBox.addWidget(QtWidgets.QLabel("Current point:"))
                nextBox.addWidget(self.edit3d_currPointId)
                nextBox.addWidget(QtWidgets.QLabel("/"))
                nextBox.addWidget(self.edit3d_countLabel)
                nextBox.addStretch()

                nextBox.addWidget(self.snapToDtmBtn)
                nextBox.addWidget(self.edit3d_dtmlayerbox)
                nextBox.addWidget(self.remonveNodeBtn)
                nextBox.addWidget(self.selectPrevNodeBtn)
                nextBox.addWidget(self.selectNodeBtn)

                ls.addRow(nextBox)
                self.nodeLayerChanged()

            if name == "Export":
                exp2mod, exp2scroll = QpalsModuleBase.QpalsModuleBase.createGroupBox(
                    "opalsTranslate", "opalsTranslate", self.project, {
                        'oformat': 'shp',
                        'inFile': 'modelled_lines.shp',
                        'outFile': 'STRULI3D.shp',
                    }, ["inFile", "outFile"])

                self.modules['exp'] = exp2mod
                ls.addRow(exp2scroll)

            vl = QtWidgets.QVBoxLayout()
            vl.addLayout(ls, 1)
            navbar = QtWidgets.QHBoxLayout()
            next = QtWidgets.QPushButton("Next step >")
            next.clicked.connect(self.switchToNextTab)
            prev = QtWidgets.QPushButton("< Previous step")
            prev.clicked.connect(self.switchToPrevTab)
            runcurr = QtWidgets.QPushButton(
                "Run this step (all modules above)")
            runcurr.clicked.connect(lambda: self.run_step(None))
            if idx > 0:
                navbar.addWidget(prev)
            navbar.addStretch()
            if name in [
                    "DTM", "Slope", "2D-Approximation", "Topologic correction",
                    "3D-Modelling", "Export"
            ]:
                navbar.addWidget(runcurr)
            navbar.addStretch()
            if idx < len(self.names):
                navbar.addWidget(next)
            vl.addLayout(navbar)
            self.widgets[name].setLayout(vl)
            self.tabs.addTab(self.widgets[name], name)

        # set up connections

        self.tabs.currentChanged.connect(self.updateTabs)
        return self.scrollwidget
Exemplo n.º 16
0
    def __init__(self, parent=None):  # pylint: disable=too-many-statements
        super().__init__(parent)

        self.setWindowTitle(self.tr('Redistrict Plugin | Settings'))
        layout = QVBoxLayout()
        self.auth_label = QLabel(self.tr('Authentication configuration'))
        layout.addWidget(self.auth_label)
        self.auth_value = QgsAuthConfigSelect()
        layout.addWidget(self.auth_value)
        auth_id = get_auth_config_id()
        if auth_id:
            self.auth_value.setConfigId(auth_id)

        layout.addWidget(QLabel(self.tr('API base URL')))
        self.base_url_edit = QLineEdit()
        self.base_url_edit.setText(QgsSettings().value('redistrict/base_url', '', str, QgsSettings.Plugins))
        layout.addWidget(self.base_url_edit)

        h_layout = QHBoxLayout()
        h_layout.addWidget(QLabel(self.tr('Check for completed requests every')))
        self.check_every_spin = QSpinBox()
        self.check_every_spin.setMinimum(10)
        self.check_every_spin.setMaximum(600)
        self.check_every_spin.setSuffix(' ' + self.tr('s'))
        self.check_every_spin.setValue(QgsSettings().value('redistrict/check_every', '30', int, QgsSettings.Plugins))

        h_layout.addWidget(self.check_every_spin)
        layout.addLayout(h_layout)

        self.use_mock_checkbox = QCheckBox(self.tr('Use mock Statistics NZ API'))
        self.use_mock_checkbox.setChecked(get_use_mock_api())
        layout.addWidget(self.use_mock_checkbox)

        self.test_button = QPushButton(self.tr('Test API connection'))
        self.test_button.clicked.connect(self.test_api)
        layout.addWidget(self.test_button)

        self.use_overlays_checkbox = QCheckBox(self.tr('Show updated populations during interactive redistricting'))
        self.use_overlays_checkbox.setChecked(
            QgsSettings().value('redistrict/show_overlays', False, bool, QgsSettings.Plugins))
        layout.addWidget(self.use_overlays_checkbox)

        self.use_sound_group_box = QGroupBox(self.tr('Use audio feedback'))
        self.use_sound_group_box.setCheckable(True)
        self.use_sound_group_box.setChecked(
            QgsSettings().value('redistrict/use_audio_feedback', False, bool, QgsSettings.Plugins))

        sound_layout = QGridLayout()
        sound_layout.addWidget(QLabel(self.tr('When meshblock redistricted')), 0, 0)
        self.on_redistrict_file_widget = QgsFileWidget()
        self.on_redistrict_file_widget.setDialogTitle(self.tr('Select Audio File'))
        self.on_redistrict_file_widget.setStorageMode(QgsFileWidget.GetFile)
        self.on_redistrict_file_widget.setFilePath(
            QgsSettings().value('redistrict/on_redistrict', '', str, QgsSettings.Plugins))
        self.on_redistrict_file_widget.setFilter(self.tr('Wave files (*.wav *.WAV)'))
        sound_layout.addWidget(self.on_redistrict_file_widget, 0, 1)
        self.play_on_redistrict_sound_button = QPushButton(self.tr('Test'))
        self.play_on_redistrict_sound_button.clicked.connect(self.play_on_redistrict_sound)
        sound_layout.addWidget(self.play_on_redistrict_sound_button, 0, 2)

        self.use_sound_group_box.setLayout(sound_layout)
        layout.addWidget(self.use_sound_group_box)

        button_box = QDialogButtonBox(
            QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        layout.addWidget(button_box)
        button_box.rejected.connect(self.reject)
        button_box.accepted.connect(self.accept)

        self.setLayout(layout)