Пример #1
0
    def set_widgets_into_composer(self, dialog, field, my_json=None):

        widget = None
        label = None
        if field['label']:
            label = QLabel()
            label.setObjectName('lbl_' + field['widgetname'])
            label.setText(field['label'].capitalize())
            if field['stylesheet'] is not None and 'label' in field['stylesheet']:
                label = set_setStyleSheet(field, label)
            if 'tooltip' in field:
                label.setToolTip(field['tooltip'])
            else:
                label.setToolTip(field['label'].capitalize())
        if field['widgettype'] == 'text' or field['widgettype'] == 'typeahead':
            widget = add_lineedit(field)
            widget = set_widget_size(widget, field)
            widget = set_data_type(field, widget)
            widget.editingFinished.connect(partial(get_values, dialog, widget, my_json))
            widget.returnPressed.connect(partial(get_values, dialog, widget, my_json))
        elif field['widgettype'] == 'combo':
            widget = add_combobox(field)
            widget = set_widget_size(widget, field)
            widget.currentIndexChanged.connect(partial(get_values, dialog, widget, my_json))
            if 'widgetfunction' in field:
                if field['widgetfunction'] is not None:
                    function_name = field['widgetfunction']
                    # Call def set_print(self, dialog, my_json): of the class ApiManageComposer
                    widget.currentIndexChanged.connect(partial(getattr(self, function_name), dialog, my_json))

        return label, widget
Пример #2
0
    def _set_widgets(self, dialog, db_return, field):

        widget = None
        label = None
        if field['label']:
            label = QLabel()
            label.setObjectName('lbl_' + field['widgetname'])
            label.setText(field['label'].capitalize())
            if 'stylesheet' in field and field[
                    'stylesheet'] is not None and 'label' in field[
                        'stylesheet']:
                label = tools_gw.set_stylesheet(field, label)
            if 'tooltip' in field:
                label.setToolTip(field['tooltip'])
            else:
                label.setToolTip(field['label'].capitalize())
        if field['widgettype'] == 'text' or field['widgettype'] == 'typeahead':
            completer = QCompleter()
            widget = tools_gw.add_lineedit(field)
            widget = tools_gw.set_widget_size(widget, field)
            widget = tools_gw.set_data_type(field, widget)
            if field['widgettype'] == 'typeahead':
                widget = tools_gw.set_typeahead(field, dialog, widget,
                                                completer)
        elif field['widgettype'] == 'combo':
            widget = tools_gw.add_combo(field)
            widget = tools_gw.set_widget_size(widget, field)
        elif field['widgettype'] == 'check':
            widget = tools_gw.add_checkbox(field)
        elif field['widgettype'] == 'datetime':
            widget = tools_gw.add_calendar(dialog, field)
        elif field['widgettype'] == 'button':
            widget = tools_gw.add_button(dialog, field)
            widget = tools_gw.set_widget_size(widget, field)
        elif field['widgettype'] == 'hyperlink':
            widget = tools_gw.add_hyperlink(field)
            widget = tools_gw.set_widget_size(widget, field)
        elif field['widgettype'] == 'hspacer':
            widget = tools_qt.add_horizontal_spacer()
        elif field['widgettype'] == 'vspacer':
            widget = tools_qt.add_verticalspacer()
        elif field['widgettype'] == 'textarea':
            widget = tools_gw.add_textarea(field)
        elif field['widgettype'] in 'spinbox':
            widget = tools_gw.add_spinbox(field)
        elif field['widgettype'] == 'tableview':
            widget = tools_gw.add_tableview(db_return, field)
            widget = tools_gw.add_tableview_header(widget, field)
            widget = tools_gw.fill_tableview_rows(widget, field)
            widget = tools_gw.set_tablemodel_config(dialog,
                                                    widget,
                                                    field['widgetname'],
                                                    sort_order=1,
                                                    isQStandardItemModel=True)
            tools_qt.set_tableview_config(widget)
        widget.setObjectName(widget.property('columnname'))

        return label, widget
    def set_widgets(self, dialog, db_return, field):

        widget = None
        label = None
        if field['label']:
            label = QLabel()
            label.setObjectName('lbl_' + field['widgetname'])
            label.setText(field['label'].capitalize())
            if field['stylesheet'] is not None and 'label' in field[
                    'stylesheet']:
                label = self.set_setStyleSheet(field, label)
            if 'tooltip' in field:
                label.setToolTip(field['tooltip'])
            else:
                label.setToolTip(field['label'].capitalize())
        if field['widgettype'] == 'text' or field['widgettype'] == 'typeahead':
            completer = QCompleter()
            widget = self.add_lineedit(field)
            widget = self.set_widget_size(widget, field)
            widget = self.set_data_type(field, widget)
            if field['widgettype'] == 'typeahead':
                widget = self.manage_lineedit(field, dialog, widget, completer)
        elif field['widgettype'] == 'combo':
            widget = self.add_combobox(field)
            widget = self.set_widget_size(widget, field)
        elif field['widgettype'] == 'check':
            widget = self.add_checkbox(field)
        elif field['widgettype'] == 'datetime':
            widget = self.add_calendar(dialog, field)
        elif field['widgettype'] == 'button':
            widget = self.add_button(dialog, field)
            widget = self.set_widget_size(widget, field)
        elif field['widgettype'] == 'hyperlink':
            widget = self.add_hyperlink(field)
            widget = self.set_widget_size(widget, field)
        elif field['widgettype'] == 'hspacer':
            widget = self.add_horizontal_spacer()
        elif field['widgettype'] == 'vspacer':
            widget = self.add_verical_spacer()
        elif field['widgettype'] == 'textarea':
            widget = self.add_textarea(field)
        elif field['widgettype'] in ('spinbox'):
            widget = self.add_spinbox(field)
        elif field['widgettype'] == 'tableview':
            widget = self.add_tableview(db_return, field)
            widget = self.set_headers(widget, field)
            widget = self.populate_table(widget, field)
            widget = self.set_columns_config(widget,
                                             field['widgetname'],
                                             sort_order=1,
                                             isQStandardItemModel=True)
            utils_giswater.set_qtv_config(widget)
        widget.setObjectName(widget.property('columnname'))

        return label, widget
Пример #4
0
class Ui_GHydraulicsResultDialog(object):
    def setupUi(self, GHydraulicsResultDialog):
        GHydraulicsResultDialog.setObjectName(_fromUtf8("GHydraulicsResultDialog"))
        GHydraulicsResultDialog.resize(640, 480)
        self.buttonBox = QDialogButtonBox(GHydraulicsResultDialog)
        self.buttonBox.setGeometry(QtCore.QRect(10, 440, 620, 32))
        self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
        self.buttonBox.setObjectName(_fromUtf8("buttonBox"))
        self.tabWidget = QTabWidget(GHydraulicsResultDialog)
        self.tabWidget.setGeometry(QtCore.QRect(10, 10, 620, 390))
        self.tabWidget.setObjectName(_fromUtf8("tabWidget"))
        self.tabOutput = QWidget()
        self.tabOutput.setObjectName(_fromUtf8("tabOutput"))
        self.textOutput = QTextBrowser(self.tabOutput)
        self.textOutput.setGeometry(QtCore.QRect(10, 10, 600, 340))
        sizePolicy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.textOutput.sizePolicy().hasHeightForWidth())
        self.textOutput.setSizePolicy(sizePolicy)
        self.textOutput.setObjectName(_fromUtf8("textOutput"))
        self.tabWidget.addTab(self.tabOutput, _fromUtf8(""))
        self.tabReport = QWidget()
        self.tabReport.setObjectName(_fromUtf8("tabReport"))
        self.textReport = QTextBrowser(self.tabReport)
        self.textReport.setGeometry(QtCore.QRect(10, 10, 600, 340))
        sizePolicy = QSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.textReport.sizePolicy().hasHeightForWidth())
        self.textReport.setSizePolicy(sizePolicy)
        self.textReport.setObjectName(_fromUtf8("textReport"))
        self.tabWidget.addTab(self.tabReport, _fromUtf8(""))
        self.comboStep = QComboBox(GHydraulicsResultDialog)
        self.comboStep.setGeometry(QtCore.QRect(150, 410, 80, 27))
        self.comboStep.setObjectName(_fromUtf8("comboStep"))
        self.labelStep = QLabel(GHydraulicsResultDialog)
        self.labelStep.setGeometry(QtCore.QRect(10, 415, 120, 17))
        self.labelStep.setObjectName(_fromUtf8("labelStep"))

        self.retranslateUi(GHydraulicsResultDialog)
        self.tabWidget.setCurrentIndex(0)
        
        #QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("accepted()")), GHydraulicsResultDialog.accept)
        self.buttonBox.accepted.connect(GHydraulicsResultDialog.accept)
        #QtCore.QObject.connect(self.buttonBox, QtCore.SIGNAL(_fromUtf8("rejected()")), GHydraulicsResultDialog.reject)
        self.buttonBox.rejected.connect(GHydraulicsResultDialog.reject)
        QtCore.QMetaObject.connectSlotsByName(GHydraulicsResultDialog)

    def retranslateUi(self, GHydraulicsResultDialog):
        GHydraulicsResultDialog.setWindowTitle(_translate("GHydraulicsResultDialog", "EPANET Results", None))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabOutput), _translate("GHydraulicsResultDialog", "EPANET Output", None))
        self.tabWidget.setTabText(self.tabWidget.indexOf(self.tabReport), _translate("GHydraulicsResultDialog", "Report", None))
        self.labelStep.setText(_translate("GHydraulicsResultDialog", "Load time step", None))
Пример #5
0
    def api_search(self):

        # Dialog
        self.dlg_search = ApiSearchUi()
        self.load_settings(self.dlg_search)
        self.dlg_search.lbl_msg.setStyleSheet("QLabel{color:red;}")
        self.dlg_search.lbl_msg.setVisible(False)

        # Make it dockable in left dock widget area
        self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dlg_search)

        body = self.create_body()
        function_name = "gw_api_getsearch"
        row = self.controller.execute_api_function(function_name, body)
        if not row:
            return False

        complet_list = [json.loads(row[0], object_pairs_hook=OrderedDict)]

        main_tab = self.dlg_search.findChild(QTabWidget, 'main_tab')
        first_tab = None
        self.lineedit_list = []
        for tab in complet_list[0]["form"]:
            if first_tab is None:
                first_tab = tab['tabName']
            tab_widget = QWidget(main_tab)
            tab_widget.setObjectName(tab['tabName'])
            main_tab.addTab(tab_widget, tab['tabtext'])
            gridlayout = QGridLayout()
            tab_widget.setLayout(gridlayout)
            x = 0

            for field in tab['fields']:
                label = QLabel()
                label.setObjectName('lbl_' + field['label'])
                label.setText(field['label'].capitalize())
                if field['widgettype'] == 'typeahead':
                    completer = QCompleter()
                    widget = self.add_lineedit(field)
                    widget = self.set_completer(widget, completer)
                    self.lineedit_list.append(widget)
                elif field['widgettype'] == 'combo':
                    widget = self.add_combobox(field)

                gridlayout.addWidget(label, x, 0)
                gridlayout.addWidget(widget, x, 1)
                x += 1

            vertical_spacer1 = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                           QSizePolicy.Expanding)
            gridlayout.addItem(vertical_spacer1)

        self.dlg_search.dlg_closed.connect(self.rubber_polygon.reset)
Пример #6
0
    def _set_widgets_into_composer(self, dialog, field, my_json=None):
        """
        functions called in -> widget.currentIndexChanged.connect(partial(getattr(self, function_name), dialog, my_json))
            def set_print(self, dialog, my_json)
        """

        widget = None
        label = None
        if field['label']:
            label = QLabel()
            label.setObjectName('lbl_' + field['widgetname'])
            label.setText(field['label'].capitalize())
            if 'stylesheet' in field and field[
                    'stylesheet'] is not None and 'label' in field[
                        'stylesheet']:
                label = tools_gw.set_stylesheet(field, label)
            if 'tooltip' in field:
                label.setToolTip(field['tooltip'])
            else:
                label.setToolTip(field['label'].capitalize())
        if field['widgettype'] == 'text' or field['widgettype'] == 'typeahead':
            widget = tools_gw.add_lineedit(field)
            widget = tools_gw.set_widget_size(widget, field)
            widget = tools_gw.set_data_type(field, widget)
            widget.editingFinished.connect(
                partial(tools_gw.get_values, dialog, widget, my_json))
            widget.returnPressed.connect(
                partial(tools_gw.get_values, dialog, widget, my_json))
        elif field['widgettype'] == 'combo':
            widget = tools_gw.add_combo(field)
            widget = tools_gw.set_widget_size(widget, field)
            widget.currentIndexChanged.connect(
                partial(tools_gw.get_values, dialog, widget, my_json))
            if 'widgetfunction' in field:
                if field['widgetfunction']['functionName'] is not None:
                    function_name = field['widgetfunction']['functionName']
                    widget.currentIndexChanged.connect(
                        partial(getattr(self, function_name), dialog, my_json))

        return label, widget
    def get_missing_layers(self, dialog, m_layers, critical_level):

        grl_critical = dialog.findChild(QGridLayout, "grl_critical")
        grl_others = dialog.findChild(QGridLayout, "grl_others")
        for pos, item in enumerate(m_layers):
            try:
                if not item:
                    continue
                widget = dialog.findChild(QCheckBox, f"{item['layer']}")
                # If it is the case that a layer is necessary for two functions,
                # and the widget has already been put in another iteration
                if widget:
                    continue
                label = QLabel()
                label.setObjectName(f"lbl_{item['layer']}")
                label.setText(
                    f'<b>{item["layer"]}</b><font size="2";> {item["qgis_message"]}</font>'
                )

                critical_level = int(item['criticity']) if int(
                    item['criticity']) > critical_level else critical_level
                widget = QCheckBox()
                widget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
                widget.setObjectName(f"{item['layer']}")

                if int(item['criticity']) == 3:
                    grl_critical.addWidget(label, pos, 0)
                    grl_critical.addWidget(widget, pos, 1)
                else:
                    grl_others.addWidget(label, pos, 0)
                    grl_others.addWidget(widget, pos, 1)
            except KeyError:
                description = "Key on returned json from ddbb is missed"
                self.controller.manage_exception(None, description)

        return critical_level
Пример #8
0
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()
Пример #9
0
    def api_catalog(self, previous_dialog, widget_name, geom_type,
                    feature_type):

        # Manage if geom_type is gully and set grate
        if geom_type == 'gully':
            geom_type == 'grate'

        form_name = 'upsert_catalog_' + geom_type + ''
        form = f'"formName":"{form_name}", "tabName":"data", "editable":"TRUE"'
        feature = f'"feature_type":"{feature_type}"'
        body = self.create_body(form, feature)
        sql = f"SELECT gw_fct_getcatalog({body})::text"
        row = self.controller.get_row(sql, log_sql=True)
        if not row:
            self.controller.show_message("NOT ROW FOR: " + sql, 2)
            return

        complet_list = [json.loads(row[0], object_pairs_hook=OrderedDict)]
        groupBox_1 = QGroupBox("Filter")
        self.filter_form = QGridLayout()

        self.dlg_catalog = InfoCatalogUi()
        self.load_settings(self.dlg_catalog)
        self.dlg_catalog.btn_cancel.clicked.connect(
            partial(self.close_dialog, self.dlg_catalog))
        self.dlg_catalog.btn_accept.clicked.connect(
            partial(self.fill_geomcat_id, previous_dialog, widget_name))

        main_layout = self.dlg_catalog.widget.findChild(
            QGridLayout, 'main_layout')
        result = complet_list[0]['body']['data']
        for field in result['fields']:
            label = QLabel()
            label.setObjectName('lbl_' + field['label'])
            label.setText(field['label'].capitalize())
            widget = None
            if field['widgettype'] == 'combo':
                widget = self.add_combobox(self.dlg_catalog, field)
            if field['layoutname'] == 'lyt_data_1':
                self.filter_form.addWidget(label, field['layoutorder'], 0)
                self.filter_form.addWidget(widget, field['layoutorder'], 1)

        groupBox_1.setLayout(self.filter_form)
        main_layout.addWidget(groupBox_1)
        verticalSpacer1 = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                      QSizePolicy.Expanding)
        main_layout.addItem(verticalSpacer1)

        matcat_id = self.dlg_catalog.findChild(QComboBox, 'matcat_id')

        pnom = None
        dnom = None
        if self.controller.get_project_type() == 'ws':
            pnom = self.dlg_catalog.findChild(QComboBox, 'pnom')
            dnom = self.dlg_catalog.findChild(QComboBox, 'dnom')
        elif self.controller.get_project_type() == 'ud':
            pnom = self.dlg_catalog.findChild(QComboBox, 'shape')
            dnom = self.dlg_catalog.findChild(QComboBox, 'geom1')

        id = self.dlg_catalog.findChild(QComboBox, 'id')

        # Call get_api_catalog first time
        self.get_api_catalog(matcat_id, pnom, dnom, id, feature_type,
                             geom_type)

        # Set Listeners
        matcat_id.currentIndexChanged.connect(
            partial(self.populate_pn_dn, matcat_id, pnom, dnom, feature_type,
                    geom_type))
        pnom.currentIndexChanged.connect(
            partial(self.get_api_catalog, matcat_id, pnom, dnom, id,
                    feature_type, geom_type))
        dnom.currentIndexChanged.connect(
            partial(self.get_api_catalog, matcat_id, pnom, dnom, id,
                    feature_type, geom_type))

        # Open form
        self.open_dialog(self.dlg_catalog, dlg_name='info_catalog')
Пример #10
0
    def api_search(self, dlg_mincut=None):
        form = ""
        if self.dlg_search is None and dlg_mincut is None:
            self.init_dialog()
        if dlg_mincut:
            self.dlg_search = dlg_mincut
            self.is_mincut = True
            form = f'"singleTab":"tab_address"'

        self.dlg_search.lbl_msg.setStyleSheet("QLabel{color:red;}")
        self.dlg_search.lbl_msg.setVisible(False)
        project_vars = global_vars.project_vars
        qgis_project_add_schema = project_vars['add_schema']
        self.controller.set_user_settings_value('open_search', 'true')

        if qgis_project_add_schema is None:
            body = create_body(form=form)
        else:
            extras = f'"addSchema":"{qgis_project_add_schema}"'
            body = create_body(form=form, extras=extras)
        function_name = "gw_fct_getsearch"
        complet_list = self.controller.get_json(function_name, body)
        if not complet_list:
            return False

        main_tab = self.dlg_search.findChild(QTabWidget, 'main_tab')
        if dlg_mincut and len(complet_list["form"]) == 1:
            main_tab = self.dlg_search.findChild(QTabWidget, 'main_tab')
            main_tab.setStyleSheet(
                "QTabBar::tab { background-color: transparent; text-align:left;"
                "border: 1px solid transparent;}"
                "QTabWidget::pane { background-color: #fcfcfc; border: 1 solid #dadada;}"
            )

        first_tab = None
        self.lineedit_list = []
        for tab in complet_list["form"]:
            if first_tab is None:
                first_tab = tab['tabName']
            tab_widget = QWidget(main_tab)
            tab_widget.setObjectName(tab['tabName'])
            main_tab.addTab(tab_widget, tab['tabLabel'])
            gridlayout = QGridLayout()
            tab_widget.setLayout(gridlayout)
            x = 0

            for field in tab['fields']:
                label = QLabel()
                label.setObjectName('lbl_' + field['label'])
                label.setText(field['label'].capitalize())
                widget = None
                if field['widgettype'] == 'typeahead':
                    completer = QCompleter()
                    widget = add_lineedit(field)
                    widget = self.set_typeahead_completer(widget, completer)
                    self.lineedit_list.append(widget)
                elif field['widgettype'] == 'combo':
                    widget = self.add_combobox(field)
                gridlayout.addWidget(label, x, 0)
                gridlayout.addWidget(widget, x, 1)
                x += 1

            vertical_spacer1 = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                           QSizePolicy.Expanding)
            gridlayout.addItem(vertical_spacer1)

        if self.is_mincut is False:
            self.controller.manage_translation('search', self.dlg_search)
Пример #11
0
    def _open_function(self, index):

        # this '0' refers to the index of the item in the selected row
        self.function_selected = index.sibling(index.row(), 0).data()

        # Control no clickable items
        if self.function_selected in self.no_clickable_items:
            return

        if 'reports' in index.parent().data().lower():

            # this '1' refers to the index of the item in the selected row
            function_name = index.sibling(index.row(), 0).data()
            self.function_selected = index.sibling(index.row(), 1).data()

            self.dlg_reports = GwToolboxReportsUi()
            tools_gw.load_settings(self.dlg_reports)

            # Set listeners
            self.dlg_reports.btn_export_path.clicked.connect(self._select_file_report)
            self.dlg_reports.btn_export.clicked.connect(partial(self._export_reports, self.dlg_reports, self.dlg_reports.tbl_reports, self.dlg_reports.txt_export_path))
            self.dlg_reports.rejected.connect(partial(tools_gw.close_dialog, self.dlg_reports))
            self.dlg_reports.btn_close.clicked.connect(self.dlg_reports.reject)

            extras = f'"filterText":null, "listId":"{self.function_selected}"'
            body = tools_gw.create_body(extras=extras)
            json_result = tools_gw.execute_procedure('gw_fct_getreport', body)
            if not json_result or json_result['status'] == 'Failed':
                return False

            layout = self.dlg_reports.findChild(QGridLayout, 'lyt_filters')

            order = 0

            for field in json_result['body']['data']['fields']:
                label = None
                widget = None

                if 'label' in field and field['label']:
                    label = QLabel()
                    label.setObjectName('lbl_' + field['widgetname'])
                    label.setText(field['label'].capitalize())
                    if 'stylesheet' in field and field['stylesheet'] is not None and 'label' in field['stylesheet']:
                        label = tools_gw.set_stylesheet(field, label)
                    if 'tooltip' in field:
                        label.setToolTip(field['tooltip'])
                    else:
                        label.setToolTip(field['label'].capitalize())

                if field['widgettype'] == 'text' or field['widgettype'] == 'typeahead':
                    completer = QCompleter()
                    widget = tools_gw.add_lineedit(field)
                    widget = tools_gw.set_widget_size(widget, field)
                    widget = tools_gw.set_data_type(field, widget)
                    widget.textChanged.connect(partial(self._update_tbl_reports))
                    if field['widgettype'] == 'typeahead':
                        widget = tools_gw.set_typeahead(field, self.dlg_reports, widget, completer)
                elif field['widgettype'] == 'combo':
                    widget = tools_gw.add_combo(field)
                    widget = tools_gw.set_widget_size(widget, field)
                    widget.currentIndexChanged.connect(partial(self._update_tbl_reports))
                elif field['widgettype'] == 'check':
                    widget = tools_gw.add_checkbox(field)
                    widget.stateChanged.connect(partial(self._update_tbl_reports))
                elif field['widgettype'] == 'datetime':
                    widget = tools_gw.add_calendar(self.dlg_reports, field)
                    widget.valueChanged.connect(partial(self._update_tbl_reports))
                elif field['widgettype'] == 'list':
                    numrows = len(field['value'])
                    numcols = len(field['value'][0])

                    self.dlg_reports.tbl_reports.setColumnCount(numcols)
                    self.dlg_reports.tbl_reports.setRowCount(numrows)

                    i = 0
                    dict_keys = {}
                    for key in field['value'][0].keys():
                        dict_keys[i] = f"{key}"
                        self.dlg_reports.tbl_reports.setHorizontalHeaderItem(i, QTableWidgetItem(f"{key}"))
                        i = i + 1

                    for row in range(numrows):
                        for column in range(numcols):
                            column_name = dict_keys[column]
                            self.dlg_reports.tbl_reports.setItem(row, column, QTableWidgetItem(f"{field['value'][row][column_name]}"))

                    continue

                order = order + 1

                if label:
                    layout.addWidget(label, 0, order)
                if widget:
                    layout.addWidget(widget, 1, order)

            self.dlg_reports.setWindowTitle(f"{function_name}")
            tools_gw.open_dialog(self.dlg_reports, dlg_name='reports')

        elif 'giswater' in index.parent().data().lower():

            self.dlg_functions = GwToolboxManagerUi()
            tools_gw.load_settings(self.dlg_functions)
            self.dlg_functions.progressBar.setVisible(False)
            self.dlg_functions.btn_cancel.hide()
            self.dlg_functions.btn_close.show()

            self.dlg_functions.btn_cancel.clicked.connect(self._cancel_task)
            self.dlg_functions.cmb_layers.currentIndexChanged.connect(partial(self.set_selected_layer, self.dlg_functions,
                                                                              self.dlg_functions.cmb_layers))
            self.dlg_functions.rbt_previous.toggled.connect(partial(self._rbt_state, self.dlg_functions.rbt_previous))
            self.dlg_functions.rbt_layer.toggled.connect(partial(self._rbt_state, self.dlg_functions.rbt_layer))
            self.dlg_functions.rbt_layer.setChecked(True)

            extras = f'"filterText":"{self.function_selected}"'
            extras += ', "isToolbox":true'
            body = tools_gw.create_body(extras=extras)
            json_result = tools_gw.execute_procedure('gw_fct_gettoolbox', body)
            if not json_result or json_result['status'] == 'Failed':
                return False
            status = self._populate_functions_dlg(self.dlg_functions, json_result['body']['data']['processes'])
            if not status:
                self.function_selected = index.sibling(index.row(), 1).data()
                message = "Function not found"
                tools_qgis.show_message(message, parameter=self.function_selected)
                return

            # Disable tab log
            tools_gw.disable_tab_log(self.dlg_functions)

            # Connect signals
            self.dlg_functions.mainTab.currentChanged.connect(partial(self._manage_btn_run))
            self.dlg_functions.btn_run.clicked.connect(partial(self._execute_function, self.function_selected,
                self.dlg_functions, self.dlg_functions.cmb_layers, json_result['body']['data']['processes']))
            self.dlg_functions.btn_close.clicked.connect(partial(tools_gw.close_dialog, self.dlg_functions))
            self.dlg_functions.rejected.connect(partial(tools_gw.close_dialog, self.dlg_functions))
            self.dlg_functions.btn_cancel.clicked.connect(partial(self.remove_layers))

            # Open form and set title
            self.dlg_functions.setWindowTitle(f"{self.function_selected}")
            tools_gw.open_dialog(self.dlg_functions, dlg_name='toolbox')
Пример #12
0
    def construct_form_param_system(self, row, pos):

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

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

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

                # Order Widgets
                if field['layout_id'] == 1:
                    self.order_widgets_system(field, self.basic_form, lbl,
                                              widget)
                elif field['layout_id'] == 2:
                    self.order_widgets_system(field, self.om_form, lbl, widget)
                elif field['layout_id'] == 3:
                    self.order_widgets_system(field, self.workcat_form, lbl,
                                              widget)
                elif field['layout_id'] == 4:
                    self.order_widgets_system(field, self.mapzones_form, lbl,
                                              widget)
                elif field['layout_id'] == 5:
                    self.order_widgets_system(field, self.cad_form, lbl,
                                              widget)
                elif field['layout_id'] == 6:
                    self.order_widgets_system(field, self.epa_form, lbl,
                                              widget)
                elif field['layout_id'] == 7:
                    self.order_widgets_system(field, self.masterplan_form, lbl,
                                              widget)
                elif field['layout_id'] == 8:
                    self.order_widgets_system(field, self.other_form, lbl,
                                              widget)
                elif field['layout_id'] == 9:
                    self.order_widgets_system(field, self.node_type_form, lbl,
                                              widget)
                elif field['layout_id'] == 10:
                    self.order_widgets_system(field, self.cat_form, lbl,
                                              widget)
                elif field['layout_id'] == 11:
                    self.order_widgets_system(field, self.utils_form, lbl,
                                              widget)
                elif field['layout_id'] == 12:
                    self.order_widgets_system(field, self.connec_form, lbl,
                                              widget)
                elif field['layout_id'] == 13:
                    self.order_widgets_system(field, self.topology_form, lbl,
                                              widget)
                elif field['layout_id'] == 14:
                    self.order_widgets_system(field, self.builder_form, lbl,
                                              widget)
                elif field['layout_id'] == 15:
                    self.order_widgets_system(field, self.review_form, lbl,
                                              widget)
                elif field['layout_id'] == 16:
                    self.order_widgets_system(field, self.analysis_form, lbl,
                                              widget)
                elif field['layout_id'] == 17:
                    self.order_widgets_system(field, self.system_form, lbl,
                                              widget)
Пример #13
0
    def construct_form_param_system(self, row, pos):

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

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

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

                # Order Widgets
                if 'layoutname' in field:
                    if field['layoutname'] == 'lyt_topology':
                        self.order_widgets_system(field, self.topology_form,
                                                  lbl, widget)
                    elif field['layoutname'] == 'lyt_builder':
                        self.order_widgets_system(field, self.builder_form,
                                                  lbl, widget)
                    elif field['layoutname'] == 'lyt_review':
                        self.order_widgets_system(field, self.review_form, lbl,
                                                  widget)
                    elif field['layoutname'] == 'lyt_analysis':
                        self.order_widgets_system(field, self.analysis_form,
                                                  lbl, widget)
                    elif field['layoutname'] == 'lyt_system':
                        self.order_widgets_system(field, self.system_form, lbl,
                                                  widget)
Пример #14
0
    def construct_form_param_user(self, row, pos):

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

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

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

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

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

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

                widget.setObjectName(field['widgetname'])

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

                if field['layoutname'] == 'lyt_basic':
                    self.order_widgets(field, self.basic_form, lbl, chk,
                                       widget)
                elif field['layoutname'] == 'lyt_om':
                    self.order_widgets(field, self.om_form, lbl, chk, widget)
                elif field['layoutname'] == 'lyt_inventory':
                    self.order_widgets(field, self.inventory_form, lbl, chk,
                                       widget)
                elif field['layoutname'] == 'lyt_mapzones':
                    self.order_widgets(field, self.mapzones_form, lbl, chk,
                                       widget)
                elif field['layoutname'] == 'lyt_edit':
                    self.order_widgets(field, self.cad_form, lbl, chk, widget)
                elif field['layoutname'] == 'lyt_epa':
                    self.order_widgets(field, self.epa_form, lbl, chk, widget)
                elif field['layoutname'] == 'lyt_masterplan':
                    self.order_widgets(field, self.masterplan_form, lbl, chk,
                                       widget)
                elif field['layoutname'] == 'lyt_other':
                    self.order_widgets(field, self.other_form, lbl, chk,
                                       widget)
                elif field['layoutname'] == 'lyt_node_vdef':
                    self.order_widgets(field, self.node_type_form, lbl, chk,
                                       widget)
                elif field['layoutname'] == 'lyt_arc_vdef':
                    self.order_widgets(field, self.cat_form, lbl, chk, widget)
                elif field['layoutname'] == 'lyt_utils_vdef':
                    self.order_widgets(field, self.utils_form, lbl, chk,
                                       widget)
                elif field['layoutname'] == 'lyt_connec_vdef':
                    self.order_widgets(field, self.connec_form, lbl, chk,
                                       widget)
                elif field['layoutname'] == 'lyt_gully_vdef':
                    self.order_widgets(field, self.gully_form, lbl, chk,
                                       widget)
                elif field['layoutname'] == 'lyt_fluid_type':
                    self.order_widgets(field, self.fluid_type_form, lbl, chk,
                                       widget)
                elif field['layoutname'] == 'lyt_location_type':
                    self.order_widgets(field, self.location_type_form, lbl,
                                       chk, widget)
                elif field['layoutname'] == 'lyt_category_type':
                    self.order_widgets(field, self.category_type_form, lbl,
                                       chk, widget)
                elif field['layoutname'] == 'lyt_function_type':
                    self.order_widgets(field, self.function_type_form, lbl,
                                       chk, widget)
                elif field['layoutname'] == 'lyt_addfields':
                    self.order_widgets(field, self.addfields_form, lbl, chk,
                                       widget)
Пример #15
0
class ReferencedTableEditor(QWidget):
    referenced_table_changed = pyqtSignal(str)

    changed = pyqtSignal()

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

        self._block_changed = False

        self.cbo_ref_table.setInsertPolicy(QComboBox.InsertAlphabetically)

        self.cbo_ref_table.currentIndexChanged[str].connect(self._on_ref_table_changed)

        self.cbo_source_field.currentTextChanged.connect(self._on_changed)
        self.cbo_ref_table.currentIndexChanged[str].connect(self._on_changed)
        self.cbo_referencing_col.currentTextChanged.connect(self._on_changed)

        # Tables that will be omitted from the referenced table list
        self._omit_ref_tables = []

        self._layout = None

    def _on_changed(self):
        if not self._block_changed:
            self.changed.emit()

    def add_omit_table(self, table):
        """
        Add a table name that will be omitted from the list of referenced
        tables.
        :param table: Table name that will be omitted
        :type table: str
        """
        if not table in self._omit_ref_tables:
            self._omit_ref_tables.append(table)

    def add_omit_tables(self, tables):
        """
        Add a list of tables that will be omitted from the list of referenced
        tables.
        :param tables: Table names to be omitted.
        :type tables: list
        """
        for t in tables:
            self.add_omit_table(t)

    @property
    def omit_tables(self):
        """
        :return: Returns a list of tables that are to be omitted from the
        list of referenced tables.
        """
        return self._omit_ref_tables

    def setupUi(self):
        self.setObjectName("ReferencedTableEditor")
        self.gridLayout = QGridLayout(self)
        self.gridLayout.setVerticalSpacing(10)
        self.gridLayout.setObjectName("gridLayout")
        self.label_2 = QLabel(self)
        self.label_2.setMaximumSize(QSize(100, 16777215))
        self.label_2.setObjectName("label_2")
        self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1)
        self.cbo_source_field = QComboBox(self)
        self.cbo_source_field.setMinimumSize(QSize(0, 30))
        self.cbo_source_field.setObjectName("cbo_source_field")
        self.gridLayout.addWidget(self.cbo_source_field, 2, 1, 1, 1)
        self.label = QLabel(self)
        self.label.setObjectName("label")
        self.gridLayout.addWidget(self.label, 2, 0, 1, 1)
        self.label_3 = QLabel(self)
        self.label_3.setObjectName("label_3")
        self.gridLayout.addWidget(self.label_3, 3, 0, 1, 1)
        self.cbo_referencing_col = QComboBox(self)
        self.cbo_referencing_col.setMinimumSize(QSize(0, 30))
        self.cbo_referencing_col.setObjectName("cbo_referencing_col")
        self.gridLayout.addWidget(self.cbo_referencing_col, 3, 1, 1, 1)
        self.cbo_ref_table = QComboBox(self)
        self.cbo_ref_table.setMinimumSize(QSize(0, 30))
        self.cbo_ref_table.setObjectName("cbo_ref_table")
        self.gridLayout.addWidget(self.cbo_ref_table, 1, 1, 1, 1)

        self.label_2.setText(QApplication.translate("ReferencedTableEditor",
                                                    "References"))
        self.label.setText(QApplication.translate("ReferencedTableEditor",
                                                  "Data source field"))
        self.label_3.setText(QApplication.translate("ReferencedTableEditor",
                                                    "Referencing"))

        self._current_profile = current_profile()
        self._current_profile_tables = []

        if self._current_profile is not None:
            self._current_profile_tables =self._current_profile.user_table_names()

        # Connect signals
        QMetaObject.connectSlotsByName(self)
        self.cbo_ref_table.currentIndexChanged[str].connect(self._load_source_table_fields)

    def set_layout(self, layout):
        self._layout = layout
        self._layout.variablesChanged.connect(self.layout_variables_changed)

    def layout_variables_changed(self):
        """
        When the user changes the data source then update the fields.
        """
        data_source_name = LayoutUtils.get_stdm_data_source_for_layout(self._layout)
        self.load_data_source_fields(data_source_name)

    def on_data_source_changed(self, data_source_name):
        """
        Loads data source fields for the given data source name.
        """
        self.load_data_source_fields(data_source_name)

    def _on_ref_table_changed(self, table):
        """
        Raise signal when the referenced table changes.
        :param table: Selected table name.
        :type table: str
        """
        self.referenced_table_changed.emit(table)

    def properties(self):
        """
        :returns: Returns the user-defined mapping of linked table and column
        pairings.
        :rtype: LinkedTableProps
        """
        l_table = self.cbo_ref_table.currentText()
        s_field = self.cbo_source_field.currentText()
        l_field = self.cbo_referencing_col.currentText()

        return LinkedTableProps(linked_table=l_table,
                                source_field=s_field,
                                linked_field=l_field)

    def set_properties(self, table_props):
        """
        Sets the combo selection based on the text in the linked table
        object properties.
        :param table_props: Object containing the linked table information.
        :type table_props: LinkedTableProps
        """
        self._block_changed = True
        GuiUtils.set_combo_current_index_by_text(self.cbo_ref_table, table_props.linked_table)
        GuiUtils.set_combo_current_index_by_text(self.cbo_source_field, table_props.source_field)
        GuiUtils.set_combo_current_index_by_text(self.cbo_referencing_col, table_props.linked_field)
        self._block_changed = False

    def load_data_source_fields(self, data_source_name):
        """
        Load fields/columns of the given data source.
        """
        if data_source_name == "":
            self.clear()

            return

        columns_names = table_column_names(data_source_name)

        if len(columns_names) == 0:
            return

        self.cbo_source_field.clear()
        self.cbo_source_field.addItem("")
        self.cbo_source_field.addItems(columns_names)

    def clear(self):
        """
        Resets combo box selections.
        """
        self._reset_combo_index(self.cbo_ref_table)
        self._reset_combo_index(self.cbo_referencing_col)
        self._reset_combo_index(self.cbo_source_field)

    def _reset_combo_index(self, combo):
        if combo.count > 0:
            combo.setCurrentIndex(0)

    def reset_referenced_table(self):
        self._reset_combo_index(self.cbo_ref_table)

    def load_link_tables(self, reg_exp=None, source=TABLES | VIEWS):
        self.cbo_ref_table.clear()
        self.cbo_ref_table.addItem("")

        ref_tables = []
        source_tables = []
        # Table source
        if (TABLES & source) == TABLES:
            ref_tables.extend(pg_tables(exclude_lookups=True))

            for t in ref_tables:
                # Ensure we are dealing with tables in the current profile
                if not t in self._current_profile_tables:
                    continue

                # Assert if the table is in the list of omitted tables
                if t in self._omit_ref_tables:
                    continue

                if not reg_exp is None:
                    if reg_exp.indexIn(t) >= 0:
                        source_tables.append(t)
                else:
                    source_tables.append(t)

        # View source
        if (VIEWS & source) == VIEWS:
            profile_user_views = profile_and_user_views(self._current_profile)
            source_tables = source_tables + profile_user_views

        self.cbo_ref_table.addItems(source_tables)

    def _load_source_table_fields(self, sel):
        self.cbo_referencing_col.clear()
        data_source_index = self.cbo_source_field.currentIndex()
        # self.on_data_source_changed(
        #     self.cbo_source_field.itemData(data_source_index)
        # )

        if not sel:
            return

        columns_names = table_column_names(sel)

        self.cbo_referencing_col.clear()
        self.cbo_referencing_col.addItem("")
        self.cbo_referencing_col.addItems(columns_names)
Пример #16
0
    def get_selector(self,
                     dialog,
                     selector_type,
                     filter=False,
                     widget=None,
                     text_filter=None,
                     current_tab=None):
        """
        Ask to DB for selectors and make dialog
            :param dialog: Is a standard dialog, from file selector.ui, where put widgets
            :param selector_type: List of selectors to ask DB ['exploitation', 'state', ...]
        """

        index = 0
        main_tab = dialog.findChild(QTabWidget, 'main_tab')

        # Set filter
        if filter is not False:
            main_tab = dialog.findChild(QTabWidget, 'main_tab')
            text_filter = tools_qt.get_text(dialog, widget)
            if text_filter in ('null', None):
                text_filter = ''

            # Set current_tab
            index = dialog.main_tab.currentIndex()
            current_tab = dialog.main_tab.widget(index).objectName()

        # Profilactic control of nones
        if text_filter is None:
            text_filter = ''
        # Built querytext
        form = f'"currentTab":"{current_tab}"'
        extras = f'"selectorType":{selector_type}, "filterText":"{text_filter}"'
        body = tools_gw.create_body(form=form, extras=extras)
        json_result = tools_gw.execute_procedure('gw_fct_getselectors', body)

        if not json_result or json_result['status'] == 'Failed':
            return False

        # Get styles
        stylesheet = json_result['body']['form'][
            'style'] if 'style' in json_result['body']['form'] else None
        color_rows = False
        if stylesheet:
            # Color selectors zebra-styled
            if 'rowsColor' in stylesheet and stylesheet[
                    'rowsColor'] is not None:
                color_rows = tools_os.set_boolean(stylesheet['rowsColor'],
                                                  False)

        for form_tab in json_result['body']['form']['formTabs']:

            if filter and form_tab['tabName'] != str(current_tab):
                continue

            selection_mode = form_tab['selectionMode']

            # Create one tab for each form_tab and add to QTabWidget
            tab_widget = QWidget(main_tab)
            tab_widget.setObjectName(form_tab['tabName'])
            tab_widget.setProperty('selector_type', form_tab['selectorType'])
            if filter:
                main_tab.removeTab(index)
                main_tab.insertTab(index, tab_widget, form_tab['tabLabel'])
            else:
                main_tab.addTab(tab_widget, form_tab['tabLabel'])
            if 'typeaheadForced' in form_tab and form_tab[
                    'typeaheadForced'] is not None:
                tab_widget.setProperty('typeahead_forced',
                                       form_tab['typeaheadForced'])

            # Create a new QGridLayout and put it into tab
            gridlayout = QGridLayout()
            gridlayout.setObjectName("lyt" + form_tab['tabName'])
            tab_widget.setLayout(gridlayout)
            field = {}
            i = 0

            if 'typeaheadFilter' in form_tab:
                label = QLabel()
                label.setObjectName('lbl_filter')
                label.setText('Filter:')
                if tools_qt.get_widget(
                        dialog,
                        'txt_filter_' + str(form_tab['tabName'])) is None:
                    widget = QLineEdit()
                    widget.setObjectName('txt_filter_' +
                                         str(form_tab['tabName']))
                    widget.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
                    widget.textChanged.connect(
                        partial(self.get_selector,
                                dialog,
                                selector_type,
                                filter=True,
                                widget=widget,
                                current_tab=current_tab))
                    widget.setLayoutDirection(Qt.RightToLeft)

                else:
                    widget = tools_qt.get_widget(
                        dialog, 'txt_filter_' + str(form_tab['tabName']))

                field['layoutname'] = gridlayout.objectName()
                field['layoutorder'] = i
                i = i + 1
                gridlayout.addWidget(label, int(field['layoutorder']), 0)
                gridlayout.addWidget(widget, int(field['layoutorder']), 2)
                widget.setFocus()

            if 'manageAll' in form_tab:
                if (form_tab['manageAll']).lower() == 'true':
                    if tools_qt.get_widget(
                            dialog, f"chk_all_{form_tab['tabName']}") is None:
                        widget = QCheckBox()
                        widget.setObjectName('chk_all_' +
                                             str(form_tab['tabName']))
                        widget.stateChanged.connect(
                            partial(self._manage_all, dialog, widget))
                        widget.setLayoutDirection(Qt.LeftToRight)
                    else:
                        widget = tools_qt.get_widget(
                            dialog, f"chk_all_{form_tab['tabName']}")
                    widget.setText('Check all')
                    field['layoutname'] = gridlayout.objectName()
                    field['layoutorder'] = i
                    i = i + 1
                    gridlayout.addWidget(widget, int(field['layoutorder']), 0,
                                         1, -1)

            for order, field in enumerate(form_tab['fields']):
                try:
                    # Create checkbox
                    widget = tools_gw.add_checkbox(field)
                    widget.setText(field['label'])
                    widget.stateChanged.connect(
                        partial(self._set_selection_mode, dialog, widget,
                                selection_mode))
                    widget.setLayoutDirection(Qt.LeftToRight)

                    # Set background color every other item (if enabled)
                    if color_rows and order % 2 == 0:
                        widget.setStyleSheet(f"background-color: #E9E7E3")

                    # Add widget to layout
                    field['layoutname'] = gridlayout.objectName()
                    field['layoutorder'] = order + i + 1
                    gridlayout.addWidget(widget, int(field['layoutorder']), 0,
                                         1, -1)
                except Exception:
                    msg = f"key 'comboIds' or/and comboNames not found WHERE columname='{field['columnname']}' AND " \
                          f"widgetname='{field['widgetname']}'"
                    tools_qgis.show_message(msg, 2)

            vertical_spacer1 = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                           QSizePolicy.Expanding)
            gridlayout.addItem(vertical_spacer1)

        # Set last tab used by user as current tab
        tabname = json_result['body']['form']['currentTab']
        tab = main_tab.findChild(QWidget, tabname)

        if tab:
            main_tab.setCurrentWidget(tab)
Пример #17
0
def buildfromauto(formconfig, base) -> QWidget:
    """
    Build a auto form from the form config given.
    :param formconfig: The form config containing the information about the widgets to create.
    :param base: The base widget to create the new widgets in.
    :return: The base widget with the added widgets created inside the layout.
    """
    widgetsconfig = copy.deepcopy(formconfig['widgets'])

    try:
        widgetsconfig = base.get_widgets(widgetsconfig)
    except AttributeError:
        pass

    newstyle = formconfig.get("newstyle", False)
    hassections = any(config['widget'] == "Section"
                      for config in widgetsconfig)

    def make_layout():
        """
        Create the inner layout for the widget. For new style forms this is a vbox layout so everything
        is stacked on top of each other in a simple list.
        :return:
        """
        if newstyle:
            return QVBoxLayout()
        else:
            layout = QFormLayout()
            layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow)
            return layout

    def make_tab(tabwidget, name):
        """
        Create a table in the given tab widget.
        :param tabwidget: The tab widget to create the tab in.
        :param name: The name of the new tab to create.
        :return: The new widget inside the tab and the widgets inner layout.
        """
        widget = QWidget()
        widget.setLayout(make_layout())
        tabwidget.addTab(widget, name)
        return widget, widget.layout()

    if hassections:
        outwidget = QTabWidget(base)
        outlayout = None
        base.setLayout(QVBoxLayout())
        base.layout().setContentsMargins(0, 0, 0, 0)
        base.layout().addWidget(outwidget)
    else:
        outwidget = base
        outlayout = make_layout()
        outwidget.setLayout(outlayout)

    # Add the geometry editor widget of that is set in the config.
    # This is a hidden option so isn't exposed in config manager yet
    if roam.config.settings.get("form_geom_edit", False):
        geomwidget = GeomWidget()
        geomwidget.setObjectName("__geomwidget")
        outlayout.addRow("Geometry", geomwidget)

    insection = False
    for config in widgetsconfig:
        widgettype = config['widget']

        # Make the first tab if one isn't defined already and we have other sections in the config
        if not insection and hassections and not widgettype == "Section":
            name = formconfig['label']
            tabwidget, outlayout = make_tab(outwidget, name)
            insection = True

        if widgettype == 'Section':
            # Add a spacer to the last widget
            if outlayout:
                spacer = QWidget()
                spacer.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
                outlayout.addItem(QSpacerItem(10, 500))
                outlayout.addWidget(spacer)

            name = config['name']
            tabwidget, outlayout = make_tab(outwidget, name)
            insection = True
            continue

        field = config['field']
        name = config.get('name', field)
        if not field:
            utils.warning("Field can't be null for {}".format(name))
            utils.warning("Skipping widget")
            continue

        label = QLabel(name)
        label.setObjectName(field + "_label")
        labelwidget = QWidget()
        labelwidget.setLayout(QBoxLayout(QBoxLayout.LeftToRight))
        labelwidget.layout().addWidget(label)
        labelwidget.layout().setContentsMargins(0, 0, 0, 0)

        widget = roam.editorwidgets.core.createwidget(widgettype, parent=base)
        widget.setObjectName(field)
        layoutwidget = QWidget()
        layoutwidget.setLayout(QBoxLayout(QBoxLayout.LeftToRight))
        layoutwidget.layout().addWidget(widget)
        layoutwidget.layout().setContentsMargins(0, 0, 0, 10)

        if config.get('rememberlastvalue', False):
            savebutton = QToolButton()
            savebutton.setObjectName('{}_save'.format(field))
            if newstyle:
                spacer = QWidget()
                spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
                labelwidget.layout().addWidget(spacer)
                labelwidget.layout().addWidget(savebutton)
            else:
                layoutwidget.layout().addWidget(savebutton)

        if newstyle:
            outlayout.addWidget(labelwidget)
            outlayout.addWidget(layoutwidget)
        else:
            outlayout.addRow(labelwidget, layoutwidget)

    spacer = QWidget()
    spacer.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
    outlayout.addWidget(spacer)
    if not hassections:
        outlayout.addItem(QSpacerItem(10, 500))
    return base
Пример #18
0
    def open_catalog(self, previous_dialog, widget_name, feature_type,
                     child_type):
        """ Main function of catalog """

        # Manage if feature_type is gully and set grate
        if feature_type == 'gully':
            feature_type = 'grate'

        form_name = 'upsert_catalog_' + feature_type + ''
        form = f'"formName":"{form_name}", "tabName":"data", "editable":"TRUE"'
        feature = f'"feature_type":"{child_type}"'
        body = tools_gw.create_body(form, feature)
        json_result = tools_gw.execute_procedure('gw_fct_getcatalog',
                                                 body,
                                                 log_sql=True)
        if json_result is None:
            return

        group_box_1 = QGroupBox("Filter")
        self.filter_form = QGridLayout()

        self.dlg_catalog = GwInfoCatalogUi()
        tools_gw.load_settings(self.dlg_catalog)
        self.dlg_catalog.btn_cancel.clicked.connect(
            partial(tools_gw.close_dialog, self.dlg_catalog))
        self.dlg_catalog.btn_accept.clicked.connect(
            partial(self._fill_geomcat_id, previous_dialog, widget_name))

        main_layout = self.dlg_catalog.widget.findChild(
            QGridLayout, 'main_layout')
        result = json_result['body']['data']
        for field in result['fields']:
            label = QLabel()
            label.setObjectName('lbl_' + field['label'])
            label.setText(field['label'].capitalize())
            widget = None
            if field['widgettype'] == 'combo':
                widget = self._add_combobox(field)
            if field['layoutname'] == 'lyt_data_1':
                self.filter_form.addWidget(label, field['layoutorder'], 0)
                self.filter_form.addWidget(widget, field['layoutorder'], 1)

        group_box_1.setLayout(self.filter_form)
        main_layout.addWidget(group_box_1)
        vertical_spacer1 = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                       QSizePolicy.Expanding)
        main_layout.addItem(vertical_spacer1)

        matcat_id = self.dlg_catalog.findChild(QComboBox, 'matcat_id')

        pnom = None
        dnom = None
        if tools_gw.get_project_type() == 'ws':
            pnom = self.dlg_catalog.findChild(QComboBox, 'pnom')
            dnom = self.dlg_catalog.findChild(QComboBox, 'dnom')
        elif tools_gw.get_project_type() == 'ud':
            pnom = self.dlg_catalog.findChild(QComboBox, 'shape')
            dnom = self.dlg_catalog.findChild(QComboBox, 'geom1')

        id = self.dlg_catalog.findChild(QComboBox, 'id')

        # Call _get_catalog first time
        self._get_catalog(matcat_id, pnom, dnom, id, feature_type, child_type)

        # Set Listeners
        if matcat_id:
            matcat_id.currentIndexChanged.connect(
                partial(self._populate_pn_dn, matcat_id, pnom, dnom,
                        feature_type, child_type))
        if pnom:
            pnom.currentIndexChanged.connect(
                partial(self._get_catalog, matcat_id, pnom, dnom, id,
                        feature_type, child_type))
        if dnom:
            dnom.currentIndexChanged.connect(
                partial(self._get_catalog, matcat_id, pnom, dnom, id,
                        feature_type, child_type))

        # Set shortcut keys
        self.dlg_catalog.key_escape.connect(
            partial(tools_gw.close_dialog, self.dlg_catalog))

        # Open form
        tools_gw.open_dialog(self.dlg_catalog, dlg_name='info_catalog')
Пример #19
0
    def _build_dialog_options(self, row, tab):

        self.tab = tab

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

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

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

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

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

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

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

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

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

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

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

                    if widget is None:
                        widget = self.chk

                    self._order_widgets(field, lbl, widget)

            except Exception as e:
                msg = f"{type(e).__name__} {e}. widgetname='{field['widgetname']}' AND widgettype='{field['widgettype']}'"
                tools_qgis.show_message(msg, 2)
Пример #20
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))
Пример #21
0
class Ui_form1(object):
    def setupUi(self, form1):
        form1.setObjectName(_fromUtf8("form1"))
        form1.resize(400, 253)
        form1.setFocusPolicy(QtCore.Qt.TabFocus)
        form1.setWindowTitle(_fromUtf8("Kuwahara filter"))
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(_fromUtf8(":/qgis.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        form1.setWindowIcon(icon)
        self.label = QLabel(form1)
        self.label.setGeometry(QtCore.QRect(21, 10, 111, 20))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.label.setFont(font)
        self.label.setToolTip(_fromUtf8(""))
        self.label.setObjectName(_fromUtf8("label"))
        self.outputb = QPushButton(form1)
        self.outputb.setGeometry(QtCore.QRect(320, 47, 31, 23))
        self.outputb.setObjectName(_fromUtf8("outputb"))
        self.label_2 = QLabel(form1)
        self.label_2.setGeometry(QtCore.QRect(22, 49, 101, 20))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.label_2.setFont(font)
        self.label_2.setToolTip(_fromUtf8(""))
        self.label_2.setObjectName(_fromUtf8("label_2"))
        self.progressBar = QProgressBar(form1)
        self.progressBar.setGeometry(QtCore.QRect(19, 220, 361, 23))
        self.progressBar.setProperty(_fromUtf8("value"), 24)
        self.progressBar.setObjectName(_fromUtf8("progressBar"))
        self.label_3 = QLabel(form1)
        self.label_3.setGeometry(QtCore.QRect(22, 88, 131, 20))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.label_3.setFont(font)
        self.label_3.setObjectName(_fromUtf8("label_3"))
        self.label_4 = QLabel(form1)
        self.label_4.setGeometry(QtCore.QRect(21, 125, 181, 20))
        font = QtGui.QFont()
        font.setPointSize(10)
        self.label_4.setFont(font)
        self.label_4.setObjectName(_fromUtf8("label_4"))
        self.run = QPushButton(form1)
        self.run.setGeometry(QtCore.QRect(139, 185, 101, 23))
        self.run.setObjectName(_fromUtf8("run"))
        self.inputbox = QgsMapLayerComboBox(form1)
        self.inputbox.setGeometry(QtCore.QRect(141, 10, 170, 22))
        self.inputbox.setObjectName(_fromUtf8("input"))
        self.output = QLineEdit(form1)
        self.output.setGeometry(QtCore.QRect(149, 45, 160, 28))
        self.output.setAlignment(QtCore.Qt.AlignLeading|QtCore.Qt.AlignLeft|QtCore.Qt.AlignVCenter)
        self.output.setObjectName(_fromUtf8("output"))
        self.refb = QLineEdit(form1)
        self.refb.setGeometry(QtCore.QRect(149, 82, 160, 28))
        self.refb.setObjectName(_fromUtf8("refb"))
        self.mem = QLineEdit(form1)
        self.mem.setGeometry(QtCore.QRect(208, 120, 101, 28))
        self.mem.setObjectName(_fromUtf8("mem"))
        self.addout = QCheckBox(form1)
        self.addout.setGeometry(QtCore.QRect(100, 158, 171, 17))
        self.addout.setChecked(True)
        self.addout.setObjectName(_fromUtf8("checkBox"))
        self.inputb = QPushButton(form1)
        self.inputb.setGeometry(QtCore.QRect(320, 10, 31, 23))
        self.inputb.setObjectName(_fromUtf8("inputb"))
        self.retranslateUi(form1)
        self.setWindowFlags(QtCore.Qt.WindowFlags(QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowMaximizeButtonHint | QtCore.Qt.WindowCloseButtonHint))
        QtCore.QMetaObject.connectSlotsByName(form1)
    def retranslateUi(self, form1):
        self.label.setText(QtCore.QCoreApplication.translate("form1", "Input raster"))
        self.outputb.setText("...")
        self.label_2.setText(QApplication.translate("form1", "Output raster"))
        self.label_3.setToolTip(QApplication.translate("form1", "Reference band from which variances will be calculated to choose subwindow mean."))
        self.label_3.setText(QApplication.translate("form1", "Reference band"))
        self.label_4.setToolTip(QApplication.translate("form1", "Maximum memory usage in megabytes (it is an approximated value, since algorithm will only choose how many lines will be read at once)."))
        self.label_4.setText(QApplication.translate("form1", "Max memory usage (MB)"))
        self.run.setText(QApplication.translate("form1", "Run"))
        self.output.setPlaceholderText(QApplication.translate("form1", "<temporary file>"))
        self.refb.setToolTip(QApplication.translate("form1", "Reference band from which variances will be calculated to choose subwindow mean."))
        self.refb.setText("1")
        self.mem.setToolTip(QApplication.translate("form1", "Maximum memory usage in MeB (it is an approximated value, since algorithm will only choose how many lines will be read at once)."))
        self.mem.setText("100")
        self.addout.setText(QApplication.translate("form1", "Add results to project"))
        self.inputb.setText("...")
Пример #22
0
class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(
            QtCore.QSize(QtCore.QRect(0, 0, 440, 660).size()).expandedTo(
                Dialog.minimumSizeHint()))

        self.gridlayout = QGridLayout(Dialog)
        self.gridlayout.setObjectName("gridlayout")

        font = QFont()
        font.setPointSize(15)
        font.setWeight(50)
        font.setBold(True)

        self.label_2 = QLabel(Dialog)
        self.label_2.setFont(font)
        self.label_2.setTextFormat(QtCore.Qt.RichText)
        self.label_2.setObjectName("label_2")
        self.gridlayout.addWidget(self.label_2, 1, 1, 1, 2)

        self.textEdit = QTextEdit(Dialog)

        palette = QPalette()

        brush = QBrush(QColor(0, 0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Base, brush)

        brush = QBrush(QColor(0, 0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Base, brush)

        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Base, brush)
        self.textEdit.setPalette(palette)
        self.textEdit.setAutoFillBackground(True)
        self.textEdit.width = 320
        self.textEdit.height = 360
        self.textEdit.setFrameShape(QFrame.NoFrame)
        self.textEdit.setFrameShadow(QFrame.Plain)
        self.textEdit.setReadOnly(True)
        self.textEdit.setObjectName("textEdit")
        self.textEdit.setTextInteractionFlags(QtCore.Qt.TextBrowserInteraction)

        self.gridlayout.addWidget(self.textEdit, 2, 1, 5, 2)

        self.pushButton = QPushButton(Dialog)
        self.pushButton.setObjectName("pushButton")
        self.gridlayout.addWidget(self.pushButton, 4, 2, 1, 1)

        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.gridlayout.addItem(spacerItem, 3, 1, 1, 1)

        self.retranslateUi(Dialog)
        self.pushButton.clicked.connect(Dialog.reject)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(
            QApplication.translate("Dialog", "GroupPointsWithinDistance",
                                   None))
        self.label_2.setText(
            QApplication.translate("Dialog", "GroupPointsWithinDistance 0.2",
                                   None))
        self.textEdit.setHtml(
            QApplication.translate(
                "Dialog",
                "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n"
                "p, li { white-space: pre-wrap; }\n"
                "</style></head><body style=\" font-family:\'Sans Serif\'; font-size:8pt; font-weight:400; font-style:normal;\">\n"
                "<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'MS Shell Dlg 2\'; font-size:8pt;\"><span style=\" font-weight:600;\">"
                " GroupPointsWithinDistance 0.2 :</span>"
                "  A little QGIS plugin to find and group/aggregate points of a points' layer if they are at a given distance of one another.</b>\n"
                +
                "                                                                                                                                                                                           \n"
                +
                " <br><b>WARNING:</b><br><b> Work with projected datas only, in other words do not use geographical (long-lat type) reference systems !</b>\n "
                +
                "                                                                                                                                             \n"
                + "             \n" +
                "This plugin is meant to deal with points datas (not multipoints, convert first to points) (for instance faunistic or floristic observations), nearby from one another, that the user wants to be regrouped/aggregated as a station.\n"
                + "\n" +
                "                                                                                                                                                                                                                    \n"
                +
                "The user should appreciate and cheack which distance to use, and - may be - keep the distance chosen as small as possible in order to avoid '"
                'chains effect'
                "' and producing too widespread groups .\n" +
                "                                                                                                                                          \n"
                + "The plugin produces a layer of point called '"
                'input_layer_name_aggregated_with_Distance'
                "' with 3 mores attributes:                                                          \n"
                +
                "                                                                                                                                                                                                                    \n"
                +
                " - Point_id: the point id,                                                                                                                                                              \n"
                +
                "                                                                                                                                                                                                                    \n"
                + " - NumAggreg: the '"
                'aggregates id number'
                "'                                                                                                                                                              \n"
                +
                "                                                                                                                                                                                                                    \n"
                +
                " - Nb_Pts: the number of regrouped points,                                              \n "
                + "\n" +
                "                                                                                                                                                                                                                    \n"
                +
                " - List_Pts: the list of the points ids in the aggregate.                                                                                                                     \n"
                + "\n" +
                "                                                                                                                                          \n"
                +
                "                                                                                                                                                          \n"
                + "\n" +
                " The plugin also produce a line layer, with not all lines connecting points of a same aggregate but showing only the very one of the connections that were made to link the points as part of a same aggregate."
                " the plugin also produces a layer of polygons overlaping the regrouped points within distance with an attribute table with also NumAggreg,Nb_Pts,List_Pts attributes.    \n "
                + "\n" +
                "                                                                                                                                                                \n"
                +
                "  The polygons are buffers (D/100) of the convex hull polygons of the aggregated points \n "
                +
                "                                                                                                                                                          \n"
                + "\n" +
                "<br><b>WARNING 2:</b><br> The polygons are meant - as the lines - only to show the aggregates but they overlap often points that are not part of the aggregate. The lines can be used for that matter  \n"
                +
                "<br><b>In order to select point of an aggregate only consider the point table attribute !</b><br>"
                "                                                                                                                                                          \n"
                + "\n" +
                " <br><b><i>NOTA BENE: all rasters should be unchecked in layer panel or the plugin won't work !</i></b></br>"
                " This plugin is not a part of Qgis engine and any problems should be reported only to the author. </p></td></tr></table>"
                "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"></p>\n"
                "<p style=\"margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\">"
                "                   "
                "<br><b>[email protected]</b><br>"
                "<br><br><i>code 0.2 (26 march 2019).</i></p></body></html>",
                None))
        self.pushButton.setText(QApplication.translate("Dialog", "OK", None))
class Ui_Dialog(object):
    """
    def __init__(self, iface):
        self.iface = iface
    """
    def setupUi(self, Dialog):
        self.iface = iface
        Dialog.setObjectName("Dialog")
        Dialog.resize(
            QtCore.QSize(QtCore.QRect(0, 0, 350, 250).size()).expandedTo(
                Dialog.minimumSizeHint()))
        Dialog.setWindowTitle("GroupPointsWithinDistance")

        # QLabel lancer recherche
        self.label10 = QLabel(Dialog)
        self.label10.setGeometry(QtCore.QRect(15, 15, 320, 18))
        self.label10.setObjectName("label10")
        self.label10.setText("Select a layer with points to regroup:  ")

        ListeCouchesPoint = [""]
        NbCouches = self.iface.mapCanvas().layerCount()
        if NbCouches == 0:
            QMessageBox.information(None, "information:", "No layers ! ")
        else:
            for i in range(0, NbCouches):
                couche = self.iface.mapCanvas().layer(i)
                # 0 pour point
                if couche.geometryType() == 0 or couche.geometryType() == 3:
                    if couche.isValid():
                        ListeCouchesPoint.append(couche.name())
                    else:
                        QMessageBox.information(None, "information:",
                                                "No layers with points ! ")
                        return None
        self.ComboBoxPoints = QComboBox(Dialog)
        self.ComboBoxPoints.setMinimumSize(QtCore.QSize(320, 25))
        self.ComboBoxPoints.setMaximumSize(QtCore.QSize(320, 25))
        self.ComboBoxPoints.setGeometry(QtCore.QRect(10, 35, 320, 25))
        self.ComboBoxPoints.setObjectName("ComboBoxPoints")
        for i in range(len(ListeCouchesPoint)):
            self.ComboBoxPoints.addItem(ListeCouchesPoint[i])

        # QLabel entrer Enter distance of recherch
        self.labelResearchDistance = QLabel(Dialog)
        self.labelResearchDistance.setGeometry(QtCore.QRect(15, 80, 240, 23))
        self.labelResearchDistance.setObjectName(" ResearchDistance")
        self.labelResearchDistance.setText("Enter distance of research :")

        #Exemple de QDoubleSpinBox
        self.dsbResearchDistance = QDoubleSpinBox(Dialog)
        self.dsbResearchDistance.setMinimumSize(QtCore.QSize(70, 23))
        self.dsbResearchDistance.setMaximumSize(QtCore.QSize(70, 23))
        self.dsbResearchDistance.setGeometry(QtCore.QRect(180, 80, 70, 23))
        self.dsbResearchDistance.setObjectName("dsb")
        #self.dsbResearchDistance.setValue(10.0)
        self.dsbResearchDistance.setDecimals(1)
        self.dsbResearchDistance.setSingleStep(10.0)
        self.dsbResearchDistance.setRange(0, 1000000)
        self.dsbResearchDistance.setProperty("value", 100.0)

        #self.dsbResearchDistance.valueChanged.connect(self.onValueChanged)

        #Exemple de QPushButton
        self.DoButton = QPushButton(Dialog)
        self.DoButton.setMinimumSize(QtCore.QSize(280, 20))
        self.DoButton.setMaximumSize(QtCore.QSize(280, 20))
        self.DoButton.setGeometry(QtCore.QRect(15, 120, 280, 20))
        self.DoButton.setObjectName("DoButton")
        self.DoButton.setText(" Let's make aggregates - being patient !")

        #Exemple de QLCDNumber
        self.progressBar = QProgressBar(Dialog)
        self.progressBar.setProperty("value", 0)
        self.progressBar.setMinimumSize(QtCore.QSize(260, 15))
        self.progressBar.setMaximumSize(QtCore.QSize(260, 15))
        self.progressBar.setGeometry(QtCore.QRect(30, 155, 260, 15))
        self.progressBar.setAlignment(QtCore.Qt.AlignCenter)
        self.progressBar.setTextVisible(True)
        self.progressBar.setObjectName("progressBar")
        self.progressBar.setStyleSheet(
            """QProgressBar {border: 2px solid grey; border-radius: 5px; text-align: center;}"""
            """QProgressBar::chunk {background-color: #6C96C6; width: 20px;}"""
        )
        #Pose a minima une valeur de la barre de progression / slide contrôle
        self.progressBar.setValue(0)

        #Exemple de QPushButton
        self.aboutButton = QPushButton(Dialog)
        self.aboutButton.setMinimumSize(QtCore.QSize(70, 20))
        self.aboutButton.setMaximumSize(QtCore.QSize(70, 20))
        self.aboutButton.setGeometry(QtCore.QRect(30, 195, 70, 23))
        self.aboutButton.setObjectName("aboutButton")
        self.aboutButton.setText(" Read me ")

        self.PushButton = QPushButton(Dialog)
        self.PushButton.setMinimumSize(QtCore.QSize(100, 20))
        self.PushButton.setMaximumSize(QtCore.QSize(100, 20))
        self.PushButton.setGeometry(QtCore.QRect(185, 195, 100, 20))
        self.PushButton.setObjectName("PushButton")
        self.PushButton.setText("Close")

        self.PushButton.clicked.connect(Dialog.reject)
        self.ComboBoxPoints.activated[str].connect(self.onComboP)
        self.aboutButton.clicked.connect(self.doAbout)
        self.DoButton.clicked.connect(self.Run)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def onComboP(self):
        global SelectionP
        SelectionP = self.ComboBoxPoints.currentText()

    def doAbout(self):
        d = doAboutGroupPointsWithinDistance.Dialog()
        d.exec_()

    def Run(self):
        D = 0.0
        D = self.dsbResearchDistance.value()
        #QMessageBox.information(None,"information:"," D : "+str(D))
        DicoP1 = {}
        DicoA = {}
        counterProgess = 0
        compteur_pt = 0
        layerP = fonctionsGPWD.getVectorLayerByName(SelectionP)
        # on parcourt la couche de points et on stocke dans les dictionnaire DicoP1  les points
        # the points of the point laye are put into a dictionnary
        for featP in layerP.getFeatures():
            Point_id = featP.id()
            geomP1 = featP.geometry()
            Point1 = geomP1.asPoint()
            DicoP1[Point_id] = [Point1]
            compteur_pt += 1

        if D == 0:
            QMessageBox.information(None, "information:",
                                    "Zero is not a value for D !")

        #zdim est le compteur de la progress bar
        zDim = compteur_pt
        counterProgess = 0
        cpt_agg = 1
        nb = 0
        liste_id = []
        liste_pt = []
        liste_aggreg_pt = []
        DicoSegments = {}
        firstDicoSegments = True
        T = True
        while len(DicoP1) != 0:
            first = True
            zPercent = int(100 * counterProgess / zDim)
            self.progressBar.setValue(zPercent)
            nb = 0
            for keyD1 in list(DicoP1.keys()):
                P1 = DicoP1[keyD1][0]
            if first:
                # we pick a first point and delete it from the dictionnary we point are stored
                T = True
                first = False
                nb += 1
                liste_id = [keyD1]
                liste_pt = [P1]
                counterProgess += 1
                del DicoP1[keyD1]
            while T:
                # We are generating an aggregates and making it grows
                # by adding points at distance from the point it contains
                # and repeating the research all over again as soon a poitn is added
                # untill none are added
                for pt in liste_pt:
                    compteur_corresP = 0
                    for keyD1 in list(DicoP1.keys()):
                        P1 = DicoP1[keyD1][0]
                        if fonctionsGPWD.mag(fonctionsGPWD.vect(
                                pt, P1)) < D:  # one point at distance found
                            compteur_corresId = 0
                            for idp in liste_id:
                                if keyD1 == idp:  # is this point already added in the aggregate
                                    compteur_corresId += 1
                            if compteur_corresId == 0:  # if not let s add it
                                nb += 1
                                liste_id.append(keyD1)
                                liste_pt.append(P1)
                                compteur_corresP += 1
                                counterProgess += 1
                                # boucle des segments
                                # interpoint line loop
                                idseg = ''  # a segment as an id made of the points id order ordered id: smallerid-biggerid
                                idseg = str(keyD1) + '-' + str(idp)
                                idseg_reverse = str(idp) + '-' + str(keyD1)
                                if firstDicoSegments:
                                    firstDicoSegments = False
                                    if int(keyD1) > int(idp):
                                        idseg = idseg_reverse
                                        DicoSegments[idseg] = [[pt, P1], idp,
                                                               keyD1, cpt_agg]
                                    else:
                                        DicoSegments[idseg] = [[P1, pt], keyD1,
                                                               idp, cpt_agg]
                                else:
                                    for idseg_cheack in list(
                                            DicoSegments.keys()):
                                        if idseg == idseg_cheack or idseg_reverse == idseg_cheack:
                                            pass
                                        else:
                                            if int(keyD1) > int(idp):
                                                idseg = idseg_reverse
                                                DicoSegments[idseg] = [[
                                                    pt, P1
                                                ], idp, keyD1, cpt_agg]
                                            else:
                                                DicoSegments[idseg] = [[
                                                    P1, pt
                                                ], keyD1, idp, cpt_agg]

                if compteur_corresP == 0:  # if no more points are find then we are over with the previous aggregate
                    T = False

                    DicoA[cpt_agg] = [nb, liste_id, liste_pt, DicoSegments]
                    cpt_agg += 1
                    for id in liste_id:
                        for keyD1 in list(DicoP1.keys()):
                            if id == keyD1:
                                del DicoP1[keyD1]

        # on fabrique un polygone buffer de D/100
        # du convexHull de tous les points de l'agregat
        # pour les operateur Pyqgis
        # voir http://www.qgis.org/api/classQgsGeometry.html#a1699b205d01c365a50ead2d0bf2bbcfb
        DicoP4 = {}

        for key2 in list(DicoA.keys()):
            list_pt = []
            list_pt = DicoA[key2][2]
            nb_pt = 0
            nb_pt = DicoA[key2][0]
            Liste_id = []
            Liste_id = DicoA[key2][1]
            buff = 0.0
            first = True
            for pt in list_pt:
                if first:
                    first = False
                    #https://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/geometry.html
                    g0 = QgsGeometry().fromPointXY(pt)
                else:
                    g0 = QgsGeometry().fromPointXY(pt).combine(
                        g0)  # combine pour union car union reserve C++
            buff = D / 100
            P = g0.convexHull()
            B = P.buffer(buff, 5)
            DicoP4[key2] = [B, Liste_id, nb_pt]

        zPercent = int(100 * counterProgess / zDim)
        self.progressBar.setValue(zPercent)
        self.iface.mapCanvas().refresh()

        STATIONS = QgsVectorLayer(
            "MultiPolygon", "Polygons_under_AGGREGATES_D" + str(D) + "_OF_" +
            str(layerP.name()), "memory")
        QgsProject.instance().addMapLayer(STATIONS)
        prSTATIONS = STATIONS.dataProvider()
        listFieldsS = []
        listFieldsS.append(QgsField("NumAggreg", QVariant.String))
        listFieldsS.append(QgsField("List_Pts", QVariant.String))
        listFieldsS.append(QgsField("Nb_Pts", QVariant.Int))
        prSTATIONS.addAttributes(listFieldsS)

        STATIONS.startEditing()
        newfeatSTATIONS = QgsFeature()
        for keyP4 in DicoP4.keys():
            GeomPoly = DicoP4[keyP4][0]
            newfeatSTATIONS = QgsFeature()
            newfeatSTATIONS.setGeometry(GeomPoly)
            toto = ''
            first = True
            for t in DicoP4[keyP4][1]:
                if first:
                    first = False
                    toto = str(t)
                else:
                    toto = toto + ' - ' + str(t)
            NbObs = DicoP4[keyP4][2]
            ValuesSTATIONS = [keyP4]
            ValuesSTATIONS.append(toto)
            ValuesSTATIONS.append(NbObs)
            newfeatSTATIONS.setAttributes(ValuesSTATIONS)
            prSTATIONS.addFeatures([newfeatSTATIONS])
        STATIONS.commitChanges()
        iface.mapCanvas().refresh()

        SEGMENTS = QgsVectorLayer(
            "MultiLineString",
            "Lines_from_" + str(layerP.name()) + "_Aggregates_with_D" + str(D),
            "memory")
        QgsProject.instance().addMapLayer(SEGMENTS)
        prSEGMENTS = SEGMENTS.dataProvider()
        listFields = []
        listFields.append(QgsField("NumAgregat", QVariant.String))
        listFields.append(QgsField("Nb_Pts", QVariant.Int))
        prSEGMENTS.addAttributes(listFields)
        SEGMENTS.startEditing()
        newfeatSEGMENTS = QgsFeature()
        attributs = []
        for keyA in DicoA.keys():
            DicoSeg = DicoA[keyA][3]
            NbObs = DicoA[keyA][0]
            firstSEG = True
            MultiLine = []
            GeomLine = QgsGeometry
            for keyPair in DicoSeg.keys():
                if DicoSeg[keyPair][3] == keyA:
                    if firstSEG:
                        firstSEG = False
                        MultiLine = []
                        MultiLine = [DicoSeg[keyPair][0]]
                    else:
                        MultiLine.append(DicoSeg[keyPair][0])

            GeomLine = QgsGeometry.fromMultiPolylineXY(MultiLine)
            NumAg = keyA
            newfeatSEGMENTS = QgsFeature()
            newfeatSEGMENTS.setGeometry(GeomLine)
            ValuesSEGMENTS = [NumAg]
            ValuesSEGMENTS.append(NbObs)
            newfeatSEGMENTS.setAttributes(ValuesSEGMENTS)
            prSEGMENTS.addFeatures([newfeatSEGMENTS])
        SEGMENTS.commitChanges()
        iface.mapCanvas().refresh()

        # modification de la table de point initiale pour ajout d un numero d agregat
        # making of the modified point layer with aggregates code
        AGGREGATS = QgsVectorLayer(
            "Point",
            str(layerP.name()) + "_aggregated_with_D" + str(D), "memory")
        QgsProject.instance().addMapLayer(AGGREGATS)
        prAGGREGATS = AGGREGATS.dataProvider()
        fieldsP = layerP.fields()
        listFields = []
        for f in fieldsP:
            znameField = f.name()
            Type = str(f.typeName())
            if Type == 'Integer':
                listFields.append(QgsField(znameField, QVariant.Int))
            if Type == 'Real':
                listFields.append(QgsField(znameField, QVariant.Double))
            if Type == 'String':
                listFields.append(QgsField(znameField, QVariant.String))
            else:
                listFields.append(QgsField(znameField, QVariant.String))
        listFields.append(QgsField("Point_id", QVariant.String))
        listFields.append(QgsField("NumAggreg", QVariant.String))
        listFields.append(QgsField("Nb_Pts", QVariant.Int))
        listFields.append(QgsField("List_Pts", QVariant.String))
        prAGGREGATS.addAttributes(listFields)
        AGGREGATS.startEditing()
        newfeatAGGREGATS = QgsFeature()
        attributs = []
        for featP in layerP.getFeatures():
            attributs = featP.attributes()
            Point_id = featP.id()
            geomP1 = featP.geometry()
            NbObs = 1
            NumAgregat = 0
            for keyP4 in DicoP4.keys():
                #GeomPoly=DicoP4[keyP4][0]
                #if geomP1.intersects(GeomPoly):
                for ptid in DicoP4[keyP4][1]:
                    if Point_id == ptid:
                        NbObs = DicoP4[keyP4][2]
                        toto = ''
                        first = True
                        for t in DicoP4[keyP4][1]:
                            if first:
                                first = False
                                toto = str(t)
                            else:
                                toto = toto + ' - ' + str(t)
                        list_id = toto
                        NumAgregat = keyP4
            newfeatAGGREGATS = QgsFeature()
            newfeatAGGREGATS.setGeometry(geomP1)
            ValuesAGGREGATS = attributs
            ValuesAGGREGATS.append(Point_id)
            ValuesAGGREGATS.append(NumAgregat)
            ValuesAGGREGATS.append(NbObs)
            ValuesAGGREGATS.append(list_id)
            newfeatAGGREGATS.setAttributes(ValuesAGGREGATS)
            prAGGREGATS.addFeatures([newfeatAGGREGATS])
        AGGREGATS.commitChanges()
        iface.mapCanvas().refresh()