示例#1
0
        class listview(QDialog):
            name = "class"

            def __init__(self, table):
                super().__init__()
                self.table = table
                self.title = "Hinzufügen"
                self.top = 600
                self.left = 200
                self.width = 350
                self.height = 450

                self.initWindow()

            def initWindow(self):
                self.addButton = QPushButton("Hinzufügen", self)
                self.closeButton = QPushButton("Schließen", self)
                self.listWidget = QListWidget(self)
                self.listWidget.move(50, 50)
                self.listWidget.resize(250, 350)
                self.addButton.move(100, 410)
                self.addButton.clicked.connect(self.add)
                self.closeButton.move(220, 410)
                self.closeButton.clicked.connect(self.closing)

                self.setWindowTitle(self.title)
                self.setGeometry(self.top, self.left, self.width, self.height)

            def fill(self):
                self.listWidget.clear()
                if self.table.missingattr != []:
                    self.listWidget.addItems(self.table.missingattr)
                self.show()

            def add(self):
                print([li.text() for li in self.listWidget.selectedItems()])
                self.table.add(
                    [li.text() for li in self.listWidget.selectedItems()])
                self.fill()
                print("ok")

            def closing(self):
                self.close()
示例#2
0
class DataSelector(QDialog):
    def __init__(self, viewer, features, config_list, config):
        QDialog.__init__(self)

        self.__viewer = viewer
        self.__features = features
        self.__config_list = config_list
        self.__config = config
        vbox = QVBoxLayout()

        btn = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        btn.accepted.connect(self.accept)
        btn.rejected.connect(self.reject)

        self.__list = QListWidget()
        self.__list.setSelectionMode(QAbstractItemView.ExtendedSelection)

        hbox = QHBoxLayout()
        lbl = QLabel("Sub selection")
        self.__sub_selection_combo = QComboBox()
        self.__sub_selection_combo.setEnabled(False)
        hbox.addWidget(lbl)
        hbox.addWidget(self.__sub_selection_combo)

        self.__title_label = QLabel()

        hbox2 = QHBoxLayout()
        hbox2.addWidget(self.__title_label)

        vbox.addLayout(hbox2)
        vbox.addWidget(self.__list)
        vbox.addLayout(hbox)
        vbox.addWidget(btn)

        self.__list.itemSelectionChanged.connect(self.on_selection_changed)
        self.__sub_selection_combo.currentIndexChanged[str].connect(
            self.on_combo_changed)

        self.setLayout(vbox)
        self.setWindowTitle("Choose the data to add")
        self.resize(400, 200)

        self._populate_list()
        self.set_title(",".join([
            feature[self.__config["name_column"]]
            for feature in self.__features
        ]))

    def set_title(self, title):
        self.__title_label.setText("Station(s): {}".format(title))

    def _populate_list(self):
        self.__list.clear()
        for cfg in self.__config_list:
            if cfg["type"] in ("cumulative", "instantaneous"):
                # check number of features for this station

                if cfg.get("feature_filter_type") == "unique_data_from_values":
                    # get unique filter values

                    layerid = cfg["source"]
                    data_l = QgsProject.instance().mapLayers()[layerid]
                    values = set()
                    for feature in self.__features:
                        feature_id = feature[self.__config["id_column"]]
                        req = QgsFeatureRequest()
                        req.setFilterExpression("{}={}".format(
                            cfg["feature_ref_column"], feature_id))
                        values.update([
                            f[cfg["feature_filter_column"]]
                            for f in data_l.getFeatures(req)
                        ])

                        cfg.set_filter_unique_values(sorted(list(values)))

            item = QListWidgetItem(cfg["name"])
            item.setData(Qt.UserRole, cfg)
            self.__list.addItem(item)

    def accept(self):

        for feature in self.__features:
            self.__load_feature(feature)

    def __load_feature(self, feature):
        # FIXME this code too similar to main_dialog.load_plots
        # FIXME find a way to factor

        feature_id = feature[self.__config["id_column"]]
        feature_name = feature[self.__config["name_column"]]

        for item in self.__list.selectedItems():
            # now add the selected configuration
            cfg = item.data(Qt.UserRole)
            if cfg["type"] in ("cumulative", "instantaneous", "continuous"):
                layerid = cfg["source"]
                data_l = QgsProject.instance().mapLayers()[layerid]
                req = QgsFeatureRequest()
                filter_expr = "{}='{}'".format(cfg["feature_ref_column"],
                                               feature_id)
                req.setFilterExpression(filter_expr)

                title = cfg["name"]

                if cfg.get_filter_value():
                    filter_expr += " and {}='{}'".format(
                        cfg["feature_filter_column"], cfg.get_filter_value())

                    title = cfg.get_filter_value()
                else:
                    title = cfg["name"]

                f = None
                # test if the layer actually contains data
                for f in data_l.getFeatures(req):
                    break
                if f is None:
                    return
                if cfg["type"] == "instantaneous":
                    uom = cfg.get_uom()
                    data = LayerData(data_l,
                                     cfg["event_column"],
                                     cfg["value_column"],
                                     filter_expression=filter_expr,
                                     uom=uom)
                    uom = data.uom()
                    self.__viewer.add_data_cell(data,
                                                title,
                                                uom,
                                                station_name=feature_name,
                                                config=cfg)
                    self.__viewer.add_scale()
                if cfg["type"] == "continuous":
                    uom = cfg.get_uom()
                    fids = [f.id() for f in data_l.getFeatures(req)]
                    data = FeatureData(
                        data_l,
                        cfg["values_column"],
                        feature_ids=fids,
                        x_start_fieldname=cfg["start_measure_column"],
                        x_delta_fieldname=cfg["interval_column"])
                    self.__viewer.add_data_cell(data,
                                                title,
                                                uom,
                                                station_name=feature_name,
                                                config=cfg)
                elif cfg["type"] == "cumulative":
                    self.__viewer.add_histogram(
                        data_l,
                        filter_expression=filter_expr,
                        column_mapping={
                            f: cfg[f]
                            for f in ("min_event_column", "max_event_column",
                                      "value_column")
                        },
                        title=title,
                        config=cfg,
                        station_name=feature_name)

            elif cfg["type"] == "image":
                self.__viewer.add_imagery_from_db(cfg, feature_id)

        QDialog.accept(self)

    def on_selection_changed(self):
        self.__sub_selection_combo.clear()
        self.__sub_selection_combo.setEnabled(False)
        for item in self.__list.selectedItems():
            cfg = item.data(Qt.UserRole)
            for v in cfg.get_filter_unique_values():
                self.__sub_selection_combo.addItem(v)
            if cfg.get_filter_value():
                self.__sub_selection_combo.setCurrentIndex(
                    self.__sub_selection_combo.findText(
                        cfg.get_filter_value()))
            self.__sub_selection_combo.setEnabled(True)
            return

    def on_combo_changed(self, text):
        for item in self.__list.selectedItems():
            cfg = item.data(Qt.UserRole)
            cfg.set_filter_value(text)
            item.setData(Qt.UserRole, cfg)
            return
class ScenarioSelectionDialog(QDialog):
    """
    A dialog used for selecting from available scenarios
    """

    def __init__(self, scenario_registry: ScenarioRegistry, parent=None):
        """
        Constructor for ScenarioSelectionDialog
        :param scenario_registry: linked scenario registry
        :param parent: parent widget
        """
        super().__init__(parent)

        self.scenario_registry = scenario_registry

        self.setWindowTitle(self.tr('Select Current Scenario'))

        layout = QVBoxLayout()

        self.search = QgsFilterLineEdit()
        self.search.setShowSearchIcon(True)
        self.search.setPlaceholderText(self.tr('Search for scenario'))
        self.search.textChanged.connect(self.filter_changed)
        layout.addWidget(self.search)

        self.list = QListWidget()
        for title, scenario_id in scenario_registry.scenario_titles().items():
            item = QListWidgetItem(title)
            item.setData(Qt.UserRole, scenario_id)
            self.list.addItem(item)

        layout.addWidget(self.list, 10)

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

        self.setLayout(layout)

        self.list.itemDoubleClicked.connect(
            self.accept)

        # select last scenario by default
        if self.list.count() > 0:
            self.list.item(self.list.count() - 1).setSelected(True)

    def set_selected_scenario(self, scenario):
        """
        Sets the scenario selected in the dialog
        :param scenario: scenario to select
        """
        for i in range(self.list.count()):
            if self.list.item(i).data(Qt.UserRole) == scenario:
                self.list.item(i).setSelected(True)
                return

    def selected_scenario(self):
        """
        Returns the scenario selected in the dialog
        """
        if self.list.selectedItems():
            return self.list.selectedItems()[0].data(Qt.UserRole)

        return None

    def filter_changed(self, filter_text):
        """
        Handles search filter changes
        """
        for i in range(self.list.count()):
            item = self.list.item(i)
            item.setHidden(filter_text.upper() not in item.text().upper())
class DeprecateElectorateDialog(QDialog):
    """
    A dialog used for selecting electorates to deprecate (or un-deprecate)
    :param district_registry: associated registry of available
    districts to show
    """
    def __init__(self,
                 electorate_registry: LinzElectoralDistrictRegistry,
                 parent=None):
        super().__init__(parent)

        self.electorate_registry = electorate_registry

        self.setWindowTitle(self.tr('Deprecate Electorate'))

        layout = QVBoxLayout()

        self.search = QgsFilterLineEdit()
        self.search.setShowSearchIcon(True)
        self.search.setPlaceholderText(
            self.tr('Search for {}').format(
                electorate_registry.type_string_sentence()))
        self.search.textChanged.connect(self.filter_changed)
        layout.addWidget(self.search)

        request = QgsFeatureRequest()
        request.setFlags(QgsFeatureRequest.NoGeometry)
        request.setSubsetOfAttributes([
            electorate_registry.source_field_index,
            electorate_registry.title_field_index,
            electorate_registry.deprecated_field_index
        ])
        self.list = QListWidget()
        for f in electorate_registry.source_layer.getFeatures(request):
            title = f[electorate_registry.title_field_index]
            code = f[electorate_registry.source_field_index]
            deprecated = f[electorate_registry.deprecated_field_index]

            if deprecated:
                title = '*' + title
            item = QListWidgetItem(title)
            item.setData(Qt.UserRole, code)
            self.list.addItem(item)

        layout.addWidget(self.list, 10)

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

        self.setLayout(layout)
        self.list.itemDoubleClicked.connect(self.accept)

    def selected_district(self):
        """
        Returns the electorate selected in the dialog
        """
        if self.list.selectedItems():
            return self.list.selectedItems()[0].data(Qt.UserRole)

        return None

    def filter_changed(self, filter_text):
        """
        Handles search filter changes
        """
        for i in range(self.list.count()):
            item = self.list.item(i)
            item.setHidden(filter_text.upper() not in item.text().upper())
示例#5
0
class TagsDialog(QDialog):

    def __init__(self, dockwidget, parent, params):

        QDialog.__init__(self, parent)
        main_lay = QVBoxLayout(self)
        self.dockwidget = dockwidget
        self.params = params

        self.setWindowTitle('Tags editor')

        # Top frame
        self.fra_top = QFrame()
        fra_top_lay = QVBoxLayout(self.fra_top)

        self.lst_main = QListWidget(self)
        self.btn_add = QPushButton('Add tag')
        self.btn_add.clicked.connect(self.add_tag)
        self.btn_remove = QPushButton('Remove tag')
        self.btn_remove.clicked.connect(self.remove_tag)

        fra_top_lay.addWidget(self.lst_main)
        fra_top_lay.addWidget(self.btn_add)
        fra_top_lay.addWidget(self.btn_remove)

        # Bottom frame
        self.fra_bottom = QFrame()
        fra_bottom_lay = QHBoxLayout(self.fra_bottom)

        btb_main = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        btb_main.accepted.connect(self.ok)
        btb_main.rejected.connect(self.reject)

        fra_bottom_lay.addWidget(btb_main)

        # Main
        main_lay.addWidget(self.fra_top)
        main_lay.addWidget(self.fra_bottom)

        self.initialize()

    def initialize(self):
        for tag_name in self.params.tag_names:
            self.lst_main.insertItem(self.lst_main.count(), QListWidgetItem(tag_name, self.lst_main))

    def ok(self):
        tag_names = []
        for r in range(self.lst_main.count()):
            tag_names.append(self.lst_main.item(r).text())

        self.params.tag_names = tag_names

        self.setVisible(False)

    def reject(self):
        self.setVisible(False)

    def add_tag(self):

        tag_name_dialog = TagNameDialog(self.dockwidget, self)
        tag_name_dialog.exec_()
        tag_name = tag_name_dialog.get_tag_name()

        if tag_name is not None:
            current_row = self.lst_main.currentRow()
            if current_row is None:
                current_row = self.lst_main.count()
            self.lst_main.insertItem(current_row, QListWidgetItem(tag_name, self.lst_main))

    def remove_tag(self):
        sel_items = self.lst_main.selectedItems()
        for sel_item in sel_items:
            self.lst_main.takeItem(self.lst_main.row(sel_item))
示例#6
0
class AnnotationManager:
    def __init__(self, iface):
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(os.path.dirname(__file__), 'i18n',
                                   'annotationManager_{}.qm'.format(locale))

        self.translator = None
        if os.path.exists(locale_path):
            self.translator = QTranslator()
            self.translator.load(locale_path)

        if qVersion() > '4.3.3':
            QCoreApplication.installTranslator(self.translator)

        self.iface = iface
        self.iface.projectRead.connect(self.projectOpen)

        self.dock = QDockWidget(self.tr('Annotations'))
        self.manager = QWidget()
        toolbar = QToolBar()

        self.annotationList = QListWidget()
        self.annotationList.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        self.annotationList.itemSelectionChanged.connect(self.selectAnnotation)
        self.annotationList.itemChanged.connect(self.checkItem)
        action_refresh = QAction(
            QIcon(':/plugins/annotationManager/resources/mActionDraw.png'),
            self.tr('Refresh the annotations list'), self.manager)
        action_refresh.triggered.connect(self.refreshAnnotations)
        action_remove = QAction(
            QIcon(
                ':/plugins/annotationManager/resources/mActionRemoveAnnotation.png'
            ), self.tr('Remove the selected annotation'), self.manager)
        action_remove.triggered.connect(self.removeAnnotation)

        viewMenu = QMenu()
        action_showAll = QAction(
            QIcon(':/plugins/annotationManager/resources/mActionShowAll.png'),
            self.tr('Show all annotations'), self.manager)
        action_showAll.triggered.connect(self.showAll)
        action_hideAll = QAction(
            QIcon(':/plugins/annotationManager/resources/mActionHideAll.png'),
            self.tr('Hide all annotations'), self.manager)
        action_hideAll.triggered.connect(self.hideAll)
        action_showAllSelected = QAction(
            QIcon(':/plugins/annotationManager/resources/mActionShowAll.png'),
            self.tr('Show all selected annotations'), self.manager)
        action_showAllSelected.triggered.connect(self.showAllSelected)
        action_hideAllSelected = QAction(
            QIcon(':/plugins/annotationManager/resources/mActionHideAll.png'),
            self.tr('Hide all selected annotations'), self.manager)
        action_hideAllSelected.triggered.connect(self.hideAllSelected)
        viewMenu.addAction(action_showAll)
        viewMenu.addAction(action_hideAll)
        viewMenu.addAction(action_showAllSelected)
        viewMenu.addAction(action_hideAllSelected)
        viewButton = QToolButton()
        viewButton.setIcon(
            QIcon(':/plugins/annotationManager/resources/mActionShowAll.png'))
        viewButton.setPopupMode(2)
        viewButton.setMenu(viewMenu)

        toolbar.addAction(action_refresh)
        toolbar.addAction(action_remove)
        toolbar.addWidget(viewButton)
        toolbar.setIconSize(QSize(16, 16))

        p1_vertical = QVBoxLayout()
        p1_vertical.setContentsMargins(0, 0, 0, 0)
        p1_vertical.addWidget(toolbar)
        p1_vertical.addWidget(self.annotationList)
        self.manager.setLayout(p1_vertical)

        self.dock.setWidget(self.manager)
        self.dock.setAllowedAreas(Qt.LeftDockWidgetArea
                                  | Qt.RightDockWidgetArea)
        self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dock)

        self.rb = QgsRubberBand(self.iface.mapCanvas(),
                                QgsWkbTypes.PolygonGeometry)

        self.project = QgsProject.instance()
        self.annotationManager = self.project.annotationManager()
        self.annotationManager.annotationAdded.connect(self.refreshAnnotations)
        self.annotationManager.annotationRemoved.connect(
            self.refreshAnnotations)

    def checkItem(self, item):
        index = self.annotationList.row(item)
        if item.checkState() == Qt.Checked:
            self.annotationManager.annotations()[index].setVisible(True)
        else:
            self.annotationManager.annotations()[index].setVisible(False)
            if item.isSelected():
                item.setSelected(False)
                self.rb.reset(QgsWkbTypes.PolygonGeometry)

    def selectAnnotation(self):
        self.rb.reset(QgsWkbTypes.PolygonGeometry)
        self.rb.setColor(QColor(0, 0, 255, 128))
        for item in self.annotationList.selectedItems():
            index = self.annotationList.row(item)
            mapTool = QgsMapTool(self.iface.mapCanvas())
            point = mapTool.toCanvasCoordinates(
                self.annotationManager.annotations()[index].mapPosition())
            pt1 = mapTool.toMapCoordinates(
                QPoint(point.x() - 10,
                       point.y() - 10))
            pt2 = mapTool.toMapCoordinates(
                QPoint(point.x() + 10,
                       point.y() + 10))
            rect = QgsRectangle(pt1, pt2)
            poly = QgsGeometry().fromRect(rect)
            self.rb.addGeometry(poly, None)

    def showAll(self):
        count = self.annotationList.count()
        for i in range(count):
            self.annotationList.item(i).setCheckState(Qt.Checked)

    def hideAll(self):
        count = self.annotationList.count()
        for i in range(count):
            self.annotationList.item(i).setCheckState(Qt.Unchecked)

    def showAllSelected(self):
        for item in self.annotationList.selectedItems():
            item.setCheckState(Qt.Checked)

    def hideAllSelected(self):
        for item in self.annotationList.selectedItems():
            item.setCheckState(Qt.Unchecked)

    def unload(self):
        del self.dock

    def tr(self, message):
        return QCoreApplication.translate('AnnotationManager', message)

    def refreshAnnotationTitle(self, annotation=None):
        if annotation is None:
            annotation = self.project.annotationManager().sender()
        item = self.annotationList.item(
            self.annotationManager.annotations().index(annotation))
        title = 'Annotation'
        if isinstance(annotation, QgsTextAnnotation):
            title = annotation.document().toPlainText().split('\n')[0]
            if len(title) > 40:
                title = title[:40] + '(...)'
        item.setText(title)

    def refreshAnnotations(self):
        self.annotationList.clearSelection()
        self.annotationList.clear()
        for annotation in self.annotationManager.annotations():
            item = QListWidgetItem()
            annotation.appearanceChanged.connect(self.refreshAnnotationTitle)
            if annotation.isVisible():
                item.setCheckState(Qt.Checked)
            else:
                item.setCheckState(Qt.Unchecked)
            item.setFlags(item.flags())
            self.annotationList.addItem(item)
            self.refreshAnnotationTitle(annotation)

    def removeAnnotation(self):
        if len(self.annotationList.selectedItems()) > 0:
            self.annotationManager.annotationRemoved.disconnect()
            trash = []
            for item in self.annotationList.selectedItems():
                index = self.annotationList.row(item)
                trash.append(self.annotationManager.annotations()[index])
            while trash:
                self.annotationManager.removeAnnotation(trash.pop())
            self.refreshAnnotations()
            self.annotationManager.annotationRemoved.connect(
                self.refreshAnnotations)

    def projectOpen(self):
        self.refreshAnnotations()

    def initGui(self):
        self.refreshAnnotations()
示例#7
0
class DataSelector(QDialog):
    #def select_data_to_add(viewer, feature_id, config_list):
    def __init__(self, viewer, feature_id, feature_name, config_list, config):
        QDialog.__init__(self)

        self.__viewer = viewer
        self.__feature_id = feature_id
        self.__feature_name = feature_name
        self.__config_list = config_list
        self.__config = config

        vbox = QVBoxLayout()

        btn = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        btn.accepted.connect(self.accept)
        btn.rejected.connect(self.reject)

        self.__list = QListWidget()
        self.__list.setSelectionMode(QAbstractItemView.ExtendedSelection)

        hbox = QHBoxLayout()
        lbl = QLabel("Sub selection")
        self.__sub_selection_combo = QComboBox()
        self.__sub_selection_combo.setEnabled(False)
        hbox.addWidget(lbl)
        hbox.addWidget(self.__sub_selection_combo)

        from_elsewhere_btn = QPushButton("Select another station")

        self.__title_label = QLabel()

        hbox2 = QHBoxLayout()
        hbox2.addWidget(self.__title_label)
        hbox2.addWidget(from_elsewhere_btn)

        vbox.addLayout(hbox2)
        vbox.addWidget(self.__list)
        vbox.addLayout(hbox)
        vbox.addWidget(btn)

        self.__list.itemSelectionChanged.connect(self.on_selection_changed)
        self.__sub_selection_combo.currentIndexChanged[str].connect(
            self.on_combo_changed)
        from_elsewhere_btn.clicked.connect(self.on_from_elsewhere_clicked)

        self.setLayout(vbox)
        self.setWindowTitle("Choose the data to add")
        self.resize(400, 200)

        self._populate_list()
        self.set_title(feature_name)

    def set_title(self, title):
        self.__title_label.setText("Station: {}".format(title))

    def _populate_list(self):
        self.__list.clear()
        for cfg in self.__config_list:
            if cfg["type"] in ("continuous", "instantaneous"):
                uri, provider = cfg["source"]
                # check number of features for this station
                data_l = QgsVectorLayer(uri, "data_layer", provider)
                req = QgsFeatureRequest()
                req.setFilterExpression("{}={}".format(
                    cfg["feature_ref_column"], self.__feature_id))
                if len(list(data_l.getFeatures(req))) == 0:
                    continue

                if cfg.get("feature_filter_type") == "unique_data_from_values":
                    # get unique filter values
                    cfg["filter_unique_values"] = sorted(
                        list(
                            set([
                                f[cfg["feature_filter_column"]]
                                for f in data_l.getFeatures(req)
                            ])))

            elif cfg["type"] == "image":
                if not self.__viewer.has_imagery_data(cfg, self.__feature_id):
                    continue

            item = QListWidgetItem(cfg["name"])
            item.setData(Qt.UserRole, cfg)
            self.__list.addItem(item)

    def accept(self):
        for item in self.__list.selectedItems():
            # now add the selected configuration
            cfg = item.data(Qt.UserRole)
            if cfg["type"] in ("continuous", "instantaneous"):
                uri, provider = cfg["source"]
                data_l = QgsVectorLayer(uri, "data_layer", provider)
                req = QgsFeatureRequest()
                filter_expr = "{}={}".format(cfg["feature_ref_column"],
                                             self.__feature_id)
                req.setFilterExpression(filter_expr)
                print("Layer", uri, "Filter", filter_expr)

                title = cfg["name"]

                if cfg["type"] == "instantaneous":
                    if "filter_value" in cfg:
                        filter_expr += " and {}='{}'".format(
                            cfg["feature_filter_column"], cfg["filter_value"])
                        title = cfg["filter_value"]
                    else:
                        title = cfg["name"]

                    f = None
                    for f in data_l.getFeatures(req):
                        pass
                    if f is None:
                        return
                    uom = cfg[
                        "uom"] if "uom" in cfg else "@" + cfg["uom_column"]
                    data = LayerData(data_l,
                                     cfg["event_column"],
                                     cfg["value_column"],
                                     filter_expression=filter_expr,
                                     uom=uom)
                    uom = data.uom()

                if cfg["type"] == "continuous":
                    uom = cfg["uom"]
                    fids = [f.id() for f in data_l.getFeatures(req)]
                    data = FeatureData(
                        data_l,
                        cfg["values_column"],
                        feature_ids=fids,
                        x_start_fieldname=cfg["start_measure_column"],
                        x_delta_fieldname=cfg["interval_column"])

                if hasattr(self.__viewer, "add_data_column"):
                    self.__viewer.add_data_column(
                        data, title, uom, station_name=self.__feature_name)
                if hasattr(self.__viewer, "add_data_row"):
                    self.__viewer.add_data_row(
                        data, title, uom, station_name=self.__feature_name)
            elif cfg["type"] == "image":
                self.__viewer.add_imagery_from_db(cfg, self.__feature_id)

        QDialog.accept(self)

    def on_selection_changed(self):
        self.__sub_selection_combo.clear()
        self.__sub_selection_combo.setEnabled(False)
        for item in self.__list.selectedItems():
            cfg = item.data(Qt.UserRole)
            if "filter_unique_values" in cfg:
                for v in cfg["filter_unique_values"]:
                    self.__sub_selection_combo.addItem(v)
            if "filter_value" in cfg:
                self.__sub_selection_combo.setCurrentIndex(
                    self.__sub_selection_combo.findText(cfg["filter_value"]))
            self.__sub_selection_combo.setEnabled(True)
            return

    def on_combo_changed(self, text):
        for item in self.__list.selectedItems():
            cfg = item.data(Qt.UserRole)
            cfg["filter_value"] = text
            item.setData(Qt.UserRole, cfg)
            return

    def on_from_elsewhere_clicked(self):
        layer_config = get_layer_config()
        from qgis.utils import iface
        if iface.activeLayer() is None:
            iface.messageBar().pushMessage(u"Please select an active layer",
                                           QgsMessageBar.CRITICAL)
            return
        uri, provider = iface.activeLayer().source(), iface.activeLayer(
        ).dataProvider().name()
        if (uri, provider) not in layer_config:
            iface.messageBar().pushMessage(u"Unconfigured layer",
                                           QgsMessageBar.CRITICAL)
            return

        config = layer_config[(uri, provider)]
        iface.messageBar().pushMessage(
            u"Please select a feature on the active layer")
        self.__tool = FeatureSelectionTool(iface.mapCanvas(),
                                           iface.activeLayer())
        iface.mapCanvas().setMapTool(self.__tool)
        self.__tool.featureSelected.connect(self.on_other_station_selected)

        self.setModal(False)
        self.setWindowState(Qt.WindowMinimized)

    def on_other_station_selected(self, selected):
        self.__feature_id = selected[0].id()
        self._populate_list()
        self.__feature_name = selected[0][self.__config["name_column"]]
        self.set_title(self.__feature_name)
        self.setModal(True)
        self.setWindowState(Qt.WindowActive)
class DistrictSelectionDialog(QDialog):
    """
    A dialog used for selecting from available districts
    :param district_registry: associated registry of available
    districts to show
    """

    def __init__(self, district_registry, parent=None):
        super().__init__(parent)

        self.district_registry = district_registry

        self.setWindowTitle(self.tr('Select New {}').format(
            district_registry.type_string_title()))
        layout = QVBoxLayout()
        self.recent_label = QLabel(self.tr('Recently used {}').format(
            district_registry.type_string_sentence_plural()))
        layout.addWidget(self.recent_label)

        self.recent_list = QListWidget()
        self.recent_list.setMaximumHeight(100)
        for d in district_registry.recent_districts_list():
            item = QListWidgetItem(self.district_registry.get_district_title(d))
            item.setData(Qt.UserRole, d)
            self.recent_list.addItem(item)
        layout.addWidget(self.recent_list, 0)

        self.available_label = QLabel(self.tr('Available {}').format(
            district_registry.type_string_sentence_plural()
        ))
        layout.addWidget(self.available_label)
        self.search = QgsFilterLineEdit()
        self.search.setShowSearchIcon(True)
        self.search.setPlaceholderText(self.tr('Search for {}').format(
            district_registry.type_string_sentence()))
        self.search.textChanged.connect(self.filter_changed)
        layout.addWidget(self.search)

        self.list = QListWidget()
        for title, code in district_registry.district_titles().items():
            item = QListWidgetItem(title)
            item.setData(Qt.UserRole, code)
            self.list.addItem(item)

        layout.addWidget(self.list, 10)

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

        if self.district_registry.flags() & DistrictRegistry.FLAG_ALLOWS_SPATIAL_SELECT:
            self.select_from_map_button = button_box.addButton(
                self.tr("Select from Map"), QDialogButtonBox.ActionRole)
            self.select_from_map_button.clicked.connect(self.pick_from_map)
        else:
            self.select_from_map_button = None
        self.chose_pick_from_map = False

        self.setLayout(layout)

        self.recent_list.itemSelectionChanged.connect(
            self.recent_list_item_selected)
        self.list.itemSelectionChanged.connect(
            self.list_item_selected)
        self.recent_list.itemDoubleClicked.connect(
            self.accept)
        self.list.itemDoubleClicked.connect(
            self.accept)

        # select most recently used district by default
        if self.recent_list.count() > 0:
            self.recent_list.item(0).setSelected(True)

    def recent_list_item_selected(self):
        """
        Handles a selection made in the recent district list
        """
        if self.recent_list.selectedItems():
            self.list.clearSelection()

    def list_item_selected(self):
        """
        Handles a selection made in the complete district list
        """
        if self.list.selectedItems():
            self.recent_list.clearSelection()

    def set_selected_district(self, district):
        """
        Sets the district selected in the dialog
        :param district: district to select
        """
        for i in range(self.list.count()):
            if self.list.item(i).data(Qt.UserRole) == district:
                self.list.item(i).setSelected(True)
                return

    def selected_district(self):
        """
        Returns the district selected in the dialog
        """
        if self.recent_list.selectedItems():
            return self.recent_list.selectedItems()[0].data(Qt.UserRole)
        elif self.list.selectedItems():
            return self.list.selectedItems()[0].data(Qt.UserRole)

        return None

    def accept(self):  # pylint: disable=missing-docstring
        self.district_registry.push_recent_district(self.selected_district())
        super().accept()

    def filter_changed(self, filter_text):
        """
        Handles search filter changes
        """
        for i in range(self.list.count()):
            item = self.list.item(i)
            item.setHidden(filter_text.upper() not in item.text().upper())

    def pick_from_map(self):
        """
        Triggered when a user selects the "Select from Map" option
        """
        self.chose_pick_from_map = True
        self.reject()
class CommitSelectDialog(QDialog):
    def __init__(self, repo, until=None, path=None, parent=None):
        super(CommitSelectDialog, self).__init__(parent or iface.mainWindow())
        self.repo = repo
        self.ref = None
        self.path = path
        self.until = until
        self.initGui()

    def initGui(self):
        layout = QVBoxLayout()
        buttonBox = QDialogButtonBox(QDialogButtonBox.Ok
                                     | QDialogButtonBox.Close)
        self.filterBox = QLineEdit()
        self.filterBox.setPlaceholderText(
            "[enter text or date in dd/mm/yyyy format to filter history]")
        self.filterBox.textChanged.connect(self.filterCommits)
        self.list = QListWidget()
        self.list.setAlternatingRowColors(True)
        self.list.setSelectionMode(QAbstractItemView.SingleSelection)
        self.list.setSelectionBehavior(QAbstractItemView.SelectRows)
        log = self.repo.log(until=self.until, path=self.path, limit=100)
        for commit in log:
            item = CommitListItem(commit)
            self.list.addItem(item)
        layout.addWidget(self.filterBox)
        layout.addWidget(self.list)
        layout.addWidget(buttonBox)
        self.setLayout(layout)

        buttonBox.accepted.connect(self.okPressed)
        buttonBox.rejected.connect(self.cancelPressed)

        self.resize(500, 400)
        self.setWindowTitle("Select commit")

    def filterCommits(self):
        text = self.filterBox.text().strip()
        try:
            t = datetime.datetime.strptime(text, "%d/%m/%Y")
            found = False
            for i in range(self.list.count()):
                item = self.list.item(i)
                if found:
                    item.setHidden(True)
                else:
                    delta = item.commit.committerdate - t
                    found = delta.days < 0
                    item.setHidden(not found)

        except ValueError as e:
            for i in range(self.list.count()):
                item = self.list.item(i)
                msg = item.commit.message
                item.setHidden(text != "" and text not in msg)

    def okPressed(self):
        selected = self.list.selectedItems()
        if len(selected) == 0:
            QMessageBox.warning(self, 'No commit selected',
                                "Select 1 commits from the commit list.",
                                QMessageBox.Ok)
        else:
            self.ref = selected[0].commit
            self.close()

    def cancelPressed(self):
        self.ref = None
        self.close()