def mk_prj_storage_icon(self, qgs_type_storage: str) -> QLabel: """Returns a QLabel with the matching icon for the storage type. :param qgs_type_storage: storage type :type qgs_type_storage: str :return: QLabel to be set in a cellWidget :rtype: QLabel """ lbl_location_type = QLabel(self.tableWidget) lbl_location_type.setPixmap( QPixmap(icon_per_storage_type(qgs_type_storage))) lbl_location_type.setScaledContents(True) lbl_location_type.setMaximumSize(20, 20) lbl_location_type.setAlignment(Qt.AlignCenter) lbl_location_type.setTextInteractionFlags(Qt.NoTextInteraction) lbl_location_type.setToolTip(qgs_type_storage) return lbl_location_type
def __init__(self, parent, model_to_insert, snimar_keyword_types_list): super(SNIMARKeywordsDialog, self).__init__(parent) self.model_to_insert = model_to_insert self.combo_items_md_keywordtypecode = snimar_keyword_types_list if platform.system() != "Linux": font = QFont() font.setFamily(u"Segoe UI Symbol") self.setFont(font) self.setupUi(self) self.setModal(True) self.thesaurus_model = SnimarThesurusModel().get_Model() self.to_add_keywords = {} # id : QStandartItem self.list_view_thesaurus.setModel(self.thesaurus_model) # TODO fix this self.thesaurus_model.itemChanged.connect(self.register_item) self.list_view_thesaurus.setAlternatingRowColors(True) self.list_view_thesaurus.setSelectionBehavior( QAbstractItemView.SelectColumns) self.list_view_thesaurus.setSelectionMode( QAbstractItemView.SingleSelection) self.list_view_thesaurus.setTextElideMode(Qt.ElideNone) self.list_view_thesaurus.setVerticalScrollBarPolicy( Qt.ScrollBarAlwaysOff) self.list_view_thesaurus.setHorizontalScrollBarPolicy( Qt.ScrollBarAsNeeded) self.list_view_thesaurus.setResizeGripsVisible(False) self.list_view_thesaurus.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.list_view_thesaurus.setColumnWidths( [300, 300, 300, 0, 0, 0, 0, 0]) self.list_view_thesaurus.setAutoScroll(True) label = QLabel('') label.setMaximumSize(0, 0) self.list_view_thesaurus.setPreviewWidget(label) label.hide() self.bt_add_selected.clicked.connect(self.add_keywords) self.btn_exit.clicked.connect(lambda: self.done(0)) self.setSizeGripEnabled(True) self.resize(self.maximumSize()) self.adjustSize()
class CommanderWindow(QDialog): def __init__(self, parent, canvas): self.canvas = canvas QDialog.__init__(self, parent, Qt.FramelessWindowHint) self.commands = imp.load_source('commands', self.commandsFile()) self.initGui() def commandsFolder(self): folder = unicode(os.path.join(userFolder(), 'commander')) mkdir(folder) return os.path.abspath(folder) def commandsFile(self): f = os.path.join(self.commandsFolder(), 'commands.py') if not os.path.exists(f): out = open(f, 'w') out.write('from qgis.core import *\n') out.write('import processing\n\n') out.write('def removeall():\n') out.write('\tmapreg = QgsMapLayerRegistry.instance()\n') out.write('\tmapreg.removeAllMapLayers()\n\n') out.write('def load(*args):\n') out.write('\tprocessing.load(args[0])\n') out.close() return f def algsListHasChanged(self): self.fillCombo() def initGui(self): self.combo = ExtendedComboBox() self.fillCombo() self.combo.setEditable(True) self.label = QLabel('Enter command:') self.errorLabel = QLabel('Enter command:') self.vlayout = QVBoxLayout() self.vlayout.setSpacing(2) self.vlayout.setMargin(0) self.vlayout.addSpacerItem( QSpacerItem(0, OFFSET, QSizePolicy.Maximum, QSizePolicy.Expanding)) self.hlayout = QHBoxLayout() self.hlayout.addWidget(self.label) self.vlayout.addLayout(self.hlayout) self.hlayout2 = QHBoxLayout() self.hlayout2.addWidget(self.combo) self.vlayout.addLayout(self.hlayout2) self.vlayout.addSpacerItem( QSpacerItem(0, OFFSET, QSizePolicy.Maximum, QSizePolicy.Expanding)) self.setLayout(self.vlayout) self.combo.lineEdit().returnPressed.connect(self.run) self.prepareGui() def fillCombo(self): self.combo.clear() # Add algorithms for algs in algList.algs.values(): for alg in algs: self.combo.addItem('Processing algorithm: ' + alg) # Add functions for command in dir(self.commands): if isinstance(self.commands.__dict__.get(command), types.FunctionType): self.combo.addItem('Command: ' + command) # Add menu entries menuActions = [] actions = iface.mainWindow().menuBar().actions() for action in actions: menuActions.extend(self.getActions(action)) for action in menuActions: self.combo.addItem('Menu action: ' + unicode(action.text())) def prepareGui(self): self.combo.setEditText('') self.combo.setMaximumSize( QSize(self.canvas.rect().width() - 2 * OFFSET, ITEMHEIGHT)) self.combo.view().setStyleSheet('min-height: 150px') self.combo.setFocus(Qt.OtherFocusReason) self.label.setMaximumSize(self.combo.maximumSize()) self.label.setVisible(False) self.adjustSize() pt = self.canvas.rect().topLeft() absolutePt = self.canvas.mapToGlobal(pt) self.move(absolutePt) self.resize(self.canvas.rect().width(), HEIGHT) self.setStyleSheet('CommanderWindow {background-color: #e7f5fe; \ border: 1px solid #b9cfe4;}') def getActions(self, action): menuActions = [] menu = action.menu() if menu is None: menuActions.append(action) return menuActions else: actions = menu.actions() for subaction in actions: if subaction.menu() is not None: menuActions.extend(self.getActions(subaction)) elif not subaction.isSeparator(): menuActions.append(subaction) return menuActions def run(self): s = unicode(self.combo.currentText()) if s.startswith('Processing algorithm: '): algName = s[len('Processing algorithm: '):] alg = Processing.getAlgorithmFromFullName(algName) if alg is not None: self.close() self.runAlgorithm(alg) elif s.startswith("Command: "): command = s[len("Command: "):] try: self.runCommand(command) self.close() except Exception as e: self.label.setVisible(True) self.label.setText('Error:' + unicode(e)) elif s.startswith('Menu action: '): actionName = s[len('Menu action: '):] menuActions = [] actions = iface.mainWindow().menuBar().actions() for action in actions: menuActions.extend(self.getActions(action)) for action in menuActions: if action.text() == actionName: self.close() action.trigger() return else: try: self.runCommand(s) self.close() except Exception as e: self.label.setVisible(True) self.label.setText('Error:' + unicode(e)) def runCommand(self, command): tokens = command.split(' ') if len(tokens) == 1: method = self.commands.__dict__.get(command) if method is not None: method() else: raise Exception('Wrong command') else: method = self.commands.__dict__.get(tokens[0]) if method is not None: method(*tokens[1:]) else: raise Exception('Wrong command') def runAlgorithm(self, alg): alg = alg.getCopy() message = alg.checkBeforeOpeningParametersDialog() if message: dlg = MessageDialog() dlg.setTitle(self.tr('Missing dependency')) dlg.setMessage(message) dlg.exec_() return dlg = alg.getCustomParametersDialog() if not dlg: dlg = AlgorithmDialog(alg) canvas = iface.mapCanvas() prevMapTool = canvas.mapTool() dlg.show() dlg.exec_() if canvas.mapTool() != prevMapTool: try: canvas.mapTool().reset() except: pass canvas.setMapTool(prevMapTool)
class CommanderWindow(QDialog): def __init__(self, parent, canvas): self.canvas = canvas QDialog.__init__(self, parent, Qt.FramelessWindowHint) self.commands = imp.load_source('commands', self.commandsFile()) self.initGui() def commandsFolder(self): folder = str(os.path.join(userFolder(), 'commander')) mkdir(folder) return os.path.abspath(folder) def commandsFile(self): f = os.path.join(self.commandsFolder(), 'commands.py') if not os.path.exists(f): with open(f, 'w') as out: out.write('from qgis.core import *\n') out.write('import processing\n\n') out.write('def removeall():\n') out.write('\tmapreg = QgsProject.instance()\n') out.write('\tmapreg.removeAllMapLayers()\n\n') out.write('def load(*args):\n') out.write('\tprocessing.load(args[0])\n') return f def algsListHasChanged(self): self.fillCombo() def initGui(self): self.combo = ExtendedComboBox() self.fillCombo() self.combo.setEditable(True) self.label = QLabel('Enter command:') self.errorLabel = QLabel('Enter command:') self.vlayout = QVBoxLayout() self.vlayout.setSpacing(2) self.vlayout.setMargin(0) self.vlayout.addSpacerItem(QSpacerItem(0, OFFSET, QSizePolicy.Maximum, QSizePolicy.Expanding)) self.hlayout = QHBoxLayout() self.hlayout.addWidget(self.label) self.vlayout.addLayout(self.hlayout) self.hlayout2 = QHBoxLayout() self.hlayout2.addWidget(self.combo) self.vlayout.addLayout(self.hlayout2) self.vlayout.addSpacerItem(QSpacerItem(0, OFFSET, QSizePolicy.Maximum, QSizePolicy.Expanding)) self.setLayout(self.vlayout) self.combo.lineEdit().returnPressed.connect(self.run) self.prepareGui() def fillCombo(self): self.combo.clear() # Add algorithms for provider in list(algList.algs.values()): for alg in provider: self.combo.addItem('Processing algorithm: ' + alg) # Add functions for command in dir(self.commands): if isinstance(self.commands.__dict__.get(command), types.FunctionType): self.combo.addItem('Command: ' + command) # Add menu entries menuActions = [] actions = iface.mainWindow().menuBar().actions() for action in actions: menuActions.extend(self.getActions(action)) for action in menuActions: self.combo.addItem('Menu action: ' + str(action.text())) def prepareGui(self): self.combo.setEditText('') self.combo.setMaximumSize(QSize(self.canvas.rect().width() - 2 * OFFSET, ITEMHEIGHT)) self.combo.view().setStyleSheet('min-height: 150px') self.combo.setFocus(Qt.OtherFocusReason) self.label.setMaximumSize(self.combo.maximumSize()) self.label.setVisible(False) self.adjustSize() pt = self.canvas.rect().topLeft() absolutePt = self.canvas.mapToGlobal(pt) self.move(absolutePt) self.resize(self.canvas.rect().width(), HEIGHT) self.setStyleSheet('CommanderWindow {background-color: #e7f5fe; \ border: 1px solid #b9cfe4;}') def getActions(self, action): menuActions = [] menu = action.menu() if menu is None: menuActions.append(action) return menuActions else: actions = menu.actions() for subaction in actions: if subaction.menu() is not None: menuActions.extend(self.getActions(subaction)) elif not subaction.isSeparator(): menuActions.append(subaction) return menuActions def run(self): s = str(self.combo.currentText()) if s.startswith('Processing algorithm: '): algName = s[len('Processing algorithm: '):] alg = algList.getAlgorithm(algName) if alg is not None: self.close() self.runAlgorithm(alg) elif s.startswith("Command: "): command = s[len("Command: "):] try: self.runCommand(command) self.close() except Exception as e: self.label.setVisible(True) self.label.setText('Error:' + str(e)) elif s.startswith('Menu action: '): actionName = s[len('Menu action: '):] menuActions = [] actions = iface.mainWindow().menuBar().actions() for action in actions: menuActions.extend(self.getActions(action)) for action in menuActions: if action.text() == actionName: self.close() action.trigger() return else: try: self.runCommand(s) self.close() except Exception as e: self.label.setVisible(True) self.label.setText('Error:' + str(e)) def runCommand(self, command): tokens = command.split(' ') if len(tokens) == 1: method = self.commands.__dict__.get(command) if method is not None: method() else: raise Exception('Wrong command') else: method = self.commands.__dict__.get(tokens[0]) if method is not None: method(*tokens[1:]) else: raise Exception('Wrong command') def runAlgorithm(self, alg): alg = alg.getCopy() message = alg.checkBeforeOpeningParametersDialog() if message: dlg = MessageDialog() dlg.setTitle(self.tr('Missing dependency')) dlg.setMessage(message) dlg.exec_() return dlg = alg.getCustomParametersDialog() if not dlg: dlg = AlgorithmDialog(alg) canvas = iface.mapCanvas() prevMapTool = canvas.mapTool() dlg.show() dlg.exec_() if canvas.mapTool() != prevMapTool: try: canvas.mapTool().reset() except: pass canvas.setMapTool(prevMapTool)
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)
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()