class ApiWithQtDialog(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, parent=None):
        """Constructor."""
        super(ApiWithQtDialog, self).__init__(parent)
        # Set up the user interface from Designer through FORM_CLASS.
        # After self.setupUi() you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect

        # additional widgets setting
        self.btn = QPushButton("Launch")
        self.lbl_expected = QLabel()
        self.lbl_expected.setAlignment(Qt.AlignCenter)
        self.lbl_found = QLabel()
        self.lbl_found.setAlignment(Qt.AlignCenter)

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.btn)
        self.layout.addWidget(self.lbl_expected)
        self.layout.addWidget(self.lbl_found)

        self.setLayout(self.layout)

        # original ui setup line
        self.setupUi(self)
Esempio n. 2
0
    def _setupUI(self):
        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)

        self.setMinimumHeight(180)

        self.main_horizontal_layout = QHBoxLayout(self)

        italic_font = QFont()
        italic_font.setItalic(True)

        # deselected widget
        self.deselected_widget = QListWidget(self)
        self._set_list_widget_defaults(self.deselected_widget)
        deselected_label = QLabel()
        deselected_label.setText('Deselected')
        deselected_label.setAlignment(Qt.AlignCenter)
        deselected_label.setFont(italic_font)
        deselected_v_layout = QVBoxLayout()
        deselected_v_layout.addWidget(deselected_label)
        deselected_v_layout.addWidget(self.deselected_widget)

        # selected widget
        self.selected_widget = QListWidget(self)
        self._set_list_widget_defaults(self.selected_widget)
        selected_label = QLabel()
        selected_label.setText('Selected')
        selected_label.setAlignment(Qt.AlignCenter)
        selected_label.setFont(italic_font)
        selected_v_layout = QVBoxLayout()
        selected_v_layout.addWidget(selected_label)
        selected_v_layout.addWidget(self.selected_widget)

        # buttons
        self.buttons_vertical_layout = QVBoxLayout()
        self.buttons_vertical_layout.setContentsMargins(0, -1, 0, -1)

        self.select_all_btn = SmallQPushButton('>>')
        self.deselect_all_btn = SmallQPushButton('<<')
        self.select_btn = SmallQPushButton('>')
        self.deselect_btn = SmallQPushButton('<')
        self.select_btn.setToolTip('Add the selected items')
        self.deselect_btn.setToolTip('Remove the selected items')
        self.select_all_btn.setToolTip('Add all')
        self.deselect_all_btn.setToolTip('Remove all')

        # add buttons
        spacer_label = QLabel()  # pragmatic way to create a spacer with
        # the same height of the labels on top
        # of the lists, in order to align the
        # buttons with the lists.
        self.buttons_vertical_layout.addWidget(spacer_label)
        self.buttons_vertical_layout.addWidget(self.select_btn)
        self.buttons_vertical_layout.addWidget(self.deselect_btn)
        self.buttons_vertical_layout.addWidget(self.select_all_btn)
        self.buttons_vertical_layout.addWidget(self.deselect_all_btn)

        # add sub widgets
        self.main_horizontal_layout.addLayout(deselected_v_layout)
        self.main_horizontal_layout.addLayout(self.buttons_vertical_layout)
        self.main_horizontal_layout.addLayout(selected_v_layout)
Esempio n. 3
0
class AddRasterDialog(QDialog):
    def __init__(self):
        super(QDialog, self).__init__()
        self.resize(410, 200)
        self.setWindowTitle('Add Raster Layer Dialog')
        self.label = QLabel(self)
        self.label.setGeometry(QtCore.QRect(20, 20, 300, 100))
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setText(
            'The requested ressource is a raster layer. \n'
            'Depending on it\'s size\', downloading \nand importing it to QGIS'
            'may \ntake while. You can also consider to only import the\n'
            'layer as a WMS if you only need to view it')
        self.cancelbutton = QPushButton(self)
        self.cancelbutton.setText('Cancel')
        self.cancelbutton.setGeometry(QtCore.QRect(20, 150, 125, 30))
        self.wmsbutton = QPushButton(self)
        self.wmsbutton.setText('Add as WMS Layer')
        self.wmsbutton.setGeometry(QtCore.QRect(150, 150, 125, 30))
        self.rasterbutton = QPushButton(self)
        self.rasterbutton.setText('Add as Raster Layer')
        self.rasterbutton.setGeometry(QtCore.QRect(280, 150, 125, 30))

        # we reconfigure the already existing slot self.done() (inherited
        # from QDialog to emit different ints - self.done() is called by
        # exec_())
        self.cancelbutton.clicked.connect(lambda: self.done(0))
        self.wmsbutton.clicked.connect(lambda: self.done(1))
        self.rasterbutton.clicked.connect(lambda: self.done(2))
    def progress_bar(self):
        try:
            return self._progress_bar
        except AttributeError:
            message_bar_item = QgsMessageBarItem("")

            label = QLabel(self.tr("Computing cartogram"))
            label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
            message_bar_item.layout().addWidget(label)

            progress_bar = QProgressBar()
            progress_bar.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
            progress_bar.setMaximum(100)
            message_bar_item.layout().addWidget(progress_bar)

            cancel_button = QPushButton(self.tr("Cancel"))
            cancel_button.clicked.connect(self.cancel_task)
            message_bar_item.layout().addWidget(cancel_button)

            self.iface.messageBar().pushWidget(message_bar_item)
            self._progress_bar_message_bar_item = message_bar_item
            self._progress_bar = progress_bar
            self._cancel_button = cancel_button

            return self._progress_bar
Esempio n. 5
0
    def _setupUI(self):
        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)

        self.setMinimumHeight(180)

        self.main_horizontal_layout = QHBoxLayout(self)

        italic_font = QFont()
        italic_font.setItalic(True)

        # unselected widget
        self.unselected_widget = QListWidget(self)
        self._set_list_widget_defaults(self.unselected_widget)
        unselected_label = QLabel()
        unselected_label.setText("Unselected")
        unselected_label.setAlignment(Qt.AlignCenter)
        unselected_label.setFont(italic_font)
        unselected_v_layout = QVBoxLayout()
        unselected_v_layout.addWidget(unselected_label)
        unselected_v_layout.addWidget(self.unselected_widget)

        # selected widget
        self.selected_widget = QListWidget(self)
        self._set_list_widget_defaults(self.selected_widget)
        selected_label = QLabel()
        selected_label.setText("Selected")
        selected_label.setAlignment(Qt.AlignCenter)
        selected_label.setFont(italic_font)
        selected_v_layout = QVBoxLayout()
        selected_v_layout.addWidget(selected_label)
        selected_v_layout.addWidget(self.selected_widget)

        # buttons
        self.buttons_vertical_layout = QVBoxLayout()
        self.buttons_vertical_layout.setContentsMargins(0, -1, 0, -1)

        self.select_all_btn = SmallQPushButton(">>")
        self.deselect_all_btn = SmallQPushButton("<<")
        self.select_btn = SmallQPushButton(">")
        self.deselect_btn = SmallQPushButton("<")
        self.select_btn.setToolTip("Add the selected items")
        self.deselect_btn.setToolTip("Remove the selected items")
        self.select_all_btn.setToolTip("Add all")
        self.deselect_all_btn.setToolTip("Remove all")

        # add buttons
        spacer_label = QLabel()  # pragmatic way to create a spacer with
        # the same height of the labels on top
        # of the lists, in order to align the
        # buttons with the lists.
        self.buttons_vertical_layout.addWidget(spacer_label)
        self.buttons_vertical_layout.addWidget(self.select_btn)
        self.buttons_vertical_layout.addWidget(self.deselect_btn)
        self.buttons_vertical_layout.addWidget(self.select_all_btn)
        self.buttons_vertical_layout.addWidget(self.deselect_all_btn)

        # add sub widgets
        self.main_horizontal_layout.addLayout(unselected_v_layout)
        self.main_horizontal_layout.addLayout(self.buttons_vertical_layout)
        self.main_horizontal_layout.addLayout(selected_v_layout)
Esempio n. 6
0
 def _setup_table(self, prechecked_elements, state_list, state_list_enables,
                  partly_disabled, disable_fancy, auto_depresso):
     self.signalMapper = QtCore.QSignalMapper(self)
     self.signalMapper.mapped[QWidget].connect(self.previewToggler)
     self.signalMapper2 = QtCore.QSignalMapper(self)
     self.signalMapper2.mapped[QWidget].connect(self.elementToggler)
     self.signalMapper3 = QtCore.QSignalMapper(self)
     self.signalMapper3.mapped[QWidget].connect(self.emit_right_clicked)
     self.signalMapper4 = QtCore.QSignalMapper(self)
     self.signalMapper4.mapped[QWidget].connect(self.focus_on_toggler)
     self.signalMapper5 = QtCore.QSignalMapper(self)
     self.signalMapper5.mapped[QWidget].connect(self.focus_off_toggler)
     self.signalMapper6 = QtCore.QSignalMapper(self)
     self.signalMapper6.mapped[QWidget].connect(self.emit_triggered)
     is_checkable = not auto_depresso
     for i in pt_indexes:
         pt_button = HoverableButton(i,
                                     partly_disabled=partly_disabled,
                                     disable_fancy=disable_fancy,
                                     is_checkable=is_checkable)
         pt_button.setMinimumSize(16, 16)
         pt_button.setMaximumSize(512, 512)
         if i in prechecked_elements:
             pt_button.setChecked(True)
         self.layout().addWidget(pt_button, pt_indexes[i][0],
                                 pt_indexes[i][1])
         # pt_button.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
         pt_button.hoverChanged.connect(self.signalMapper.map)
         pt_button.toggled.connect(self.signalMapper2.map)
         pt_button.rightClicked.connect(self.signalMapper3.map)
         pt_button.gainedFocus.connect(self.signalMapper4.map)
         pt_button.lostFocus.connect(self.signalMapper5.map)
         pt_button.pressed.connect(self.signalMapper6.map)
         self.signalMapper.setMapping(pt_button, pt_button)
         self.signalMapper2.setMapping(pt_button, pt_button)
         self.signalMapper3.setMapping(pt_button, pt_button)
         self.signalMapper4.setMapping(pt_button, pt_button)
         self.signalMapper5.setMapping(pt_button, pt_button)
         self.signalMapper6.setMapping(pt_button, pt_button)
     line = QFrame()
     line.setFrameShape(QFrame.HLine)
     line.setFrameShadow(QFrame.Sunken)
     line.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)
     self.layout().addWidget(line, 6, 3, 1, 15)
     # dissable elements/buttons for provided list:
     if state_list_enables:
         disabled_elements = set(pt_indexes).difference(state_list)
     else:
         disabled_elements = state_list
     for i in disabled_elements:
         self.getButton(pt_indexes[i]).setEnabled(False)
     lant_text = QLabel('Lan')
     act_text = QLabel('Act')
     lant_text.setAlignment(QtCore.Qt.AlignCenter)
     act_text.setAlignment(QtCore.Qt.AlignCenter)
     self.layout().addWidget(lant_text, 5, 2)
     self.layout().addWidget(act_text, 6, 2)
     lant_text.setEnabled(False)
     act_text.setEnabled(False)
class ConnectCredentialsWidget(QWidget):
    rememberStateChanged = pyqtSignal(int)

    def __init__(self, parent=None):
        QWidget.__init__(self, parent)

        self.leLogin = IconLineEdit(self)
        self.leLogin.setIcon(QIcon(os.path.join(iconsPath, "envelope.svg")))
        self.leLogin.setPlaceholderText("Email")

        self.lePassword = PasswordLineEdit(self)

        self.chkRemember = QCheckBox(self)
        self.chkRemember.setText("Remember me")

        self.lblResetPassword = QLabel(self)
        self.lblResetPassword.setAlignment(Qt.AlignCenter)
        self.lblResetPassword.setOpenExternalLinks(True)
        self.lblResetPassword.setTextInteractionFlags(Qt.LinksAccessibleByKeyboard | Qt.LinksAccessibleByMouse)
        self.lblResetPassword.setText("<html><head/><body><p><a href='https://boundlessgeo.auth0.com/login?client=rmtncamSKiwRBuVYTvFYJGtTspVuplMh'><span style='text-decoration: underline; color:#0000ff;'>Don't remember your password?</span></a></p></body></html>")

        self.lblRegister = QLabel(self)
        self.lblRegister.setAlignment(Qt.AlignCenter)
        self.lblRegister.setOpenExternalLinks(True)
        self.lblRegister.setTextInteractionFlags(Qt.LinksAccessibleByKeyboard | Qt.LinksAccessibleByMouse)
        self.lblRegister.setText("<html><head/><body><p><a href='https://connect.boundlessgeo.com'><span style='text-decoration: underline; color:#0000ff;'>Don't have an account?</span></a></p></body></html>")

        self.layout = QVBoxLayout(self)
        self.layout.addWidget(self.leLogin)
        self.layout.addWidget(self.lePassword)
        self.layout.addWidget(self.chkRemember)
        self.layout.addWidget(self.lblResetPassword)
        self.layout.addWidget(self.lblRegister)
        self.setLayout(self.layout)

        self.chkRemember.stateChanged.connect(self.rememberCheckChanged)


    def login(self):
        return self.leLogin.text()

    def setLogin(self, login):
        self.leLogin.setText(login)

    def password(self):
        return self.lePassword.text()

    def setPassword(self, password):
        self.lePassword.setText(password)

    def remember(self):
        return self.chkRemember.isChecked()

    def setRemember(self, state):
        self.chkRemember.setCheckState(state)

    def rememberCheckChanged(self, state):
        self.rememberStateChanged.emit(state)
Esempio n. 8
0
    def fill_row(self, receiver_name, parcel_count, row):
        # First add a spacer between previoud data row (could be the title) and the next row data
        v_spacer = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Preferred)
        self.grb_summary.layout().addItem(v_spacer, row, 0)

        # Now, let's add a row of data
        w = QLabel(receiver_name)
        self.grb_summary.layout().addWidget(w, row+1, 0)
        w = QLabel(str(parcel_count))
        w.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        self.grb_summary.layout().addWidget(w, row+1, 2)
Esempio n. 9
0
 def _create_labels(self):
     for i in range(len(self.steps)):
         if i != 0:
             spacer = QSpacerItem(
                 self.label_spacing_width,
                 0,
                 QSizePolicy.Expanding,
                 QSizePolicy.Minimum,
             )
             self.layout_labels.addItem(spacer)
         label = QLabel(self.steps[i])
         label.font_size = 11
         label.setWordWrap(True)
         label.setAlignment(Qt.AlignCenter)
         label.setFixedWidth(self.label_width)
         self.layout_labels.addWidget(label)
         self.widgets[i].append(label)
Esempio n. 10
0
class AuthWidget(QWidget):
    def __init__(self):
        super().__init__()

        self.btn = QPushButton("Launch")
        self.lbl_expected = QLabel()
        self.lbl_expected.setAlignment(Qt.AlignCenter)
        self.lbl_found = QLabel()
        self.lbl_found.setAlignment(Qt.AlignCenter)

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.btn)
        self.layout.addWidget(self.lbl_expected)
        self.layout.addWidget(self.lbl_found)
        self.setLayout(self.layout)

        self.setWindowTitle("Connect to Isogeo API using PyQT")
    def mk_prj_storage_icon(self, qgs_type_storage: str) -> QLabel:
        """Returns a QLabel with the matching icon for the storage type.

        :param qgs_type_storage: storage type
        :type qgs_type_storage: str
        :return: QLabel to be set in a cellWidget
        :rtype: QLabel
        """
        lbl_location_type = QLabel(self.tableWidget)
        lbl_location_type.setPixmap(
            QPixmap(icon_per_storage_type(qgs_type_storage)))
        lbl_location_type.setScaledContents(True)
        lbl_location_type.setMaximumSize(20, 20)
        lbl_location_type.setAlignment(Qt.AlignCenter)
        lbl_location_type.setTextInteractionFlags(Qt.NoTextInteraction)
        lbl_location_type.setToolTip(qgs_type_storage)

        return lbl_location_type
Esempio n. 12
0
 def _create_bar(self):
     for i in range(len(self.steps)):
         self.widgets[i] = []
         if i != 0:
             line = QFrame()
             line.setFrameShape(QFrame.HLine)
             line.setLineWidth(3)
             line.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
             line.setFixedHeight(self.bar_height)
             self.layout_bar.addWidget(line)
             self.widgets[i].append(line)
         dot = QLabel("•")
         dot.font_size = self.bar_height * 2.6
         dot.setFixedWidth(self.dot_width)
         dot.setFixedHeight(self.bar_height)
         dot.setAlignment(Qt.AlignCenter)
         self.layout_bar.addWidget(dot)
         self.widgets[i].append(dot)
    def offer_to_add_sample_dataset(self):
        """Display an error message in message bar that offers to add a sample dataset."""
        message_bar_item = self.iface.messageBar().createMessage(
            self.tr("Error"))

        label = QLabel(
            self.
            tr("You need at least one polygon vector layer to create a cartogram."
               ))
        label.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        message_bar_item.layout().addWidget(label)

        button = QPushButton(self.tr("Add sample dataset"))
        button.clicked.connect(
            functools.partial(self.add_sample_dataset_clicked,
                              message_bar_item=message_bar_item))
        message_bar_item.layout().addWidget(button)

        self.iface.messageBar().pushWidget(message_bar_item, Qgis.Critical)
Esempio n. 14
0
    def __get_custom_widget_item_for_result(self, qr_result):
        label = QLabel()

        if not qr_result:
            style = WIDGET_STYLE_QUALITY_RULE_INITIAL_STATE
            label.setText("0%")
        elif qr_result.level == EnumQualityRuleResult.SUCCESS:
            style = WIDGET_STYLE_QUALITY_RULE_SUCCESS
            icon = QIcon(
                ":/Asistente-LADM-COL/resources/images/qr_validation.svg")
            label.setPixmap(icon.pixmap(QSize(16, 16)))
        elif qr_result.level == EnumQualityRuleResult.ERRORS:
            style = WIDGET_STYLE_QUALITY_RULE_ERRORS
            label.setText(str(qr_result.record_count))
        elif qr_result.level == EnumQualityRuleResult.UNDEFINED:
            style = WIDGET_STYLE_QUALITY_RULE_UNDEFINED
        else:  # EnumQualityRuleResult.CRITICAL
            style = WIDGET_STYLE_QUALITY_RULE_CRITICAL

        label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        label.setStyleSheet("QLabel{}".format(style))

        return label
Esempio n. 15
0
class AuthWidget(QWidget):
    def __init__(self):
        super().__init__()

        self.lbl_expected = QLabel()
        self.lbl_expected.setAlignment(Qt.AlignCenter)
        self.lbl_found = QLabel()
        self.lbl_found.setAlignment(Qt.AlignCenter)
        self.lbl_selection = QLabel()
        self.lbl_selection.setAlignment(Qt.AlignCenter)
        self.kw_cbbox = CheckableComboBox()
        self.btn_reset = QPushButton("Reset")

        self.layout = QGridLayout()
        self.layout.addWidget(self.lbl_expected, 1, 0, 1, 2)
        self.layout.addWidget(self.lbl_found, 2, 0, 1, 2)
        self.layout.addWidget(self.kw_cbbox, 3, 0)
        self.layout.addWidget(self.btn_reset, 3, 1)
        self.layout.addWidget(self.lbl_selection, 4, 0, 1, 2)
        self.setLayout(self.layout)

        self.setWindowTitle("Select Isogeo keywords using PyQT")
Esempio n. 16
0
class TrackingDisplay(QToolBar):
    '''
        Display the position of a mobile and add action for centering
        the map on the vehicle and erasing the track
    '''
    def __init__(self, mobile, parent=None):
        super(TrackingDisplay, self).__init__(parent)
        self.setMovable(True)
        self.setFloatable(True)
        self.mobile = mobile
        self.timedOut = True
        self.lastFix = 0.0
        s = QSettings()
        self.defFormat = s.value('PosiView/Misc/DefaultFormat',
                                 defaultValue=0,
                                 type=int)
        self.format = self.defFormat & 3
        self.withSuff = cf.FlagDegreesUseStringSuffix if bool(
            self.defFormat & 4) else cf.FormatFlag(0)
        try:
            self.sep = cf.separator() + ' '
        except AttributeError:
            self.sep = ', '
        self.createActions()
        self.mobile.newPosition.connect(self.onNewPosition)
        self.mobile.timeout.connect(self.onTimeout)
        self.posText = '0.000000, 0.000000'

    def createActions(self):
        self.nameLabel = QLabel(self.mobile.name)
        self.nameLabel.setMinimumSize(80, 23)
        self.nameLabelAction = QWidgetAction(self)
        self.nameLabelAction.setDefaultWidget(self.nameLabel)
        self.addAction(self.nameLabelAction)

        self.enableAction = QAction("Enable Display", self)
        self.enableAction.setCheckable(True)
        self.enableAction.setChecked(True)
        icon = QIcon(':/plugins/PosiView/ledgrey.png')
        icon.addFile(':/plugins/PosiView/ledgreen.png', QSize(), QIcon.Normal,
                     QIcon.On)
        self.enableAction.setIcon(icon)
        self.addAction(self.enableAction)
        self.enableAction.triggered.connect(self.onEnableClicked)
        self.enableAction.triggered.connect(self.mobile.setEnabled)

        self.addSeparator()
        self.posLabel = QLabel("--:--:-- 0.000000, 0.000000")
        self.posLabel.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        widths = (180, 196, 204, 180, 184, 200, 208, 184)
        self.posLabel.setMinimumSize(widths[self.format], 23)
        self.posLabel.setStyleSheet(
            'background: red; font-size: 8pt; color: white;')
        self.posLabelAction = QWidgetAction(self)
        self.posLabelAction.setDefaultWidget(self.posLabel)
        self.addAction(self.posLabelAction)
        self.centerAction = QAction(QIcon(':/plugins/PosiView/center.png'),
                                    "Center &Map", self)
        self.addAction(self.centerAction)
        self.deleteTrackAction = QAction(
            QIcon(':/plugins/PosiView/deletetrack.png'), 'Delete &Track', self)
        self.addAction(self.deleteTrackAction)
        self.deleteTrackAction.triggered.connect(self.mobile.deleteTrack)
        self.centerAction.triggered.connect(self.mobile.centerOnMap)

    @pyqtSlot(float, QgsPointXY, float, float)
    def onNewPosition(self, fix, pos, depth, altitude):
        s = str()
        if fix > 0:
            s = strftime('%H:%M:%S   ', gmtime(fix))
        else:
            s = '--:--:-- '

        if self.format == 1:
            f, pr = cf.FormatDegreesMinutes, 4
        elif self.format == 2:
            f, pr = cf.FormatDegreesMinutesSeconds, 2
        else:
            f, pr = cf.FormatDecimalDegrees, 6
        self.posText = self.sep.join(
            (cf.formatY(pos.y(), f, pr, self.withSuff),
             cf.formatX(pos.x(), f, pr, self.withSuff)))
        s += self.posText
        if depth > -9999:
            s += "\nd = {:.1f}".format(depth)
        if altitude > -9999:
            if depth > -9999:
                s += "   alt = {:.1f}".format(altitude)
            else:
                s += "\nalt = {:.1f}".format(altitude)
        self.posLabel.setText(s)
        if self.timedOut:
            if fix > self.lastFix:
                self.posLabel.setStyleSheet(
                    'background: lime; font-size: 8pt; color: black;')
                self.timedOut = False
        self.lastFix = fix

    @pyqtSlot()
    def onTimeout(self):
        if not self.timedOut:
            self.timedOut = True
            self.posLabel.setStyleSheet(
                'background: red; font-size: 8pt; color: white;')

    @pyqtSlot(bool)
    def onEnableClicked(self, enable):
        self.timedOut = True
        if enable:
            self.posLabel.setStyleSheet(
                'background: red; font-size: 8pt; color: white;')
        else:
            self.posLabel.setStyleSheet(
                'background: white; font-size: 8pt; color: black;')

    def mousePressEvent(self, event):
        if event.button() == Qt.LeftButton:
            if event.modifiers() == Qt.ControlModifier:
                QGuiApplication.clipboard().setText(self.posText)
            else:
                drag = QDrag(self)
                mimeData = QMimeData()
                mimeData.setText(self.posText)
                drag.setMimeData(mimeData)
                drag.exec_()

    def releaseMobile(self):
        self.mobile = None
Esempio n. 17
0
class pyarchinit_dbmanagment(QDialog, MAIN_DIALOG_CLASS):

    MSG_BOX_TITLE = \
        'PyArchInit - pyarchinit_version 0.4 - Scheda gestione DB'
    HOME = os.environ['PYARCHINIT_HOME']
    BK = '{}{}{}'.format(HOME, os.sep, "pyarchinit_db_backup")

    def __init__(self, iface):
        super().__init__()
        self.iface = iface
        self.setupUi(self)

        # self.customize_GUI() #call for GUI customizations

        self.currentLayerId = None

    def enable_button(self, n):

        self.backup.setEnabled(n)

    def enable_button_search(self, n):

        self.backup.setEnabled(n)

    def on_backupsqlite_pressed(self):
        conn = Connection()
        conn_str = conn.conn_str()

        a = conn_str.lstrip('sqlite:///')
        home = os.environ['PYARCHINIT_HOME']
        # conn_import = '%s%s%s' % (home, os.sep,
        # 'pyarchinit_DB_folder/pyarchinit_db.sqlite'
        # )

        #conn_export = '%s%s%s' % (home, os.sep,
        #'pyarchinit_db_backup/pyarchinit_db_'
        #+ time.strftime('%Y%m%d_%H_%M_%S_')
        #+ '.sqlite')

        PDF_path = '%s%s%s' % (home, os.sep, 'pyarchinit_db_backup/')

        cfg_rel_path = os.path.join(os.sep, 'pyarchinit_DB_folder',
                                    'config.cfg')
        file_path = '{}{}'.format(home, cfg_rel_path)
        conf = open(file_path, "r")

        data = conf.read()
        settings = Settings(data)
        settings.set_configuration()
        conf.close()

        dump_dir = PDF_path
        db_username = settings.USER
        host = settings.HOST
        port = settings.PORT
        database_password = settings.PASSWORD

        db_names = settings.DATABASE
        conn_export = '%s' % (dump_dir + 'backup_' + db_names)

        b = shutil.copy(a, conn_export)

        i = 0

        for c in b:

            if i == 0:
                self.progress = self.progressBar_db  #("Please Wait!", "Cancel", 0, 100, MainWindow)

                self.progress.setWindowModality(Qt.WindowModal)

                self.progress.setWindowTitle(
                    "Loading, Please Wait! (Cloudflare Protection)")

                self.progress.setMinimum(0)

                self.progress.setMaximum(100)

                self.progress.resize(1000, 100)

                self.progress.show()

                self.progress.setValue(0)

                self.progress.setValue(100)
                self.setLayout(QVBoxLayout())
                self.layout().addWidget(self.progress)

            else:
                self.image = QLabel('Backup Falied')
                self.image.setAlignment(Qt.AlignCenter)
                self.layout().addWidget(self.image)

    def on_backup_pressed(self):

        home = os.environ['PYARCHINIT_HOME']

        PDF_path = '%s%s%s' % (home, os.sep, 'pyarchinit_db_backup/')

        cfg_rel_path = os.path.join(os.sep, 'pyarchinit_DB_folder',
                                    'config.cfg')
        file_path = '{}{}'.format(home, cfg_rel_path)
        conf = open(file_path, "r")

        data = conf.read()
        settings = Settings(data)
        settings.set_configuration()
        conf.close()

        dump_dir = PDF_path
        db_username = settings.USER
        host = settings.HOST
        port = settings.PORT
        database_password = settings.PASSWORD

        db_names = settings.DATABASE

        dumper = '-U %s -h %s -p %s -Z 9 -f %s -Fc %s'

        bkp_file = '%s_%s.backup' % (db_names, time.strftime('%Y%m%d_%H_%M'))

        file_path = os.path.join(dump_dir, bkp_file)
        command = 'pg_dump ' + dumper % (db_username, host, port, file_path,
                                         db_names)
        try:
            p = subprocess.Popen(command, shell=False)
        except Exception as e:
            QMessageBox.warning(self, "INFO", str(e), QMessageBox.Ok)
        #subprocess.call('gzip ' + file_path, shell=False)

        i = 0

        for c in command:
            if i == 0:
                self.progress = self.progressBar_db  #("Please Wait!", "Cancel", 0, 100, MainWindow)

                self.progress.setWindowModality(Qt.WindowModal)

                self.progress.setMinimum(0)

                self.progress.setMaximum(100)

                self.progress.setWindowTitle(
                    "Loading, Please Wait! (Cloudflare Protection)")

                self.progress.resize(1000, 100)

                self.progress.show()

                self.progress.setValue(0)

                self.progress.setValue(100)
                self.setLayout(QVBoxLayout())
                self.layout().addWidget(self.progress)

            else:
                self.image = QLabel('Backup Falied')
                self.image.setAlignment(Qt.AlignCenter)
                self.layout().addWidget(self.image)

    # def on_backup_total_pressed(self):

    # home = os.environ['PYARCHINIT_HOME']
    # PDF_path = '%s%s%s' % (home, os.sep, 'pyarchinit_db_backup/')
    # filename = '%s%s%s' % (PDF_path, os.sep, 'semivariogramma.png')

    # username = '******'

    # defaultdb = 'postgres'

    # port = '5432'

    # backupdir = PDF_path

    # date = time.strftime('%Y-%m-%d-%H-%M-%S')

    # GET DB NAMES

    # get_db_names = \
    # "psql -U%s -d%s -p%s --tuples-only -c '\l' | awk -F\| '{ print $1 }' | grep -E -v '(template0|template1|^$)'" \
    # % (username, defaultdb, port)

    # MAKE BACKUP OF SYSTEMGRANTS

    # os.popen('pg_dumpall -p%s -g|gzip -9 -c > %s/system.%s.gz'
    # % (port, backupdir, date))

    # MAKING DB BACKUP

    # for base in os.popen(get_db_names).readlines():
    # try:

    # app = QtGui.QApplication(sys.argv)

    # barra = QProgressBar(self)
    # barra.show()
    # barra.setMinimum(0)
    # barra.setMaximum(9)
    # for a in range(10):
    # time.sleep(1)
    # barra.setValue(a)

    # app.exec_()....

    # base = base.strip()
    # fulldir = backupdir + base
    # if not os.path.exists(fulldir):
    # os.mkdir(fulldir)
    # filename = '%s/%s-%s.sql' % (fulldir, base, date)
    # os.popen('nice -n 19 pg_dump -C -F c -U%s -p%s %s > %s'
    # % (username, port, base, filename))
    # QMessageBox.warning(self, 'Messaggio',
    # 'Backup completato', QMessageBox.Ok)
    # except Exception as e:
    # QMessageBox.warning(self, 'Messaggio',
    # 'Backup fallito!!' + str(e),
    # QMessageBox.Ok)

    def on_upload_pressed(self):
        s = QgsSettings()
        dbpath = QFileDialog.getOpenFileName(self, "Set file name", self.BK,
                                             " backup (*.backup)")[0]
        #filename=dbpath.split("/")[-1]
        if dbpath:
            self.lineEdit_bk_path.setText(dbpath)
            s.setValue('', dbpath)

    def on_restore_pressed(self):
        try:

            # barra = QProgressBar(self)
            # barra.show()
            # barra.setMinimum(0)
            # barra.setMaximum(9)
            # for a in range(10):
            # time.sleep(1)
            # barra.setValue(a)

            path = self.lineEdit_bk_path.text()

            home = os.environ['PYARCHINIT_HOME']

            BK_path = '%s%s%s' % (home, os.sep, 'pyarchinit_db_backup/')

            cfg_rel_path = os.path.join(os.sep, 'pyarchinit_DB_folder',
                                        'config.cfg')
            file_path = '{}{}'.format(home, cfg_rel_path)
            conf = open(file_path, "r")

            data = conf.read()
            settings = Settings(data)
            settings.set_configuration()
            conf.close()

            dump_dir = BK_path
            db_username = self.lineEdit_username_wt.text()
            host = self.lineEdit_host_wt.text()
            port = self.lineEdit_port_wt.text()
            database_password = self.lineEdit_pass_wt.text()

            db_names = self.lineEdit_database_wt.text()
            #os.popen('dropdb -U postgres pyarchinit')
            drop = '-h %s -p %s -U %s %s'
            command1 = 'dropdb ' + drop % (host, port, db_username, db_names)
            try:
                subprocess.call(command1, shell=False)
            except:
                pass
            create = '-h %s -p %s -U %s -e %s -E UTF8 -T template_postgis'
            command2 = 'createdb ' + create % (host, port, db_username,
                                               db_names)
            subprocess.call(command2, shell=False)

            #os.popen('createdb -U postgres -p 5432 -h localhost -E UTF8  -T template_postgis_20 -e pyarchinit')
            restore = '--host %s --port %s --username %s --dbname %s --role postgres  %s'
            command = 'pg_restore ' + restore % (host, port, db_username,
                                                 db_names, path)

            subprocess.call(command, shell=False)

            QMessageBox.warning(self, 'Messaggio', 'Ripristino completato',
                                QMessageBox.Ok)
        except Exception as e:
            QMessageBox.warning(self, 'Messaggio',
                                'Ripristino fallito!!' + str(e),
                                QMessageBox.Ok)
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()
Esempio n. 19
0
#!/usr/bin/python
Esempio n. 20
0
class gpx_to_3d(QDialog):

    # Open Qgis Aplication, for using his function
    # I think there is a better way to start, but by the moment I don't know how
    #QgsApplication.setPrefixPath('/usr', True)
    #qgs = QgsApplication([], False)
    #qgs.initQgis()

    # Initialize window and create Graphic User Interface
    def __init__(self):
        super().__init__()
        self.setWindowTitle("GPX TO 3D")
        #QgsApplication.setPrefixPath('/usr', True)
        #self.qgs = QgsApplication([], False)
        #self.qgs.initQgis()

        # File to show in map
        self.Output_KML_File = 'C:/Roberto/Visual_Studio_Code/Sharing_Little_Things/Python/Qgis/GPX 3D/2019_E6_V8.gpx'
        self.Output_KML_File = 'C:/Roberto/Visual_Studio_Code/Sharing_Little_Things/Python/Qgis/GPX 3D/2019_E6_V8_3D.kml'
        #self.Output_KML_File=None
        self.initGui()

    def select_file(self):
        # User select the file to converter and start convertion
        filename, _ = QFileDialog.getOpenFileName(
            self, 'Select GPX File / Selecciona Fichero GPX',
            os.path.dirname(__file__), 'TRACK (*.gpx *.kml)')
        if filename:
            # Start convertion
            self.convert_track(filename)

            # Create a Profile
            self.profile()

            # Open Map
            map = see_map(self.Output_KML_File)
            map.exec_()
            self.info('Finished / Finalizado')

    def convert_track(self, filename):
        self.file_name = filename
        if self.file_name[-3:] == 'gpx':
            # Set parameters to load file like a layer. Get track like a points, not a line
            uri = self.file_name + "|layername=track_points"
            # Load Layer with points of track gpx o line KML
            self.points = QgsVectorLayer(uri, "Original Points", "ogr")
            # Check if load is correct
            if not self.points.isValid():
                self.info("Track failed to load! /n" + filename)
            else:
                self.info("Track Load Correct! " + filename)

        elif self.file_name[-3:] == 'kml':
            uri = self.file_name
            # Set parameters to load file like a layer. Get track like a line
            # Load Layer with points of track gpx o line KML
            lines = QgsVectorLayer(uri, "Original Line", "ogr")
            # Check if load is correct
            if not lines.isValid():
                self.info("Track failed to load! /n" + filename)
            else:
                self.info("Track Load Correct! " + filename)

            # KML is a line convert line in points
            for line in lines.getFeatures():
                # Create a layer for points in memory
                self.points = QgsVectorLayer("Point?crs=epsg:4326&index=yes",
                                             "Original Points", "memory")
                features = []
                for vertex in line.geometry().vertices():
                    feature = QgsFeature()
                    feature.setGeometry(vertex)
                    features.append(feature)

                self.points.dataProvider().addFeatures(features)

        # Set parameters to load the Digital Elevation Model of IGN
        if self.comboBox.currentIndex() == 3:
            uri = "dpiMode=7&identifier=mdt:Elevacion4258_1000&url=http://www.ign.es/wcs/mdt"
            uri2 = "dpiMode=7&identifier=Elevacion4258_1000&url=http://servicios.idee.es/wcs-inspire/mdt?version%3D1.1.2"
        elif self.comboBox.currentIndex() == 2:
            uri = "dpiMode=7&identifier=mdt:Elevacion4258_500&url=http://www.ign.es/wcs/mdt"
            uri2 = "dpiMode=7&identifier=Elevacion4258_500&url=http://servicios.idee.es/wcs-inspire/mdt?version%3D1.1.2"
        elif self.comboBox.currentIndex() == 1:
            uri = "dpiMode=7&identifier=mdt:Elevacion4258_200&url=http://www.ign.es/wcs/mdt"
            uri2 = "dpiMode=7&identifier=Elevacion4258_200&url=http://servicios.idee.es/wcs-inspire/mdt?version%3D1.1.2"
        else:
            uri = "dpiMode=7&identifier=mdt:Elevacion4258_25&url=http://www.ign.es/wcs/mdt"
            uri2 = "dpiMode=7&identifier=Elevacion4258_25&url=http://servicios.idee.es/wcs-inspire/mdt?version%3D1.1.2"

        DEM = QgsRasterLayer(uri, 'my wcs layer', 'wcs')

        if not DEM.isValid():
            self.info("DEM failed to load!")
        else:
            self.info("DEM Load Correct!")

        # For calculate distance between points
        d = QgsDistanceArea()
        d.setEllipsoid('WGS84')
        point_origin = 0

        # For make profile
        self.all_coord_m = []
        self.all_coord_z = []
        self.ymax = 0

        # Start to create KML file (firts lines of file)
        self.start_creation_kml()

        # Start to create GPX file (firts lines of file)
        self.start_creation_gpx()

        # For put time in points of track
        self.track_day = QDateTime.currentDateTime()

        # For each point in the track, analize information
        for point in self.points.getFeatures():
            # Get Geometry of feature like a point
            geompt = point.geometry().asPoint()
            if not DEM.isValid():
                if self.file_name[-3:] == 'kml':
                    elevation = [0, 0]
                else:
                    elevation = [point['ele'], point['ele']]
            else:
                # Find this point in DEM and return his elevation
                elevation = DEM.dataProvider().identify(
                    geompt, QgsRaster.IdentifyFormatValue).results()

            #print (elevation[1],point['ele'])
            # Get Value of original point (y - Latitude, x - Longitude)
            self.coor_x = geompt.x()
            self.coor_y = geompt.y()
            if len(elevation) > 0:
                # Set value of elevation like coordinate Z
                self.coor_z = elevation[1]
            else:
                self.info('Point ' + str(self.coor_y) + " / " +
                          str(self.coor_x) + " Not Found / No encontrado")
                self.coor_z = 0

            # Calculate lenght of track
            if not point_origin == 0:
                self.distance = d.measureLine(point_origin, geompt)
                self.coor_m += (self.distance / 1000)  # Distance in km
                point_origin = geompt
            else:
                self.coor_m = 0
                self.distance = 0
                point_origin = geompt

            # Maxium Hight for profile
            if self.ymax < self.coor_z:
                self.ymax = self.coor_z
            # Acumulate points (distance / Elevation) for make profile
            self.all_coord_m.append(self.coor_m)
            self.all_coord_z.append(self.coor_z)

            # Put a time in points
            if self.file_name[-3:] == 'kml':
                self.track_day = self.track_day.addSecs(1)
            else:
                if point['time'] == None:
                    # If track hase no time add 1 second to previous time
                    self.track_day = self.track_day.addSecs(1)
                else:
                    # Get point time from track
                    self.track_day = point['time']

            # Add point in the new kml file
            self.add_points_kml()

            # Add point in the new GPX file
            self.add_points_gpx()

        # Close and write finish of kml file
        self.finish_kml()

        # Close and write finish of gpx file
        self.finish_gpx()

    def start_creation_kml(self):
        # Write head lines of kml file
        self.Output_KML_File = self.file_name[:-4] + '_3D.kml'
        self.file_kml = open(self.Output_KML_File, 'w')
        color_dic = {
            'Rojo': 'ff0000ff',
            'Verde': 'ff00ff00',
            'Azul': 'ffff0000',
            'Morado': 'ff800080',
            'Amarillo': 'ff00ffff',
            'Rosado': 'ffff00ff',
            'Naranja': 'ff0080ff',
            'Marrón': 'ff336699'
        }
        color = [
            'ff0000ff', 'ff00ff00', 'ffff0000', 'ff800080', 'ff00ffff',
            'ffff00ff', 'ff0080ff', 'ff336699'
        ]
        self.file_kml.write("<?xml version='1.0' encoding='UTF-8'?>\n")
        self.file_kml.write(
            "<kml xmlns='http://www.opengis.net/kml/2.2' xmlns:gx='http://www.google.com/kml/ext/2.2' xmlns:kml='http://www.opengis.net/kml/2.2' xmlns:atom='http://www.w3.org/2005/Atom'>\n"
        )
        self.file_kml.write("<Document>\n")
        self.file_kml.write("   <name>" + self.Output_KML_File + "</name>\n")
        self.file_kml.write("   <Placemark>\n")
        self.file_kml.write("       <name>" +
                            os.path.basename(self.Output_KML_File) +
                            "</name>\n")
        self.file_kml.write("       <description>" +
                            os.path.basename(self.Output_KML_File) +
                            "</description>\n")
        self.file_kml.write("	<Style>\n")
        self.file_kml.write("		<LineStyle>\n")
        self.file_kml.write("			<color>" + color[0] + "</color>\n")
        self.file_kml.write("			<width>4</width>\n")
        self.file_kml.write("		</LineStyle>\n")
        self.file_kml.write("	</Style>\n")
        self.file_kml.write("       <LineString>\n")
        self.file_kml.write("           <coordinates>")

    def add_points_kml(self):
        self.file_kml.write(
            str(self.coor_x) + "," + str(self.coor_y) + "," +
            str(self.coor_z) + " ")

    def finish_kml(self):
        # Write foot lines, write and close kml file
        self.file_kml.write("           </coordinates>\n")
        self.file_kml.write("       </LineString>\n")
        self.file_kml.write("   </Placemark>\n")
        self.file_kml.write("</Document>\n")
        self.file_kml.write("</kml>\n")
        self.file_kml.close()
        self.info(self.Output_KML_File)

    def start_creation_gpx(self):
        # Write head lines of gpx file
        self.Output_GPX_File = self.file_name[:-4] + '_3D.gpx'
        self.file_gpx = open(self.Output_GPX_File, 'w')

        self.file_gpx.write('''<?xml version="1.0"?>\n''')
        self.file_gpx.write(
            '''<gpx version="1.1" creator="GDAL 3.0.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.topografix.com/GPX/1/1" xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">\n'''
        )
        self.file_gpx.write("  <trk>\n")
        self.file_gpx.write("    <name>" +
                            os.path.basename(self.Output_GPX_File) +
                            "</name>\n")
        self.file_gpx.write("    <trkseg>\n")

    def add_points_gpx(self):
        # Add points in the GPX file
        self.file_gpx.write('      <trkpt lat="' + str(self.coor_y) +
                            '" lon="' + str(self.coor_x) + '">\n')
        self.file_gpx.write("        <ele>" + str(self.coor_z) + "</ele>\n")
        self.file_gpx.write("      <time>" +
                            self.track_day.toString('yyyy-MM-ddTHH:mm:ssZ') +
                            "</time>\n")
        self.file_gpx.write("      </trkpt>\n")

    def finish_gpx(self):
        # Write foot lines, write and close kml file
        self.file_gpx.write("    </trkseg>\n")
        self.file_gpx.write("  </trk>\n")
        self.file_gpx.write("</gpx>\n")
        self.file_gpx.close()
        self.info(self.Output_GPX_File)

    def profile(self):
        import matplotlib.pyplot as plt

        # Create Profile
        plt.xlim(right=self.coor_m)  #xmax is your value
        plt.xlim(left=0)  #xmin is your value
        plt.ylim(top=self.ymax * 1.2)  #ymax is your value
        plt.ylim(bottom=0)  #ymin is your value
        plt.plot(self.all_coord_m, self.all_coord_z)
        plt.fill_between(self.all_coord_m,
                         self.all_coord_z,
                         facecolor='red',
                         color='#539ecd')
        #pylab.fill_between(x, y, color='#539ecd')
        file_profile = self.file_name[:-3] + "jpg"
        plt.savefig(file_profile)
        plt.clf()
        pixmap = QPixmap(file_profile)
        self.profile_jpg.setPixmap(pixmap)
        self.profile_jpg.setScaledContents(True)
        self.info(file_profile)

    def info(self, message):
        # Show Information message in the screen and print in console
        print(message)
        self.message_box.append(message)

    def initGui(self):
        # Create Graphical User Interface
        icon = QIcon()
        icon.addPixmap(QPixmap(os.path.dirname(__file__) + "/icon.png"),
                       QIcon.Normal, QIcon.Off)
        self.setWindowIcon(icon)
        self.setWindowModality(Qt.WindowModal)
        self.setWindowFlags(Qt.Window
                            | Qt.WindowSystemMenuHint
                            | Qt.WindowMinimizeButtonHint
                            | Qt.WindowMaximizeButtonHint
                            | Qt.WindowCloseButtonHint)

        self.resize(520, 520)

        self.label = QLabel(self)
        self.label.setGeometry(QRect(10, 20, 500, 20))
        font = QFont()
        font.setPointSize(14)
        font.setUnderline(True)
        self.label.setFont(font)
        self.label.setAlignment(Qt.AlignCenter)
        self.label_2 = QLabel(self)
        self.label_2.setGeometry(QRect(10, 70, 500, 16))
        self.label_3 = QLabel(self)
        self.label_3.setGeometry(QRect(10, 90, 500, 16))
        self.label_4 = QLabel(self)
        self.label_4.setGeometry(QRect(10, 110, 500, 16))
        self.pushButton = QPushButton(self)
        self.pushButton.setGeometry(QRect(50, 150, 121, 24))
        self.comboBox = QComboBox(self)
        self.comboBox.setGeometry(QRect(240, 150, 121, 24))
        self.comboBox.addItem("Paso Malla 25m")
        self.comboBox.addItem("Paso Malla 200m")
        self.comboBox.addItem("Paso Malla 500m")
        self.comboBox.addItem("Paso Malla 1.000m")
        self.bt_view_map = QPushButton(self)
        self.bt_view_map.setGeometry(QRect(370, 150, 121, 24))
        self.profile_jpg = QLabel(self)
        self.profile_jpg.setGeometry(QRect(20, 200, 480, 180))

        self.message_box = QTextEdit(self)
        self.message_box.setGeometry(QRect(10, 400, 500, 111))
        self.label.setText("KML / GPX TO 3D")
        self.label_2.setText(
            "Convert a GPX file without elevation, in a GPX and KML with elevation. It's only for Spain."
        )
        self.label_3.setText(
            "Convierte un GPX sin elevación, en un GPX y KML con elevación.")
        self.label_4.setText(
            "Es solo para España ya que utiliza el servicio WCS del Instituto Geografico Nacional"
        )
        self.pushButton.setText("File / Fichero")
        self.bt_view_map.setText("Map / Mapa")

        self.pushButton.clicked.connect(self.select_file)
        self.bt_view_map.clicked.connect(
            lambda: see_map(self.Output_KML_File).exec_())
    def postFeatureRequestTaskRun(self):
        try:
            self.iface.messageBar().popWidget()
        except RuntimeError:
            pass

        self.iface.messageBar().pushMessage('Lähdeaineiston kohteet haettu',
                                            Qgis.Info,
                                            duration=5)

        # self.yleiskaavaDatabase.reconnectToDB()

        self.shownSourceLayer = self.yleiskaavaSourceDataAPIs.createMemoryLayer(
            self.originalSourceLayer, self.originalSourceLayerInfo,
            self.featureRequestTask.features)

        if self.shownSourceLayer is not None and self.shownSourceLayer.featureCount(
        ) > 0:
            self.showSourceLayer()

        featureCount = 0
        featureInfos = []

        selectedTargetLayerFeatureRequest = QgsFeatureRequest(
        ).setNoAttributes().setLimit(1)
        if self.shownSourceLayer.fields().indexFromName(
                self.originalSourceLayerInfo["nimi"]
        ) != -1 and self.shownSourceLayer.fields().indexFromName(
                self.originalSourceLayerInfo["linkki_data"]) != -1:
            for index, feature in enumerate(
                    self.shownSourceLayer.getFeatures()):
                if feature.isValid():
                    featureCount += 1  # layer.featureCount() ei luotettava
                    featureInfos.append({
                        "feature":
                        feature,
                        "distance":
                        self.getDistance(
                            self.shownSourceLayer, feature,
                            self.selectedTargetLayer,
                            list(
                                self.selectedTargetLayer.getSelectedFeatures(
                                    selectedTargetLayerFeatureRequest))[0]),
                        "nimi":
                        feature[self.originalSourceLayerInfo["nimi"]],
                        "linkki_data":
                        feature[self.originalSourceLayerInfo["linkki_data"]]
                    })
        self.dialogAddSourceDataLinks.tableWidgetSourceTargetMatches.setRowCount(
            featureCount)
        # QgsMessageLog.logMessage('updateTableWidgetSourceTargetMatches - featureCount: ' + str(featureCount), 'Yleiskaava-työkalu', Qgis.Info)

        if featureCount == 0:
            self.iface.messageBar().pushMessage(
                'Lähdeaineistokarttatasolta ei löytynyt valituista kohteista määritetyn rajaussuorakulmion sisältä kohteita',
                Qgis.Info,
                duration=10)

        for index, featureInfo in enumerate(
                sorted(featureInfos, key=itemgetter("distance"))):
            # lähdeaineiston mukaan nimi/tunniste UI:hin
            # QgsMessageLog.logMessage('updateTableWidgetSourceTargetMatches, nimi: ' + str(featureInfo["nimi"]) + ', linkki_data: ' + str(featureInfo["linkki_data"]), 'Yleiskaava-työkalu', Qgis.Info)

            userFriendlyFieldNameLabel = QLabel(str(featureInfo["nimi"]))

            infoLinkButton = QPushButton()
            infoLinkButton.setText("Näytä lähdetietosivu")
            infoLinkButton.clicked.connect(
                partial(self.showInfoPage, str(featureInfo["linkki_data"])))

            sourceMapButton = QPushButton()
            sourceMapButton.setText("Näytä")
            sourceMapButton.clicked.connect(
                partial(self.showSourceFeature, self.shownSourceLayer,
                        featureInfo["feature"].id()))

            distanceLabel = QLabel()
            distanceLabel.setAlignment(Qt.AlignCenter)
            distanceLabel.setText(str(featureInfo["distance"]))

            linkedFeatureWidget = None
            # yhdistä tietokannan data
            linkedFeatureID, linkedSourceDataFeature = self.yleiskaavaSourceDataAPIs.getLinkedDatabaseFeatureIDAndSourceDataFeature(
                self.selectedTargetLayer, featureInfo)
            if linkedFeatureID != None:
                linkedFeatureWidget = QPushButton()
                linkedFeatureWidget.setText("Näytä yhdistetty kohde")
                linkedFeatureWidget.clicked.connect(
                    partial(self.showLinkedFeature, self.selectedTargetLayer,
                            linkedFeatureID))
            else:
                linkedFeatureWidget = QLabel()
                linkedFeatureWidget.setAlignment(Qt.AlignCenter)
                linkedFeatureWidget.setText("-")

            linkToFeatureButton = QPushButton()
            linkToFeatureButton.setText("Yhdistä")
            linkToFeatureButton.clicked.connect(
                partial(
                    self.addLinkBetweenSourceFeatureAndSelectedTargetFeature,
                    index, featureInfo))

            self.dialogAddSourceDataLinks.tableWidgetSourceTargetMatches.setCellWidget(
                index, AddSourceDataLinks.FIELD_USER_FRIENDLY_NAME_INDEX,
                userFriendlyFieldNameLabel)
            self.dialogAddSourceDataLinks.tableWidgetSourceTargetMatches.setCellWidget(
                index, AddSourceDataLinks.INFO_LINK_INDEX, infoLinkButton)
            self.dialogAddSourceDataLinks.tableWidgetSourceTargetMatches.setCellWidget(
                index, AddSourceDataLinks.SOURCE_FEATURE_INDEX,
                sourceMapButton)
            self.dialogAddSourceDataLinks.tableWidgetSourceTargetMatches.setCellWidget(
                index, AddSourceDataLinks.DISTANCE_INFO_INDEX, distanceLabel)
            self.dialogAddSourceDataLinks.tableWidgetSourceTargetMatches.setCellWidget(
                index, AddSourceDataLinks.LINKED_FEATURE_INDEX,
                linkedFeatureWidget)
            self.dialogAddSourceDataLinks.tableWidgetSourceTargetMatches.setCellWidget(
                index, AddSourceDataLinks.LINK_TO_FEATURE_INDEX,
                linkToFeatureButton)

        self.dialogAddSourceDataLinks.tableWidgetSourceTargetMatches.resizeColumnsToContents(
        )
class HistoryDiffViewerWidget(QWidget):

    def __init__(self, dialog, server, user, repo, graph, layer=None, initialSimplify=False):
        self.graph = graph
        self.dialog = dialog
        self.server = server
        self.user = user
        self.repo = repo 
        self.layer = layer
        self.afterLayer = None
        self.beforeLayer = None
        self.extraLayers = [] # layers for the "Map" tab
        QWidget.__init__(self, iface.mainWindow())
        self.setWindowFlags(Qt.Window)
        self.simplifyLog = initialSimplify
        self.initGui()
        self.tabWidget.setVisible(False)
        self.setLabelText("Select a commit to show its content")
        self.label.setVisible(False)
        if self.graph.commits:
            self.history.setCurrentItem(self.history.topLevelItem(0))
            self.itemChanged(self.history.topLevelItem(0), None)
        self.history.currentItemChanged.connect(self.itemChanged)

    def setShowPopup(self, show):
        self.history.showPopup = show 

    def initGui(self):
        layout = QVBoxLayout()
        splitter = QSplitter()
        splitter.setOrientation(Qt.Vertical)

        self.history = HistoryTree(self.dialog)
        self.history.updateContent(self.server, self.user, self.repo, self.graph, self.layer)
        self.historyWithFilter = HistoryTreeWrapper(self.history)
        if self.simplifyLog:
            self.historyWithFilter.simplify(True)
        splitter.addWidget(self.historyWithFilter)
        self.tabWidget = QTabWidget()
        self.tabCanvas = QWidget()
        tabLayout = QVBoxLayout()
        tabLayout.setMargin(0)        
        self.canvas = QgsMapCanvas(self.tabCanvas)
        self.canvas.setCanvasColor(Qt.white)
        self.panTool = QgsMapToolPan(self.canvas)
        self.canvas.setMapTool(self.panTool)
        tabLayout.addWidget(self.canvas)
        self.labelNoChanges = QLabel("This commit doesn't change any geometry")
        self.labelNoChanges.setAlignment(Qt.AlignCenter)
        self.labelNoChanges.setVisible(False)
        tabLayout.addWidget(self.labelNoChanges)
        self.tabCanvas.setLayout(tabLayout)
        self.summaryTextBrowser = QTextBrowser()
        self.summaryTextBrowser.setOpenLinks(False)
        self.summaryTextBrowser.anchorClicked.connect(self.summaryTextBrowserAnchorClicked)
        self.tabWidget.addTab(self.summaryTextBrowser, "Commit Summary")
        self.tabWidget.addTab(self.tabCanvas, "Map")
        tabLayout = QVBoxLayout()
        tabLayout.setMargin(0)
        self.tabDiffViewer = QWidget()
        self.diffViewer = DiffViewerWidget({})
        tabLayout.addWidget(self.diffViewer)
        self.tabDiffViewer.setLayout(tabLayout)
        self.tabWidget.addTab(self.tabDiffViewer, "Attributes")
        splitter.addWidget(self.tabWidget)
        self.label = QTextBrowser()
        self.label.setVisible(False)
        splitter.addWidget(self.label)
        self.tabWidget.setCurrentWidget(self.tabDiffViewer)

        layout.addWidget(splitter)
        self.setLayout(layout)

        exportDiffButton = QPushButton("Export this commit's DIFF for all layers")
        exportDiffButton.clicked.connect(self.exportDiffAllLayers)

        layout.addWidget(exportDiffButton)
        self.label.setMinimumHeight(self.tabWidget.height())        
        self.setWindowTitle("Repository history")

    def summaryTextBrowserAnchorClicked(self,url):
        url = url.url() #convert to string
        item = self.history.currentItem()
        if item is None:
            return
        commitid = item.commit.commitid

        cmd,layerName = url.split(".",1)
        if cmd == "addLive":
            execute(lambda: self.history.exportVersion(layerName,commitid,True))
        elif cmd == "addGeoPKG":
            self.history.exportVersion(layerName,commitid,False)
        elif cmd == "exportDiff":
            execute(lambda: self.history.exportDiff(item, None,layer=layerName))

    def exportDiffAllLayers(self):
        item = self.history.currentItem()
        if item is not None:
            self.history.exportDiff(item, None)

    def setLabelText(self,text):
        self.label.setHtml("<br><br><br><center><b>{}</b></center>".format(text))

    def setContent(self, server, user, repo, graph, layer = None):
        self.server = server
        self.user = user
        self.repo = repo
        self.layer = layer
        self.graph = graph
        self.historyWithFilter.updateContent(server, user, repo, graph, layer)
        if self.history.graph.commits:
            self.history.setCurrentItem(self.history.topLevelItem(0))

    def itemChanged(self, current, previous, THRESHOLD = 1500):
        item = self.history.currentItem()
        if item is not None:
            commit = self.graph.getById(item.ref)
            if commit is None:
                self.tabWidget.setVisible(False)
                self.setLabelText("Select a commit to show its content")
                self.label.setVisible(True)
                return

            commit2 = commit.commitid + "~1"

            if not item.commit.hasParents():
                commit2 = "0000000000000000"

            total,details = self.server.diffSummary(self.user, self.repo,  commit2,commit.commitid)
            tooLargeDiff = total > THRESHOLD
            if tooLargeDiff:
                 html = "<br><br><center><b><font size=+3>Commit <font size=-0.1><tt>{}</tt></font> DIFF is too large to be shown</b></font><br>".format(commit.commitid[:8])
            else:
                html = "<br><br><center><b><font size=+3>Commit <font size=-0.1><tt>{}</tt></font> Summary</b></font><br>".format(commit.commitid[:8])
            html += "<table>"
            html += "<tr><Td style='padding:5px'><b>Layer&nbsp;Name</b></td><td style='padding:5px'><b>Additions</b></td><td style='padding:5px'><b>Deletions</b></td><td style='padding:5px'><b>Modifications</b></td><td></td><td></td><td></td></tr>"
            for detail in details.values():
                html += "<tr><td style='padding:5px'>{}</td><td style='padding:5px'><center>{:,}</center></td><td style='padding:5px'><center>{:,}</center></td><td style='padding:5px'><center>{:,}</center></td><td style='padding:5px'>{}</td><td style='padding:5px'>{}</td><td style='padding:5px'>{}</td></tr>".format(
                    detail["path"],
                    int(detail["featuresAdded"]), int(detail["featuresRemoved"]),int(detail["featuresChanged"]),
                    "<a href='addLive.{}'>Add Live</a>".format(detail["path"]),
                    "<a href='addGeoPKG.{}'>Add GeoPKG</a>".format(detail["path"]),
                    "<a href='exportDiff.{}'>Export Diff</a>".format(detail["path"])
                )
            html += "<tr></tr>"
            html += "<tr><td colspan=4>There is a total of {:,} features changed</td></tr>".format(total)
            html += "</table>"
            # html += "<br><br>There is a total of {:,} features changed".format(total)
            self.summaryTextBrowser.setHtml(html)
            self.label.setVisible(False)
            self.tabWidget.setVisible(True)
            self.tabWidget.setTabEnabled(1,not tooLargeDiff)
            self.tabWidget.setTabEnabled(2,not tooLargeDiff)
            if not tooLargeDiff:
                self.setDiffContent(commit, commit2)
        else:
            self.tabWidget.setVisible(False)
            self.setLabelText("Select a commit to show its content")
            self.label.setVisible(True)

    def setDiffContent(self, commit, commit2):
        if self.layer is None:
            layers = set(self.server.layers(self.user, self.repo, commit.commitid))
            layers2 = set(self.server.layers(self.user, self.repo, commit2))
            layers = layers.union(layers2)
        else:
            layers = [self.layer]

        diffs = {layer: execute(lambda: self.server.diff(self.user, self.repo, layer, commit.commitid, commit2)) for layer in layers}
        diffs = {key:value for (key,value) in diffs.items() if len(value) !=0}
        layers = [l for l in diffs.keys()]
        self.diffViewer.setChanges(diffs)

        self.canvas.setLayers([])
        self.removeMapLayers()
        extent = QgsRectangle()
        for layer in layers:
            if not diffs[layer]:
                continue
            beforeLayer, afterLayer = execute(lambda: self._getLayers(diffs[layer]))
            if afterLayer is not None:
                resourcesPath =  os.path.join(os.path.dirname(__file__), os.pardir, "resources")
                oldStylePath = os.path.join(resourcesPath, "{}_before.qml".format(
                                            QgsWkbTypes.geometryDisplayString(beforeLayer.geometryType())))
                newStylePath = os.path.join(resourcesPath, "{}_after.qml".format(
                                            QgsWkbTypes.geometryDisplayString(afterLayer.geometryType())))

                beforeLayer.loadNamedStyle(oldStylePath)
                afterLayer.loadNamedStyle(newStylePath)

                QgsProject.instance().addMapLayer(beforeLayer, False)
                QgsProject.instance().addMapLayer(afterLayer, False)

                extent.combineExtentWith(beforeLayer.extent())
                extent.combineExtentWith(afterLayer.extent())
                self.extraLayers.append(beforeLayer)
                self.extraLayers.append(afterLayer)
        # make extent a bit bit (10%) bigger
        # this gives some margin around the dataset (not cut-off at edges)
        if not extent.isEmpty():
            widthDelta = extent.width() * 0.05
            heightDelta = extent.height() * 0.05
            extent = QgsRectangle(extent.xMinimum() - widthDelta,
                                  extent.yMinimum() - heightDelta,
                                  extent.xMaximum() + widthDelta,
                                  extent.yMaximum() + heightDelta)

        layers = self.extraLayers
        hasChanges = False
        for layer in layers:
            if layer is not None and layer.featureCount() > 0:
                hasChanges = True
                break
        self.canvas.setLayers(layers)
        self.canvas.setExtent(extent)
        self.canvas.refresh()
                
        self.canvas.setVisible(hasChanges)
        self.labelNoChanges.setVisible(not hasChanges)

    def _getLayers(self, changes):
        ADDED, MODIFIED, REMOVED,  = 0, 1, 2
        def _feature(g, changeType):
            feat = QgsFeature()
            if g is not None:
                feat.setGeometry(g)
            feat.setAttributes([changeType])
            return feat
        if changes:
            f = changes[0]
            new = f["new"]            
            old = f["old"]
            reference = new or old
            geomtype = QgsWkbTypes.displayString(reference.geometry().wkbType())
            oldLayer = loadLayerNoCrsDialog(geomtype + "?crs=epsg:4326&field=geogig.changeType:integer", "old", "memory")
            newLayer = loadLayerNoCrsDialog(geomtype + "?crs=epsg:4326&field=geogig.changeType:integer", "new", "memory")
            oldFeatures = []
            newFeatures = []
            for f in changes:            
                new = f["new"]        
                old = f["old"]                  
                newGeom = new.geometry() if new is not None else None
                oldGeom = old.geometry() if old is not None else None
                if oldGeom is None:
                    feature = _feature(newGeom, ADDED)
                    newFeatures.append(feature)
                elif newGeom is None:
                    feature = _feature(oldGeom, REMOVED)
                    oldFeatures.append(feature)
                elif oldGeom.asWkt() != newGeom.asWkt():
                    feature = _feature(oldGeom, MODIFIED)
                    oldFeatures.append(feature)
                    feature = _feature(newGeom, MODIFIED)
                    newFeatures.append(feature)
                else:
                    feature = _feature(newGeom, MODIFIED)
                    newFeatures.append(feature)
            oldLayer.dataProvider().addFeatures(oldFeatures)
            newLayer.dataProvider().addFeatures(newFeatures)
        else:
            oldLayer = None
            newLayer = None

        return oldLayer, newLayer

    def removeMapLayers(self):
        for layer in self.extraLayers:
            if layer is not None:
                    QgsProject.instance().removeMapLayer(layer.id())
        self.extraLayers = []
Esempio n. 23
0
class MirrorMap(QWidget):
    def __init__(self, parent=None, iface=None):
        QWidget.__init__(self, parent)
        # self.setAttribute(Qt.WA_DeleteOnClose)

        self.iface = iface
        self.layerId2canvasLayer = {}
        self.canvasLayers = []

        self.setupUi()

    def closeEvent(self, event):
        self.scaleFactor.valueChanged.disconnect(self.onExtentsChanged)

        if not self.iface is None:
            self.iface.mapCanvas().extentsChanged.discconnect(
                self.onExtentsChanged)
            self.iface.mapCanvas().mapRenderer(
            ).destinationCrsChanged.disconnect(self.onCrsChanged)
            self.iface.mapCanvas().mapRenderer().mapUnitsChanged.disconnect(
                self.onCrsChanged)
            self.iface.mapCanvas().mapRenderer(
            ).hasCrsTransformEnabled.disconnect(self.onCrsTransformEnabled)
            QgsProject.instance().layerWillBeRemoved.disconnect(self.delLayer)
            self.iface.currentLayerChanged.disconnect(self.refreshLayerButtons)

        self.closed.emit()

        return QWidget.closeEvent(self, event)

    def setupUi(self):
        self.setObjectName("mirrormap")

        gridLayout = QGridLayout(self)
        gridLayout.setContentsMargins(0, 0, gridLayout.verticalSpacing(),
                                      gridLayout.verticalSpacing())

        self.canvas = QgsMapCanvas(self)
        self.canvas.setCanvasColor(QColor(255, 255, 255))
        settings = QSettings()
        gridLayout.addWidget(self.canvas, 0, 0, 1, 5)

        self.addLayerBtn = QToolButton(self)
        # self.addLayerBtn.setToolButtonStyle( Qt.ToolButtonTextBesideIcon )
        # self.addLayerBtn.setText("Add current layer")
        self.addLayerBtn.setIcon(GuiUtils.get_icon("add.png"))

        self.addLayerBtn.clicked.connect(self.tool_add_layer)
        gridLayout.addWidget(self.addLayerBtn, 1, 0, 1, 1)

        self.delLayerBtn = QToolButton(self)
        # self.delLayerBtn.setToolButtonStyle( Qt.ToolButtonTextBesideIcon )
        # self.delLayerBtn.setText("Remove current layer")
        self.delLayerBtn.setIcon(GuiUtils.get_icon("remove.png"))
        self.delLayerBtn.clicked.connect(self.tool_remove_layer)
        gridLayout.addWidget(self.delLayerBtn, 1, 1, 1, 1)

        self.renderCheck = QCheckBox("Render", self)
        self.renderCheck.toggled.connect(self.toggleRender)
        self.renderCheck.setChecked(True)
        gridLayout.addWidget(self.renderCheck, 1, 2, 1, 1)

        self.scaleFactorLabel = QLabel(self)
        self.scaleFactorLabel.setText("Scale factor:")
        self.scaleFactorLabel.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        gridLayout.addWidget(self.scaleFactorLabel, 1, 3, 1, 1)
        self.scaleFactor = QDoubleSpinBox(self)
        self.scaleFactor.setMinimum(0.0)
        self.scaleFactor.setMaximum(1000.0)
        self.scaleFactor.setDecimals(3)
        self.scaleFactor.setValue(1)
        self.scaleFactor.setObjectName("scaleFactor")
        self.scaleFactor.setSingleStep(.05)
        gridLayout.addWidget(self.scaleFactor, 1, 4, 1, 1)
        self.scaleFactor.valueChanged.connect(self.onExtentsChanged)

        # Add a default pan tool
        self.toolPan = QgsMapToolPan(self.canvas)
        self.canvas.setMapTool(self.toolPan)

        self.scaleFactor.valueChanged.connect(self.onExtentsChanged)
        self.set_iface(self.iface)

    def toggleRender(self, enabled):
        self.canvas.setRenderFlag(enabled)

    def extent(self):
        """
        :return: Current extents of the map canvas view.
        """
        return self.canvas.extent()

    def canvas_layers(self):
        """
        :return: Layers currently in the canvas.
        :rtype: list
        """
        return self.canvasLayers

    def on_canvas_refreshed(self):
        """
        """
        self.refresh_layers()

    def tool_add_layer(self):
        self.addLayer()

    def tool_remove_layer(self):
        self.delLayer()

    def set_iface(self, iface):
        if iface is None:
            return

        self.iface = iface
        self.iface.mapCanvas().extentsChanged.connect(self.onExtentsChanged)
        # self.iface.mapCanvas().mapCanvasRefreshed.connect(self.on_canvas_refreshed)
        self.iface.mapCanvas().destinationCrsChanged.connect(self.onCrsChanged)
        QgsProject.instance().layerWillBeRemoved.connect(self.delLayer)
        self.iface.currentLayerChanged.connect(self.refreshLayerButtons)

        self.refreshLayerButtons()

        self.onExtentsChanged()
        self.onCrsChanged()

    def refresh_layers(self):
        """
        Checks if the layers in the canvas list have already been added.
        If not, then add to the property viewer canvas.
        """
        for ly in self.iface.mapCanvas().layers():
            layer_id = self._layerId(ly)
            if layer_id not in self.layerId2canvasLayer:
                self.addLayer(layer_id)
        # QCoreApplication.processEvents(QEventLoop.ExcludeSocketNotifiers|QEventLoop.ExcludeUserInputEvents)

    def onExtentsChanged(self):
        prevFlag = self.canvas.renderFlag()
        self.canvas.setRenderFlag(False)

        self.canvas.setExtent(self.iface.mapCanvas().extent())
        self.canvas.zoomByFactor(self.scaleFactor.value())
        # self.canvas.refresh()

        self.canvas.setRenderFlag(prevFlag)

    def onCrsChanged(self):
        self.canvas.setDestinationCrs(
            self.iface.mapCanvas().mapSettings().destinationCrs())

    def refreshLayerButtons(self):
        layer = self.iface.activeLayer()

        isLayerSelected = layer != None
        hasLayer = False
        for l in self.canvas.layers():
            if l == layer:
                hasLayer = True
                break

        self.addLayerBtn.setEnabled(isLayerSelected and not hasLayer)
        self.delLayerBtn.setEnabled(isLayerSelected and hasLayer)

    def getLayerSet(self):
        return [self._layerId(x.layer()) for x in self.canvasLayers]

    def setLayerSet(self, layerIds=None):
        prevFlag = self.canvas.renderFlag()
        self.canvas.setRenderFlag(False)

        if layerIds == None:
            self.layerId2canvasLayer = {}
            self.canvasLayers = []
            self.canvas.setLayers([])

        else:
            for lid in layerIds:
                self.addLayer(lid)

        self.refreshLayerButtons()
        self.onExtentsChanged()
        self.canvas.setRenderFlag(prevFlag)

    def addLayer(self, layerId=None):
        if layerId == None:
            layer = self.iface.activeLayer()
        else:
            layer = QgsProject.instance().mapLayer(layerId)

        if layer == None:
            return

        prevFlag = self.canvas.renderFlag()
        self.canvas.setRenderFlag(False)

        # add the layer to the map canvas layer set
        self.canvasLayers = []
        id2cl_dict = {}
        for l in self.iface.mapCanvas().layers():
            lid = self._layerId(l)
            if lid in self.layerId2canvasLayer:  # previously added
                cl = self.layerId2canvasLayer[lid]
            elif l == layer:  # Selected layer
                cl = layer
            else:
                continue

            id2cl_dict[lid] = cl
            self.canvasLayers.append(cl)

        self.layerId2canvasLayer = id2cl_dict
        self.canvas.setLayers(self.canvasLayers)

        self.refreshLayerButtons()
        self.onExtentsChanged()
        self.canvas.setRenderFlag(prevFlag)

    def delLayer(self, layerId=None):
        if layerId == None:
            layer = self.iface.activeLayer()
            if layer == None:
                return
            layerId = self._layerId(layer)

        # remove the layer from the map canvas layer set
        if layerId not in self.layerId2canvasLayer:
            return

        prevFlag = self.canvas.renderFlag()
        self.canvas.setRenderFlag(False)

        cl = self.layerId2canvasLayer[layerId]
        del self.layerId2canvasLayer[layerId]
        self.canvasLayers.remove(cl)
        self.canvas.setLayers(self.canvasLayers)

        self.refreshLayerButtons()
        self.onExtentsChanged()
        self.canvas.setRenderFlag(prevFlag)

    def _layerId(self, layer):
        if hasattr(layer, 'id'):
            return layer.id()

        return layer.getLayerID()
Esempio n. 24
0
class TrackingDisplay(QToolBar):
    '''
        Display the position of a mobile and add action for centering
        the map on the vehicle and erasing the track
    '''

    def __init__(self, mobile, parent=None):
        super(TrackingDisplay, self).__init__(parent)
        self.setMovable(True)
        self.setFloatable(True)
        self.mobile = mobile
        self.timedOut = True
        self.lastFix = 0.0
        s = QSettings()
        self.defFormat = s.value('PosiView/Misc/DefaultFormat', defaultValue=0, type=int)
        self.format = self.defFormat & 3
        self.withSuff = QgsCoordinateFormatter.FlagDegreesUseStringSuffix if bool(self.defFormat & 4) else QgsCoordinateFormatter.FormatFlag(0)
        self.createActions()
        self.mobile.newPosition.connect(self.onNewPosition)
        self.mobile.timeout.connect(self.onTimeout)

    def createActions(self):
        self.nameLabel = QLabel(self.mobile.name)
        self.nameLabel.setMinimumSize(80, 23)
        self.nameLabelAction = QWidgetAction(self)
        self.nameLabelAction.setDefaultWidget(self.nameLabel)
        self.addAction(self.nameLabelAction)

        self.enableAction = QAction("Enable Display", self)
        self.enableAction.setCheckable(True)
        self.enableAction.setChecked(True)
        icon = QIcon(':/plugins/PosiView/ledgrey.png')
        icon.addFile(':/plugins/PosiView/ledgreen.png', QSize(), QIcon.Normal, QIcon.On)
        self.enableAction.setIcon(icon)
        self.addAction(self.enableAction)
        self.enableAction.triggered.connect(self.onEnableClicked)
        self.enableAction.triggered.connect(self.mobile.setEnabled)

        self.addSeparator()
        self.posLabel = QLabel("--:--:-- 0.000000 0.000000")
        self.posLabel.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)
        widths = (180, 196, 204, 180, 184, 200, 208, 184)
        self.posLabel.setMinimumSize(widths[self.format], 23)
        self.posLabel.setStyleSheet('background: red; font-size: 8pt; color: white;')
        self.posLabelAction = QWidgetAction(self)
        self.posLabelAction.setDefaultWidget(self.posLabel)
        self.addAction(self.posLabelAction)
        self.centerAction = QAction(QIcon(':/plugins/PosiView/center.png'), "Center &Map", self)
        self.addAction(self.centerAction)
        self.deleteTrackAction = QAction(QIcon(':/plugins/PosiView/deletetrack.png'), 'Delete &Track', self)
        self.addAction(self.deleteTrackAction)
        self.deleteTrackAction.triggered.connect(self.mobile.deleteTrack)
        self.centerAction.triggered.connect(self.mobile.centerOnMap)

    @pyqtSlot(float, QgsPointXY, float, float)
    def onNewPosition(self, fix, pos, depth, altitude):
        s = str()
        if fix > 0:
            s = strftime('%H:%M:%S   ', gmtime(fix))
        else:
            s = '--:--:-- '
        if self.format == 0:
            s += "{:f}  {:f}".format(pos.y(), pos.x())
        elif self.format == 1:
            s += ', '.join(QgsCoordinateFormatter.format(pos,
                                                         QgsCoordinateFormatter.FormatDegreesMinutes,
                                                         4,
                                                         self.withSuff
                                                         ).rsplit(',')[::-1])
        else:
            s += ', '.join(QgsCoordinateFormatter.format(pos,
                                                         QgsCoordinateFormatter.FormatDegreesMinutesSeconds,
                                                         2,
                                                         self.withSuff
                                                         ).rsplit(',')[::-1])
        if depth > -9999:
            s += "\nd = {:.1f}".format(depth)
        if altitude > -9999:
            if depth > -9999:
                s += "   alt = {:.1f}".format(altitude)
            else:
                s += "\nalt = {:.1f}".format(altitude)
        self.posLabel.setText(s)
        if self.timedOut:
            if fix > self.lastFix:
                self.posLabel.setStyleSheet('background: lime; font-size: 8pt; color: black;')
                self.timedOut = False
        self.lastFix = fix

    @pyqtSlot()
    def onTimeout(self):
        if not self.timedOut:
            self.timedOut = True
            self.posLabel.setStyleSheet('background: red; font-size: 8pt; color: white;')

    @pyqtSlot(bool)
    def onEnableClicked(self, enable):
        self.timedOut = True
        if enable:
            self.posLabel.setStyleSheet('background: red; font-size: 8pt; color: white;')
        else:
            self.posLabel.setStyleSheet('background: white; font-size: 8pt; color: black;')

    def releaseMobile(self):
        self.mobile = None
Esempio n. 25
0
    def show_results(self, api_results, pg_connections=dict()):
        """Display the results in a table."""
        logger.info("Results manager called. Displaying the results")
        tbl_result = self.tbl_result
        # Get the name (and other informations) of all databases whose
        # connection is set up in QGIS
        if pg_connections == {}:
            pg_connections = self.pg_connections
        else:
            pass
        # Set table rows
        if api_results.get("total") >= 10:
            tbl_result.setRowCount(10)
        else:
            tbl_result.setRowCount(api_results.get("total"))

        # dimensions (see https://github.com/isogeo/isogeo-plugin-qgis/issues/276)
        hheader = tbl_result.horizontalHeader()
        # make the entire width of the table is occupied
        hheader.setSectionResizeMode(1)
        # make date and icone columns width adapted to their content
        # so title and adding columns occupy the rest of the available width
        hheader.setSectionResizeMode(1, 3)
        hheader.setSectionResizeMode(2, 3)

        vheader = tbl_result.verticalHeader()

        # Looping inside the table lines. For each of them, showing the title,
        # abstract, geometry type, and a button that allow to add the data
        # to the canvas.
        count = 0
        for i in api_results.get("results"):
            md = Metadata.clean_attributes(i)
            # get metadata's keywords from tags, they will be displayed in QGIS
            # 'layer properties' if the layer is added to the canvas
            md.keywords = [
                md.tags.get(kw) for kw in md.tags
                if kw.startswith("keyword:isogeo")
            ]
            # COLUMN 1 - Title and abstract
            # Displaying the metadata title inside a button
            title = md.title_or_name()
            if title:
                btn_md_title = QPushButton(
                    plg_tools.format_button_title(title))
            else:
                btn_md_title = QPushButton(
                    self.tr("Undefined", context=__class__.__name__))
                btn_md_title.setStyleSheet("font: italic")

            # Connecting the button to the full metadata popup
            btn_md_title.pressed.connect(partial(self.md_asked.emit, md._id))
            # Putting the abstract as a tooltip on this button
            if md.abstract:
                btn_md_title.setToolTip(md.abstract[:300])
            else:
                pass
            # Insert it in column 1
            tbl_result.setCellWidget(count, 0, btn_md_title)

            # COLUMN 2 - Data last update
            lbl_date = QLabel(tbl_result)
            lbl_date.setText(plg_tools.handle_date(md._modified))
            lbl_date.setMargin(5)
            lbl_date.setAlignment(Qt.AlignCenter)
            tbl_result.setCellWidget(count, 1, lbl_date)

            # COLUMN 3 - Geometry type
            lbl_geom = QLabel(tbl_result)
            if md.geometry:
                if md.geometry == "TIN":
                    tbl_result.setItem(count, 2, QTableWidgetItem("TIN"))
                elif md.geometry in known_geom_list:
                    for geom_type in self.pix_geom_dict:
                        if md.geometry in geom_type:
                            geom_item = self.pix_geom_dict.get(geom_type)
                            lbl_geom.setPixmap(geom_item.get("pix"))
                            lbl_geom.setToolTip(
                                self.tr(geom_item.get("tooltip"),
                                        context=__class__.__name__))
                        else:
                            continue
                else:
                    tbl_result.setItem(
                        count,
                        2,
                        QTableWidgetItem(
                            self.tr("Unknown geometry",
                                    context=__class__.__name__)),
                    )
            else:
                if "rasterDataset" in md.type:
                    lbl_geom.setPixmap(pix_rastr)
                    lbl_geom.setToolTip(
                        self.tr("Raster", context=__class__.__name__))
                elif "service" in md.type:
                    lbl_geom.setPixmap(pix_serv)
                    lbl_geom.setToolTip(
                        self.tr("Service", context=__class__.__name__))
                else:
                    lbl_geom.setPixmap(pix_nogeo)
                    lbl_geom.setToolTip(
                        self.tr("Unknown geometry",
                                context=__class__.__name__))
            lbl_geom.setAlignment(Qt.AlignCenter)
            tbl_result.setCellWidget(count, 2, lbl_geom)

            # COLUMN 4 - Add options
            add_options_dict = {}

            # Build metadata portal URL if the setting is checked in "Settings" tab
            add_portal_md_url = int(
                qsettings.value("isogeo/settings/add_metadata_url_portal", 0))
            portal_base_url = self.form_mng.input_portal_url.text()
            portal_md_url = ""
            if add_portal_md_url and portal_base_url != "":
                portal_md_url = portal_base_url + md._id
            else:
                pass

            # Files and PostGIS direct access
            if md.format:
                # If the data is a vector and the path is available, store
                # useful information in the dict
                if md.format in li_formats_vect and md.path:
                    add_path = self._filepath_builder(md.path)
                    if add_path:
                        params = [
                            "vector",
                            add_path,
                            md.title,
                            md.abstract,
                            md.keywords,
                            portal_md_url,
                        ]
                        add_options_dict[self.tr(
                            "Data file", context=__class__.__name__)] = params
                    else:
                        pass
                # Same if the data is a raster
                elif md.format in li_formats_rastr and md.path:
                    add_path = self._filepath_builder(md.path)
                    if add_path:
                        params = [
                            "raster",
                            add_path,
                            md.title,
                            md.abstract,
                            md.keywords,
                            portal_md_url,
                        ]
                        add_options_dict[self.tr(
                            "Data file", context=__class__.__name__)] = params
                    else:
                        pass
                # If the data is a postGIS table and the connexion has
                # been saved in QGIS.
                elif md.format == "postgis":
                    if md.path:
                        base_name = md.path
                    else:
                        base_name = "No path"
                    if base_name in pg_connections.keys():
                        params = {}
                        params["base_name"] = base_name
                        schema_table = md.name
                        if schema_table is not None and "." in schema_table:
                            params["schema"] = schema_table.split(".")[0]
                            params["table"] = schema_table.split(".")[1]
                            params["abstract"] = md.abstract
                            params["title"] = md.title
                            params["keywords"] = md.keywords
                            params["md_portal_url"] = portal_md_url
                            add_options_dict[self.tr(
                                "PostGIS table",
                                context=__class__.__name__)] = params
                        else:
                            pass
                    else:
                        pass
                else:
                    logger.debug(
                        "Metadata {} has a format ({}) but it's not handled hear or path is"
                        "missing".format(md._id, md.format))
                    pass
            # Associated service layers
            if md.type == "vectorDataset" or md.type == "rasterDataset":
                for layer in md.serviceLayers:
                    service = layer.get("service")
                    if service is not None:
                        srv_details = {
                            "path": service.get("path", "NR"),
                            "formatVersion": service.get("formatVersion"),
                        }
                        # WMTS
                        if service.get("format") == "wmts":
                            params = self.layer_adder.build_wmts_url(
                                layer, srv_details, rsc_type="ds_dyn_lyr_srv")
                        # EFS, EMS, WMS or WFS
                        elif service.get("format") in list(
                                self.service_dict.keys()):
                            url_builder = self.service_dict.get(
                                service.get("format")).get("url_builder")
                            params = url_builder(
                                layer,
                                srv_details,
                                rsc_type="ds_dyn_lyr_srv",
                                mode="quicky",
                            )
                        else:
                            params = [0]
                            logger.debug(
                                "Service with no format detected for '{}' metadata : {}"
                                .format(md._id, service))
                            pass

                        if params[0] != 0:
                            basic_md = [
                                md.title,
                                md.abstract,
                                md.keywords,
                                portal_md_url,
                            ]
                            params.append(basic_md)
                            add_options_dict["{} : {}".format(
                                params[0], params[1])] = params
                        else:
                            pass
            # New association mode. For services metadata sheet, the layers
            # are stored in the purposely named include: "layers".
            elif md.type == "service":
                if md.layers is not None:
                    srv_details = {
                        "path": md.path,
                        "formatVersion": md.formatVersion,
                    }
                    # WMTS
                    if md.format == "wmts":
                        for layer in md.layers:
                            name_url = self.layer_adder.build_wmts_url(
                                layer, srv_details, rsc_type="service")
                            if name_url[0] != 0:
                                btn_label = "WMTS : {}".format(name_url[1])
                                add_options_dict[btn_label] = name_url
                            else:
                                continue
                    # EFS, EMS, WMS or WFS
                    elif md.format in list(self.service_dict.keys()):
                        url_builder = self.service_dict.get(
                            md.format).get("url_builder")
                        for layer in md.layers:
                            name_url = url_builder(layer,
                                                   srv_details,
                                                   rsc_type="service",
                                                   mode="quicky")
                            if name_url[0] != 0:
                                add_options_dict[name_url[5]] = name_url
                            else:
                                continue
                    else:
                        pass
            else:
                pass

            # Now the plugin has tested every possibility for the layer to be
            # added. The "Add" column has to be filled accordingly.

            # If the data can't be added, just insert "can't" text.
            if add_options_dict == {}:
                text = self.tr("Can't be added", context=__class__.__name__)
                fake_button = QPushButton(text)
                fake_button.setStyleSheet("text-align: left")
                fake_button.setEnabled(False)
                tbl_result.setCellWidget(count, 3, fake_button)
            # If the data can be added
            else:
                data_info = {"limitations": None, "layer": None}
                # retrieves data limitations
                data_info["limitations"] = md.limitations

                # If there is only one way for the data to be added, insert a button.
                if len(add_options_dict) == 1:
                    text = list(add_options_dict.keys())[0]
                    params = add_options_dict.get(text)
                    option_type = text.split(" : ")[0]
                    # services
                    if option_type.lower() in list(self.service_dict.keys()):
                        icon = self.service_dict.get(
                            option_type.lower()).get("ico")
                    # PostGIS table
                    elif option_type.startswith(
                            self.tr("PostGIS table",
                                    context=__class__.__name__)):
                        icon = ico_pgis
                    # Data file
                    elif option_type.startswith(
                            self.tr("Data file", context=__class__.__name__)):
                        icon = ico_file
                    # Unkown option
                    else:
                        logger.debug(
                            "Undefined add option type : {}/{} --> {}".format(
                                option_type, text, params))
                    # create the add button with the icon corresponding to the add option
                    add_button = QPushButton(icon, option_type)
                    add_button.setStyleSheet("text-align: left")
                    # connect the widget to the adding method from LayerAdder class
                    data_info["layer"] = ("info", params, count)
                    add_button.pressed.connect(
                        partial(self.lim_checker.check, data_info))
                    tbl_result.setCellWidget(count, 3, add_button)
                # Else, add a combobox, storing all possibilities.
                else:
                    combo = QComboBox()
                    for option in add_options_dict:
                        option_type = option.split(" : ")[0]
                        # services
                        if option_type.lower() in list(
                                self.service_dict.keys()):
                            icon = self.service_dict.get(
                                option_type.lower()).get("ico")
                        # PostGIS table
                        elif option.startswith(
                                self.tr("PostGIS table",
                                        context=__class__.__name__)):
                            icon = ico_pgis
                        # Data file
                        elif option.startswith(
                                self.tr("Data file",
                                        context=__class__.__name__)):
                            icon = ico_file
                        # Unkown option
                        else:
                            logger.debug(
                                "Undefined add option type : {}/{} --> {}".
                                format(option_type, text, params))
                        # add a combobox item with the icon corresponding to the add option
                        combo.addItem(icon, option,
                                      add_options_dict.get(option))
                    # connect the widget to the adding method from LayerAdder class
                    data_info["layer"] = ("index", count)
                    combo.activated.connect(
                        partial(self.lim_checker.check, data_info))
                    combo.model().sort(
                        0)  # sort alphabetically on option prefix. see: #113
                    tbl_result.setCellWidget(count, 3, combo)

            # make the widget (button or combobox) width the same as the column width
            tbl_result.cellWidget(count,
                                  3).setFixedWidth(hheader.sectionSize(3))
            count += 1

        # dimensions bis (see https://github.com/isogeo/isogeo-plugin-qgis/issues/276)
        # last column take the width of his content
        hheader.setSectionResizeMode(3, 3)
        # the height of the row adapts to the content without falling below 30px
        vheader.setMinimumSectionSize(30)
        vheader.setSectionResizeMode(3)
        # method ending
        return None
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 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()
Esempio n. 28
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. 29
0
class PoleRow(object):
    """
    Creates all input fields necessary to change the properties of a pole in
    the cable layout. The layout is identified by the position (index) it has
    in the vertical layout.
    """
    ICON_ADD_ROW = ":/plugins/SeilaplanPlugin/gui/icons/icon_addrow.png"
    ICON_DEL_ROW = ":/plugins/SeilaplanPlugin/gui/icons/icon_bin.png"

    def __init__(self,
                 parent,
                 widget,
                 layout,
                 idx,
                 nr,
                 name,
                 rowType,
                 dist,
                 distRange,
                 height=False,
                 angle=False,
                 delBtn=False,
                 addBtn=False):
        self.parent = parent
        self.widget = widget
        self.layout = layout
        self.index = idx
        self.rowType = rowType
        self.parent.poleCount += 1

        self.row = QHBoxLayout()
        self.row.setAlignment(Qt.AlignLeft)

        self.labelNr = None
        self.statusSwitcher = None
        self.fieldName = None
        self.fieldDist = None
        self.fieldHeight = None
        self.fieldAngle = None
        self.addBtn = None
        self.delBtn = None

        self.addRowToLayout()
        self.addBtnPlus(addBtn)
        if self.rowType == 'anchor':
            self.addSwitcher()
        else:
            self.addLabelNr(nr)
        self.addFieldName(name)
        self.addFieldDist(dist, distRange)
        if self.rowType not in ['anchor']:
            self.addFieldHeight(height)
            self.addFieldAngle(angle)
        self.addBtnDel(delBtn)

    def addRowToLayout(self):
        if self.index == self.parent.poleCount:
            # Add layout at the end
            self.layout.addLayout(self.row)
        else:
            # Insert new row between existing ones
            self.layout.insertLayout(self.index + 1, self.row)

    def addSwitcher(self):
        self.statusSwitcher = QCheckBox(self.widget)
        self.statusSwitcher.setText('')
        self.statusSwitcher.setFixedWidth(20)
        self.statusSwitcher.setChecked(True)
        self.row.addWidget(self.statusSwitcher)

        # Connect events
        self.statusSwitcher.stateChanged.connect(
            lambda newVal: self.parent.onRowChange(newVal == 2, self.index,
                                                   'active'))

    def addLabelNr(self, nr):
        self.labelNr = QLabel(self.widget)
        self.labelNr.setFixedWidth(20)
        self.labelNr.setAlignment(Qt.AlignVCenter | Qt.AlignRight)
        self.row.addWidget(self.labelNr)
        if nr:
            self.labelNr.setText(f"{nr}:")

    def updateIndex(self, idx):
        self.index = idx

    def updateLabelNr(self, label):
        if self.labelNr:
            if label:
                self.labelNr.setText(f"{label}:")
            else:
                self.labelNr.setText("")

    def addFieldName(self, value):
        self.fieldName = QLineEditWithFocus(self.widget)
        self.fieldName.setFocusPolicy(Qt.ClickFocus)
        self.fieldName.setFixedWidth(200)
        self.fieldName.setText(value)
        self.row.addWidget(self.fieldName)

        # Connect events
        self.fieldName.inFocus.connect(
            lambda x: self.parent.zoomIn(self.index))
        self.fieldName.outFocus.connect(self.parent.zoomOut)
        self.fieldName.textChanged.connect(
            lambda newVal: self.parent.onRowChange(newVal, self.index, 'name'))

    def addFieldDist(self, value, distRange):
        self.fieldDist = QDoubleSpinBoxWithFocus(self.widget)
        self.fieldDist.setFocusPolicy(Qt.ClickFocus)
        self.fieldDist.setDecimals(0)
        self.fieldDist.setSingleStep(self.parent.pole_dist_step)
        self.fieldDist.setSuffix(" m")
        self.fieldDist.setFixedWidth(95)
        self.fieldDist.setRange(float(distRange[0]), float(distRange[1]))
        self.fieldDist.setValue(float(value))
        self.row.addWidget(self.fieldDist)

        # Connect events
        self.fieldDist.inFocus.connect(
            lambda x: self.parent.zoomIn(self.index))
        self.fieldDist.outFocus.connect(self.parent.zoomOut)
        self.fieldDist.valueChanged.connect(
            lambda newVal: self.parent.onRowChange(newVal, self.index, 'd'))

    def addFieldHeight(self, value):
        if value is False:
            return
        self.fieldHeight = QDoubleSpinBoxWithFocus(self.widget)
        self.fieldHeight.setFocusPolicy(Qt.ClickFocus)
        self.fieldHeight.setDecimals(1)
        self.fieldHeight.setSingleStep(self.parent.pole_height_step)
        # Pole rows with type fixed are only used in profile window, so before
        #  optimization. That's why they only have 1 meter resolution.
        if self.rowType == 'fixed':
            self.fieldHeight.setDecimals(0)
            self.fieldHeight.setSingleStep(1)
        self.fieldHeight.setSuffix(" m")
        self.fieldHeight.setFixedWidth(95)
        self.fieldHeight.setRange(0.0, 50.0)
        if value is not None:
            self.fieldHeight.setValue(float(value))
        self.row.addWidget(self.fieldHeight)

        # Connect events
        self.fieldHeight.inFocus.connect(
            lambda x: self.parent.zoomIn(self.index))
        self.fieldHeight.outFocus.connect(self.parent.zoomOut)
        self.fieldHeight.valueChanged.connect(
            lambda newVal: self.parent.onRowChange(newVal, self.index, 'h'))

    def addFieldAngle(self, value):
        if value is False:
            return
        self.fieldAngle = QSpinBoxWithFocus(self.widget)
        self.fieldAngle.setFocusPolicy(Qt.ClickFocus)
        self.fieldAngle.setSuffix(" °")
        self.fieldAngle.setFixedWidth(60)
        self.fieldAngle.setRange(-180, 180)
        if value is not None:
            self.fieldAngle.setValue(int(value))
        self.row.addWidget(self.fieldAngle)

        # Connect events
        self.fieldAngle.inFocus.connect(
            lambda x: self.parent.zoomIn(self.index))
        self.fieldAngle.outFocus.connect(self.parent.zoomOut)
        self.fieldAngle.valueChanged.connect(
            lambda newVal: self.parent.onRowChange(newVal, self.index, 'angle'
                                                   ))

    def addBtnPlus(self, createButton):
        if createButton is False:
            self.row.addSpacing(33)
            return
        self.addBtn = QPushButton(self.widget)
        self.addBtn.setMaximumSize(QSize(27, 27))
        icon = QIcon()
        icon.addPixmap(QPixmap(PoleRow.ICON_ADD_ROW), QIcon.Normal, QIcon.Off)
        self.addBtn.setIcon(icon)
        self.addBtn.setIconSize(QSize(16, 16))
        self.addBtn.setToolTip(
            self.tr('Fuegt eine neue Stuetze nach dieser hinzu'))
        self.addBtn.setAutoDefault(False)
        self.row.addWidget(self.addBtn)

        self.addBtn.clicked.connect(lambda x: self.parent.onRowAdd(self.index))

    def addBtnDel(self, createButton):
        if createButton is False:
            self.row.addSpacing(33)
            return
        self.delBtn = QPushButton(self.widget)
        self.delBtn.setMaximumSize(QSize(27, 27))
        icon = QIcon()
        icon.addPixmap(QPixmap(PoleRow.ICON_DEL_ROW), QIcon.Normal, QIcon.Off)
        self.delBtn.setIcon(icon)
        self.delBtn.setIconSize(QSize(16, 16))
        self.delBtn.setToolTip(self.tr('Loescht die Stuetze'))
        self.delBtn.setAutoDefault(False)
        self.row.addWidget(self.delBtn)

        self.delBtn.clicked.connect(lambda x: self.parent.onRowDel(self.index))

    def updateLowerDistRange(self, minimum):
        self.fieldDist.setMinimum(minimum)

    def updateUpperDistRange(self, maximum):
        self.fieldDist.setMaximum(maximum)

    def activate(self):
        self.statusSwitcher.blockSignals(True)
        self.statusSwitcher.setChecked(True)
        self.statusSwitcher.blockSignals(False)
        self.fieldName.setEnabled(True)
        self.fieldDist.setEnabled(True)

    def deactivate(self):
        self.statusSwitcher.blockSignals(True)
        self.statusSwitcher.setChecked(False)
        self.statusSwitcher.blockSignals(False)
        self.fieldName.setEnabled(False)
        self.fieldDist.setEnabled(False)

    def remove(self):
        # Disconnect all widgets
        self.fieldName.disconnect()
        self.fieldDist.disconnect()
        if self.fieldHeight: self.fieldHeight.disconnect()
        if self.fieldAngle: self.fieldAngle.disconnect()
        if self.addBtn: self.addBtn.disconnect()
        if self.delBtn: self.delBtn.disconnect()

        for i in reversed(range(self.row.count())):
            item = self.row.takeAt(i)
            widget = item.widget()
            if widget is not None:
                widget.deleteLater()
            else:
                # For spacers
                self.row.removeItem(item)

        self.layout.removeItem(self.row)
        self.parent.poleCount -= 1

    # 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)