コード例 #1
0
    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
コード例 #2
0
    def __handle_found(self, uldk_response_rows):
        uldk_response_rows = validators.duplicate_rows(uldk_response_rows)
        if len(uldk_response_rows) > 1:
            try:    
                self.ui.combobox_sheet.activated.disconnect()
            except TypeError:
                pass #w przypadku braku przypiętych slotów rzuca wyjątkiem
            self.ui.combobox_sheet.activated.connect(self.__search_from_sheet)
            self.ui.combobox_sheet.setEnabled(True)
            self.ui.combobox_sheet.clear()
            for row in uldk_response_rows:
                row_split = row.split("|")
                sheet_name = row_split[-1].split('.')[2]

                self.ui.combobox_sheet.addItem(sheet_name, row)
            self.message_bar_item = QgsMessageBarItem("Wtyczka ULDK", "Wybrana działka znajduje się na różnych arkuszach map. Wybierz z listy jedną z nich.")
            iface.messageBar().widgetRemoved.connect(self.__delete_message_bar)
            iface.messageBar().pushWidget(self.message_bar_item)
        else:
            result = uldk_response_rows[0]
            
            try:
                added_feature = self.result_collector.update(result)
            except self.result_collector.BadGeometryException:
                iface.messageBar().pushCritical("Wtyczka ULDK", f"Działka posiada niepoprawną geometrię")
                return
            self.result_collector.zoom_to_feature(added_feature)

            if self.message_bar_item:
                iface.messageBar().popWidget(self.message_bar_item)

            iface.messageBar().pushSuccess("Wtyczka ULDK", "Zaaktualizowano warstwę '{}'"
                                            .format(self.result_collector.layer.sourceName()))
コード例 #3
0
    def __handle_finished(self):
        self.__collect_received_features()
        form = "obiekt"
        found_count = self.found_count
        if found_count == 1:
            pass
        elif 2 <= found_count <= 4:
            form = "obiekty"
        elif 5 <= found_count <= 15:
            form = "obiektów"
        else:
            units = found_count % 10
            if units in (2, 3, 4):
                form = "obiekty"
            else:
                form = "obiektów"

        iface.messageBar().pushWidget(
            QgsMessageBarItem(
                "Wtyczka ULDK",
                f"Import CSV: zakończono wyszukiwanie. Zapisano {found_count} {form} do warstwy <b>{self.ui.text_edit_layer_name.text()}</b>"
            ))
        if self.not_found_count > 0:
            self.ui.button_save_not_found.setEnabled(True)

        self.__cleanup_after_search()
コード例 #4
0
    def __handle_found(self, uldk_response_rows):
        if len(uldk_response_rows) > 1:
            self.ui.combobox_sheet.setEnabled(True)
            self.ui.combobox_sheet.clear()
            for row in uldk_response_rows:
                row = row.split("|")
                sheet_name = row[-3]
                sheet_teryt = row[-1]

                self.ui.combobox_sheet.addItem(sheet_name, sheet_teryt)
            self.message_bar_item = QgsMessageBarItem(
                "Wtyczka ULDK",
                "Wybrana działka znajduje się na różnych arkuszach map. Wybierz z listy jedną z nich."
            )
            self.iface.messageBar().pushWidget(self.message_bar_item)
        else:
            result = uldk_response_rows[0]

            added_feature = self.result_collector.update(result)
            self.result_collector.zoom_to_feature(added_feature)

            if self.message_bar_item:
                self.iface.messageBar().popWidget(self.message_bar_item)
                self.message_bar_item = None

            self.iface.messageBar().pushSuccess(
                "Wtyczka ULDK", "Zaaktualizowano warstwę '{}'".format(
                    self.result_collector.layer.sourceName()))
コード例 #5
0
 def __handle_finished(self, layer_found, layer_not_found):
     self.__cleanup_after_search()
     iface.messageBar().pushWidget(
         QgsMessageBarItem(
             "Wtyczka ULDK",
             f"Import z warstwy: zakończono wyszukiwanie. Zapisano {self.saved_count} {get_obiekty_form(self.saved_count)} do warstwy <b>{self.ui.text_edit_target_layer_name.text()}</b>"
         ))
コード例 #6
0
 def __init__(self, min, max, message, parent=None, timeout=1.5):
     """
     Constructs a progress widget
     """
     super(self.__class__, self).__init__(parent)
     self.min = min
     self.max = max
     sizePolicy = QSizePolicy(QSizePolicy.MinimumExpanding,
                              QSizePolicy.Fixed)
     if parent:
         self.setMinimumSize(parent.width(), 40)
     else:
         self.setMinimumSize(766, 40)
     self.setSizePolicy(sizePolicy)
     self.progressBar = QProgressBar()
     self.progressBar.setMinimum(min)
     self.progressBar.setMaximum(max)
     self.parent = parent
     self.msgBarItem = QgsMessageBarItem(self.tr("INFO: "),
                                         message,
                                         self.progressBar,
                                         level=Qgis.Info,
                                         duration=timeout,
                                         parent=self.parent)
     self.pushItem(self.msgBarItem)
     self.parent.repaint()
コード例 #7
0
 def show_message(self, title: str, msg: str, level: Qgis.MessageLevel, widget: QWidget = None):
     if widget:
         self.widget = widget
         self.item = QgsMessageBarItem(title, msg, self.widget, level, 7)
         self.iface.messageBar().pushItem(self.item)
     else:
         self.iface.messageBar().pushMessage(title, msg, level)
コード例 #8
0
 def showErrorDatabaseProjectMismatch(self):
     self.openDatabaseProjectMismatchMessageBarItem = QgsMessageBarItem(
         'Valittu tietokanta ei vastaa työtilaa', Qgis.Warning, duration=0)
     self.iface.messageBar().pushItem(
         self.openDatabaseProjectMismatchMessageBarItem)
     self.dockWidget.pushButtonSettings.setStyleSheet(
         'QPushButton {background-color: red; color: #white;}')
コード例 #9
0
 def showErrorBecauseProjectNotRead(self):
     self.openProjectMessageBarItem = QgsMessageBarItem(
         'Yleiskaavan QGIS-työtila pitää käynnistää ennen työkalujen käyttöä',
         Qgis.Warning,
         duration=10)
     self.iface.messageBar().pushItem(self.openProjectMessageBarItem)
     self.iface.projectRead.connect(self.handleProjectRead)
コード例 #10
0
    def search_lpis(self):
        teryt = self.ui.lineedit_full_teryt.text()
        lpis_response = lpis_api.search(teryt)

        if len(lpis_response) == 0:
            iface.messageBar().pushCritical("Wtyczka ULDK", f"Nie znaleziono przybliżonej lokacji działki{teryt}")
        elif len(lpis_response) > 1:
            combobox = self.ui.combobox_sheet
            def _zoom_to_lpis_wrapper():
                self._zoom_to_lpis(combobox.currentData())
                self.lpis_bbox_found.emit()
                combobox.clear()
                combobox.setEnabled(False)

            self.message_bar_item = QgsMessageBarItem("Wtyczka ULDK", "Wybrana działka znajduje się na różnych arkuszach map. Wybierz z listy jedną z nich.")
            iface.messageBar().pushWidget(self.message_bar_item)
            
            combobox.setEnabled(True)
            combobox.clear()
            for row in lpis_response:
                combobox.addItem(row["arkusz"], row)

            try:
                combobox.activated.disconnect()
            except TypeError:
                pass #w przypadku braku przypiętych slotów rzuca wyjątkiem
            combobox.activated.connect(_zoom_to_lpis_wrapper)
        else:
            self._zoom_to_lpis(lpis_response[0])
            self.lpis_bbox_found.emit()
コード例 #11
0
 def __handle_finished_precinct_unknown(self):
     self.result_collector_precinct_unknown.update(self.plots_found)
     self.iface.messageBar().pushWidget(
         QgsMessageBarItem(
             "Wtyczka ULDK",
             f"Wyszukiwanie działek: zapisano znalezione działki do warstwy <b>{self.result_collector_precinct_unknown.layer.sourceName()}</b>"
         ))
     self.ui.button_search.show()
     self.ui.progress_bar_precinct_unknown.hide()
コード例 #12
0
 def addLayer(self, geometryType=None, crs=None):
     layer = self.toMapLayer(geometryType, crs)
     layers = QgsProject.instance().addMapLayers([layer])
     if len(layers) != 1:
         QgsMessageLog.logMessage(self.tr("{layer} is an invalid layer - not loaded").format(layer=layer.publicSource()))
         msgLabel = QLabel(self.tr("{layer} is an invalid layer and cannot be loaded. Please check the <a href=\"#messageLog\">message log</a> for further info.").format(layer=layer.publicSource()), self.mainWindow.infoBar)
         msgLabel.setWordWrap(True)
         msgLabel.linkActivated.connect(self.mainWindow.iface.mainWindow().findChild(QWidget, "MessageLog").show)
         msgLabel.linkActivated.connect(self.mainWindow.iface.mainWindow().raise_)
         self.mainWindow.infoBar.pushItem(QgsMessageBarItem(msgLabel, Qgis.Warning))
コード例 #13
0
    def __handle_finished(self, layer_found, layer_not_found):
        self.__cleanup_after_search()

        if layer_found.dataProvider().featureCount():
            QgsProject.instance().addMapLayer(layer_found)
        if layer_not_found.dataProvider().featureCount():
            QgsProject.instance().addMapLayer(layer_not_found)

        iface.messageBar().pushWidget(
            QgsMessageBarItem(
                "Wtyczka ULDK",
                f"Wyszukiwarka działek z warstwy: zakończono wyszukiwanie. Zapisano {self.saved_count} {get_obiekty_form(self.saved_count)} do warstwy <b>{self.ui.text_edit_target_layer_name.text()}</b>"
            ))
コード例 #14
0
 def addLayer(self):
     table = self.currentTable()
     if table is not None:
         layer = table.toMapLayer()
         layers = QgsMapLayerRegistry.instance().addMapLayers([layer])
         if len(layers) != 1:
             QgsMessageLog.instance().logMessage(
                 self.tr("%1 is an invalid layer - not loaded").replace("%1", layer.publicSource()))
             msgLabel = QLabel(self.tr(
                 "%1 is an invalid layer and cannot be loaded. Please check the <a href=\"#messageLog\">message log</a> for further info.").replace(
                 "%1", layer.publicSource()), self.mainWindow.infoBar)
             msgLabel.setWordWrap(True)
             self.connect(msgLabel, SIGNAL("linkActivated( QString )"),
                          self.mainWindow.iface.mainWindow().findChild(QWidget, "MessageLog"), SLOT("show()"))
             self.connect(msgLabel, SIGNAL("linkActivated( QString )"),
                          self.mainWindow.iface.mainWindow(), SLOT("raise()"))
             self.mainWindow.infoBar.pushItem(QgsMessageBarItem(msgLabel, QgsMessageBar.WARNING))
コード例 #15
0
 def _export_table_errors_to_csv(self):
     count = self.ui.table_errors.rowCount()
     path, _ = QFileDialog.getSaveFileName(filter='*.csv')
     if path:
         with open(path, 'w') as f:
             writer = csv.writer(f, delimiter=',')
             writer.writerow([
                 self.ui.table_errors.horizontalHeaderItem(0).text(),
                 self.ui.table_errors.horizontalHeaderItem(1).text()
             ])
             for row in range(0, count):
                 teryt = self.ui.table_errors.item(row, 0).text()
                 error = self.ui.table_errors.item(row, 1).text()
                 writer.writerow([teryt, error])
             iface.messageBar().pushWidget(
                 QgsMessageBarItem(
                     "Wtyczka ULDK",
                     "Pomyślnie wyeksportowano nieznalezione działki."))
コード例 #16
0
ファイル: main.py プロジェクト: bgisb/gis-support-plugin
    def search_lpis(self):
        teryt = self.ui.lineedit_full_teryt.text()
        key = QSettings().value('gissupport/api/key')
        if not key:
            messageBox = QMessageBox.warning(
                None, "Wtyczka GIS Support",
                "Korzystanie z danych historycznych wymaga uzupełnienia klucza GIS Support. Więcej informacji w menu wtyczki w zakładce <b>Klucz GIS Support</b>."
            )
            return
        lpis_response = lpis_api.search(teryt, key)
        if len(lpis_response) == 0:
            self.parent.iface.messageBar().pushCritical(
                "Wtyczka ULDK",
                f"Nie znaleziono przybliżonej lokacji działki{teryt}")
        elif len(lpis_response) > 1:
            combobox = self.ui.combobox_sheet

            def _zoom_to_lpis_wrapper():
                self._zoom_to_lpis(combobox.currentData())
                self.lpis_bbox_found.emit()
                combobox.clear()
                combobox.setEnabled(False)

            self.message_bar_item = QgsMessageBarItem(
                "Wtyczka ULDK",
                "Wybrana działka znajduje się na różnych arkuszach map. Wybierz z listy jedną z nich."
            )
            self.iface.messageBar().pushWidget(self.message_bar_item)

            combobox.setEnabled(True)
            combobox.clear()
            for row in lpis_response:
                combobox.addItem(row["arkusz"], row)

            try:
                combobox.activated.disconnect()
            except TypeError:
                pass  #w przypadku braku przypiętych slotów rzuca wyjątkiem
            combobox.activated.connect(_zoom_to_lpis_wrapper)
        else:
            self._zoom_to_lpis(lpis_response[0])
            self.lpis_bbox_found.emit()
コード例 #17
0
ファイル: utils.py プロジェクト: gem/oq-irmt-qgis
def log_msg(message, tag='GEM OpenQuake IRMT plugin', level='I',
            message_bar=None, duration=None, exception=None,
            print_to_stderr=False, print_to_stdout=False):
    """
    Add a message to the QGIS message log. If a messageBar is provided,
    the same message will be displayed also in the messageBar. In the latter
    case, warnings and critical messages will have no timeout, whereas
    info messages will have a duration of 5 seconds.

    :param message: the message
    :param tag: the log topic
    :param level:
        the importance level
        'I' -> Qgis.Info,
        'W' -> Qgis.Warning,
        'C' -> Qgis.Critical,
        'S' -> Qgis.Success,
    :param message_bar: a `QgsMessageBar` instance
    :param duration: how long (in seconds) the message will be displayed (use 0
        to keep the message visible indefinitely, or None to use
        the default duration of the chosen level
    :param exception: an optional exception, from which the traceback will be
        extracted and written in the log. When the exception is provided,
        an additional button in the `QgsMessageBar` allows to visualize the
        traceback in a separate window.
    :print_to_stderr: if True, the error message will be printed also to stderr
    """
    levels = {
              'I': Qgis.Info,
              'W': Qgis.Warning,
              'C': Qgis.Critical,
              'S': Qgis.Success,
              }
    if level not in levels:
        raise ValueError('Level must be one of %s' % levels.keys())
    tb_text = ''
    if exception is not None:
        tb_lines = traceback.format_exception(
            exception.__class__, exception, exception.__traceback__)
        tb_text = '\n' + ''.join(tb_lines)

    # if we are running tests, exit on critical errors
    if 'GEM_QGIS_TEST' in os.environ and level == 'C':
        raise RuntimeError(message + tb_text)
    else:
        log_verbosity = QSettings().value('irmt/log_level', 'W')
        if (level == 'C'
                or level == 'W' and log_verbosity in ('S', 'I', 'W')
                or level in ('I', 'S') and log_verbosity in ('I', 'S')):
            QgsMessageLog.logMessage(
                tr(message) + tb_text, tr(tag), levels[level])
            if exception is not None:
                tb_btn = QToolButton(message_bar)
                tb_btn.setText('Show Traceback')
                tb_btn.clicked.connect(
                    lambda: _on_tb_btn_clicked(tr(message), tb_text))
        if message_bar is not None:
            if level == 'S':
                title = 'Success'
                duration = duration if duration is not None else 8
            elif level == 'I':
                title = 'Info'
                duration = duration if duration is not None else 8
            elif level == 'W':
                title = 'Warning'
                duration = duration if duration is not None else 0
            elif level == 'C':
                title = 'Error'
                duration = duration if duration is not None else 0
            max_msg_len = 120
            if len(message) > max_msg_len:
                display_text = ("%s[...]" % message[:max_msg_len])
                show_more = "[...]%s" % message[max_msg_len:]
            else:
                display_text = message
                show_more = None
            if exception is None:
                if show_more is not None:
                    message_bar.pushMessage(tr(title),
                                            tr(display_text),
                                            tr(show_more),
                                            levels[level],
                                            duration)
                else:
                    message_bar.pushMessage(tr(title),
                                            tr(display_text),
                                            levels[level],
                                            duration)
            else:
                mb_item = QgsMessageBarItem(
                    tr(title), tr(display_text), tb_btn, levels[level],
                    duration)
                message_bar.pushItem(mb_item)
        if print_to_stderr:
            print('\t\t%s: %s' % (datetime.now(), message + tb_text),
                  file=sys.stderr)
        if print_to_stdout:
            print('\t\t%s: %s' % (datetime.now(), message + tb_text),
                  file=sys.stdout)