def __init__(self, repo, layer=None): self.repo = repo self.layer = layer self.ref = None QDialog.__init__(self, config.iface.mainWindow(), Qt.WindowSystemMenuHint | Qt.WindowTitleHint) execute(self.initGui)
def __init__(self): QDialog.__init__(self) self.setWindowTitle(tr('XY Point drawing tool')) self.X = QLineEdit() self.Y = QLineEdit() X_val = QDoubleValidator() Y_val = QDoubleValidator() self.X.setValidator(X_val) self.Y.setValidator(Y_val) self.crsButton = QPushButton("Projection") self.crsButton.clicked.connect(self.changeCRS) self.crsLabel = QLabel("") buttons = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self) buttons.accepted.connect(self.accept) buttons.rejected.connect(self.reject) grid = QGridLayout() grid.addWidget(QLabel("X"), 0, 0) grid.addWidget(QLabel("Y"), 0, 1) grid.addWidget(self.X, 1, 0) grid.addWidget(self.Y, 1, 1) grid.addWidget(self.crsButton, 2, 0) grid.addWidget(self.crsLabel, 2, 1) grid.addWidget(buttons, 3, 0, 1, 2) self.setLayout(grid)
def accept(self): self.selectedoptions = [] model = self.lstLayers.model() for i in range(model.rowCount()): item = model.item(i) self.selectedoptions.append(item.text()) QDialog.accept(self)
def __init__(self, iface): self.iface = iface QDialog.__init__(self) # Set up the user interface from Designer. self.ui = uic.loadUi(ui_file, self) self.configFilePath = os.path.join(os.path.dirname(__file__), 'config.cfg') self.defFlags = Qt.NoItemFlags | Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsSelectable # Populate the PostGIS connection combo with the available connections # Determine our current preference s = QSettings() selectedConnection = str(s.value("constraintchecker/postgisConnection", '')) s.beginGroup('PostgreSQL/connections') i = 0 for connectionName in s.childGroups(): self.postgisConnectionComboBox.addItem(connectionName) if connectionName == selectedConnection: # Select this preference in the combo if exists self.postgisConnectionComboBox.setCurrentIndex(i) i += 1 s.endGroup() # Now read the configuration file (if it exists) into the table widget try: self.readConfiguration() except: pass
def __init__(self): QDialog.__init__(self) self.setWindowTitle(tr('Rectangle size')) self.width = QLineEdit() self.height = QLineEdit() width_val = QDoubleValidator() height_val = QDoubleValidator() self.width.setValidator(width_val) self.height.setValidator(height_val) buttons = QDialogButtonBox( QDialogButtonBox.Ok | QDialogButtonBox.Cancel, Qt.Horizontal, self) buttons.accepted.connect(self.accept) buttons.rejected.connect(self.reject) grid = QGridLayout() grid.addWidget(QLabel(tr('Give a size in m:')), 0, 0) grid.addWidget(QLabel(tr('Width:')), 1, 0) grid.addWidget(QLabel(tr('Height:')), 1, 1) grid.addWidget(self.width, 2, 0) grid.addWidget(self.height, 2, 1) grid.addWidget(buttons, 3, 0, 1, 2) self.setLayout(grid)
def reject(self): self.param = None settings = QgsSettings() settings.setValue("/Processing/modelParametersDefinitionDialogGeometry", self.saveGeometry()) QDialog.reject(self)
def __init__(self, alg, paramType=None, param=None): self.alg = alg self.paramType = paramType self.param = param QDialog.__init__(self) self.setModal(True) self.setupUi()
def __init__(self, alg, model, algName=None, configuration=None): QDialog.__init__(self) self.setModal(True) self._alg = alg # The algorithm to define in this dialog. It is an instance of QgsProcessingAlgorithm self.model = model # The model this algorithm is going to be added to. It is an instance of QgsProcessingModelAlgorithm self.childId = algName # The name of the algorithm in the model, in case we are editing it and not defining it for the first time self.configuration = configuration self.context = createContext() self.widget_labels = {} class ContextGenerator(QgsProcessingContextGenerator): def __init__(self, context): super().__init__() self.processing_context = context def processingContext(self): return self.processing_context self.context_generator = ContextGenerator(self.context) self.setupUi() self.params = None settings = QgsSettings() self.restoreGeometry(settings.value("/Processing/modelParametersDialogGeometry", QByteArray()))
def accept(self): styles = {} for key in self.valueItems.keys(): styles[key] = unicode(self.valueItems[key].getValue()) RenderingStyles.addAlgStylesAndSave(self.alg.commandLineName(), styles) QDialog.accept(self)
def __init__(self, iface): QDialog.__init__(self, iface.mainWindow()) self.setAttribute(Qt.WA_DeleteOnClose) self.iface = iface self.setupUi(self) # binaries self.leGdalBinPath.setText(Utils.getGdalBinPath()) self.btnSetBinPath.clicked.connect(self.setBinPath) self.bin_tooltip_label.setPixmap(QPixmap(':/icons/tooltip.png')) self.bin_tooltip_label.setToolTip(self.tr(u"""\ A list of colon-separated (Linux and MacOS) or semicolon-separated (Windows) paths to both binaries and python executables. MacOS users usually need to set it to something like /Library/Frameworks/GDAL.framework/Versions/1.8/Programs""")) # python modules self.leGdalPymodPath.setText(Utils.getGdalPymodPath()) self.btnSetPymodPath.clicked.connect(self.setPymodPath) self.pymod_tooltip_label.setPixmap(QPixmap(':/icons/tooltip.png')) self.pymod_tooltip_label.setToolTip(self.tr(u"""\ A list of colon-separated (Linux and MacOS) or semicolon-separated (Windows) paths to python modules.""")) # help self.leGdalHelpPath.setText(Utils.getHelpPath()) self.btnSetHelpPath.clicked.connect(self.setHelpPath) self.help_tooltip_label.setPixmap(QPixmap(':/icons/tooltip.png')) self.help_tooltip_label.setToolTip(self.tr(u"""\ Useful to open local GDAL documentation instead of online help when pressing on the tool dialog's Help button."""))
def show(self): QDialog.show(self) self.setWindowModality(0) if self.firstShow: inet = internet_on(proxyUrl=self.proxy, timeout=self.timeout) #filters if inet: self.poiThemes = dict( self.poi.listPoiThemes() ) poiThemes = [""] + list(self.poiThemes.keys()) poiThemes.sort() self.ui.filterPoiThemeCombo.addItems( poiThemes ) self.poiCategories = dict( self.poi.listPoiCategories() ) poiCategories = [""] + list(self.poiCategories.keys()) poiCategories.sort() self.ui.filterPoiCategoryCombo.addItems( poiCategories ) self.poiTypes = dict( self.poi.listPoitypes() ) poiTypes = [""] + list(self.poiTypes.keys()) poiTypes.sort() self.ui.filterPoiTypeCombo.addItems( poiTypes ) gemeentes = json.load( open(os.path.join(os.path.dirname(__file__), "data/gemeentenVL.json")) ) self.NIScodes= { n["Naam"] : n["Niscode"] for n in gemeentes } gemeenteNamen = [n["Naam"] for n in gemeentes] gemeenteNamen.sort() self.ui.filterPoiNIS.addItems( gemeenteNamen ) #connect when inet on self.ui.filterPoiThemeCombo.activated.connect(self.onThemeFilterChange) self.ui.filterPoiCategoryCombo.activated.connect(self.onCategorieFilterChange) self.firstShow = False else: self.bar.pushMessage( QCoreApplication.translate("geopunt4QgisPoidialog", "Waarschuwing "), QCoreApplication.translate("geopunt4QgisPoidialog", "Kan geen verbing maken met het internet."), level=Qgis.Warning, duration=3)
def accept(self): styles = {} for key in list(self.valueItems.keys()): styles[key] = str(self.valueItems[key].getValue()) RenderingStyles.addAlgStylesAndSave(self.alg.id(), styles) QDialog.accept(self)
def __init__(self, parent=None, table=None, db=None): QDialog.__init__(self, parent) self.table = table self.db = self.table.database() if self.table and self.table.database() else db self.setupUi(self) self.buttonBox.accepted.connect(self.createGeomColumn)
def __init__(self, inLayer, outDb, outUri, parent=None): QDialog.__init__(self, parent) self.inLayer = inLayer self.db = outDb self.outUri = outUri self.setupUi(self) supportCom = self.db.supportsComment() if not supportCom: self.chkCom.setVisible(False) self.editCom.setVisible(False) self.default_pk = "id" self.default_geom = "geom" self.mode = self.ASK_FOR_INPUT_MODE if self.inLayer is None else self.HAS_INPUT_MODE # used to delete the inlayer whether created inside this dialog self.inLayerMustBeDestroyed = False self.populateSchemas() self.populateTables() self.populateLayers() self.populateEncodings() # updates of UI self.setupWorkingMode(self.mode) self.cboSchema.currentIndexChanged.connect(self.populateTables) self.widgetSourceSrid.setCrs(QgsProject.instance().crs()) self.widgetTargetSrid.setCrs(QgsProject.instance().crs()) self.updateInputLayer()
def __init__(self, table, parent=None): QDialog.__init__(self, parent) self.table = table self.setupUi(self) self.db = self.table.database() m = TableFieldsModel(self) self.viewFields.setModel(m) m = TableConstraintsModel(self) self.viewConstraints.setModel(m) m = TableIndexesModel(self) self.viewIndexes.setModel(m) self.btnAddColumn.clicked.connect(self.addColumn) self.btnAddGeometryColumn.clicked.connect(self.addGeometryColumn) self.btnEditColumn.clicked.connect(self.editColumn) self.btnDeleteColumn.clicked.connect(self.deleteColumn) self.btnAddConstraint.clicked.connect(self.addConstraint) self.btnDeleteConstraint.clicked.connect(self.deleteConstraint) self.btnAddIndex.clicked.connect(self.createIndex) self.btnAddSpatialIndex.clicked.connect(self.createSpatialIndex) self.btnDeleteIndex.clicked.connect(self.deleteIndex) self.populateViews() self.checkSupports()
def __init__(self, iface): self.supportedPaperSizes = ['A0', 'A1', 'A2', 'A3', 'A4', 'A5', 'A6', 'A7', 'A8'] # ISO A series self.paperSizesPresent = [] self.presetScales = ['200', '500', '1 000', '1 250', '2 500', '5 000', '10 000', '25 000', '50 000', '100 000'] self.iface = iface QDialog.__init__(self) # Set up the user interface from Designer. self.ui = uic.loadUi(ui_file, self) # Set up the list of templates s = QtCore.QSettings() self.identifiable_only = s.value("SelectorTools/ProjectSelector/identifiableOnly", True, type=bool) self.templateFileRoot = s.value("SelectorTools/TemplateSelector/templateRoot", '', type=str) if len(self.templateFileRoot) == 0 or not os.path.isdir(self.templateFileRoot): raise TemplateSelectorException('\'%s\' is not a valid template file root folder.' % self.templateFileRoot) self.populateTemplateTypes() self.populatePoiLayers() self.onPoiLayerChanged() self.onTemplateTypeChanged() self.plugin_dir = os.path.dirname(__file__) # Replacement map self.ui.suitableForComboBox.addItem('<custom>') self.user = os.environ.get('username', '[user]') self.replaceMap = { 'author': "Compiled by {} on [%concat(day($now ),'/',month($now),'/',year($now))%]".format(self.user) } self.ui.autofit_btn.clicked.connect(self.autofit_map) self.ui.suitableForComboBox.currentIndexChanged.connect(self.specify_dpi) self.ui.suitableForComboBox.editTextChanged.connect(self.text_changed) self.ui.poiLayerComboBox.currentIndexChanged.connect(self.onPoiLayerChanged)
def __init__(self, parent, iface, pluginBase, pluginName, pluginCommand): QDialog.__init__(self, parent) self.setAttribute(Qt.WA_DeleteOnClose) self.iface = iface self.process = QProcess(self) Utils.setProcessEnvironment(self.process) self.process.error.connect(self.processError) self.process.finished.connect(self.processFinished) self.setupUi(self) self.arguments = [] self.editCmdBtn.setIcon(QIcon(":/icons/edit.png")) self.editCmdBtn.toggled.connect(self.editCommand) self.resetCmdBtn.setIcon(QIcon(":/icons/reset.png")) self.resetCmdBtn.clicked.connect(self.resetCommand) self.editCommand(False) self.buttonBox.rejected.connect(self.reject) self.buttonBox.accepted.connect(self.accept) self.buttonBox.helpRequested.connect(self.help) self.buttonBox.button(QDialogButtonBox.Ok).setDefault(True) self.plugin = pluginBase self.valuesChanged.connect(self.handleRefreshArgs) self.pluginLayout.addWidget(self.plugin) self.plugin.setFocus() self.setWindowTitle(pluginName) self.setPluginCommand(pluginCommand)
def __init__(self, iface): """ Constructor """ QDialog.__init__(self) self.setupUi(self) self.iface = iface self.mc = self.iface.mapCanvas() #self.legend = self.iface.legendInterface() self.loaded_layers = [layer for layer in QgsProject.instance().mapLayers().values()] # UI CCONNECTORS self.buttonBox_ok_cancel.accepted.connect(self.run) self.buttonBox_ok_cancel.rejected.connect(self.close) self.comboBox_line_layer.currentIndexChanged.connect(self.update_fields) # Get line layers and raster layers from legend vector_line_layers, raster_layers = self.get_useful_layers() # Populate comboboxes self.comboBox_line_layer.clear() self.comboBox_line_layer.addItems(vector_line_layers) self.comboBox_elevation_layer.clear() self.comboBox_elevation_layer.addItems(raster_layers)
def __init__(self, parent): QDialog.__init__(self, parent) self.setWindowTitle(QCoreApplication.translate("SettingsDialogPythonConsole", "Settings Python Console")) self.parent = parent self.setupUi(self) self.listPath = [] self.lineEdit.setReadOnly(True) self.restoreSettings() self.initialCheck() self.addAPIpath.setIcon(QIcon(":/images/themes/default/symbologyAdd.svg")) self.addAPIpath.setToolTip(QCoreApplication.translate("PythonConsole", "Add API path")) self.removeAPIpath.setIcon(QIcon(":/images/themes/default/symbologyRemove.svg")) self.removeAPIpath.setToolTip(QCoreApplication.translate("PythonConsole", "Remove API path")) self.preloadAPI.stateChanged.connect(self.initialCheck) self.addAPIpath.clicked.connect(self.loadAPIFile) self.removeAPIpath.clicked.connect(self.removeAPI) self.compileAPIs.clicked.connect(self._prepareAPI) self.resetFontColor.setIcon(QIcon(":/images/themes/default/console/iconResetColorConsole.png")) self.resetFontColor.setIconSize(QSize(18, 18)) self.resetFontColorEditor.setIcon(QIcon(":/images/themes/default/console/iconResetColorConsole.png")) self.resetFontColorEditor.setIconSize(QSize(18, 18)) self.resetFontColor.clicked.connect(self._resetFontColor) self.resetFontColorEditor.clicked.connect(self._resetFontColorEditor)
def __init__(self, item, parent=None): QDialog.__init__(self, parent) self.item = item self.setupUi(self) self.db = self.item.database() self.schemas = self.db.schemas() self.hasSchemas = self.schemas is not None self.buttonBox.accepted.connect(self.onOK) self.buttonBox.helpRequested.connect(self.showHelp) self.populateSchemas() self.populateTables() if isinstance(item, Table): index = self.cboTable.findText(self.item.name) if index >= 0: self.cboTable.setCurrentIndex(index) self.cboSchema.currentIndexChanged.connect(self.populateTables) # updates of SQL window self.cboSchema.currentIndexChanged.connect(self.updateSql) self.cboTable.currentIndexChanged.connect(self.updateSql) self.chkCreateCurrent.stateChanged.connect(self.updateSql) self.editPkey.textChanged.connect(self.updateSql) self.editStart.textChanged.connect(self.updateSql) self.editEnd.textChanged.connect(self.updateSql) self.updateSql()
def __init__(self, parent=None): QDialog.__init__(self, parent) self.setupUi(self) self.titleBoldBtn.hide() self.titleItalicBtn.hide() self.labelsBoldBtn.hide() self.labelsItalicBtn.hide() # remove fonts matplotlib doesn't load for index in range(self.titleFontCombo.count()-1, -1, -1): found = False family = unicode( self.titleFontCombo.itemText( index ) ) try: props = self.findFont( {'family':family} ) if family == props['family']: found = True except Exception: pass if not found: self.titleFontCombo.removeItem( index ) self.labelsFontCombo.removeItem( index ) self.initProps() self.titleColorBtn.clicked.connect(self.chooseTitleColor) self.labelsColorBtn.clicked.connect(self.chooseLabelsColor) self.pointsColorBtn.clicked.connect(self.choosePointsColor) self.pointsReplicasColorBtn.clicked.connect(self.choosePointsReplicasColor) self.linesColorBtn.clicked.connect(self.chooseLinesColor) self.linesThrendColorBtn.clicked.connect(self.chooseLinesThrendColor)
def reject(self): #QMessageBox.warning(self.iface.mainWindow(), "VoGIS-Profiltool", "REJECTED") QgsMessageLog.logMessage("reject: {0}".format(self.exaggeration_edited), "VoGis", Qgis.Info) if self.exaggeration_edited is True: self.exaggeration_edited = False return QDialog.reject(self)
def __init__(self, iface): QDialog.__init__(self, iface.mainWindow()) self.iface = iface # Set up the user interface from Designer. self.setupUi(self) self.populateLayers() spaced_distance_list = ['1','2','3','4','5'] self.spaced_pts_comboBox.clear() for distance in spaced_distance_list: self.spaced_pts_comboBox.addItem(distance) self.spaced_pts_comboBox.setEnabled(False) self.middle_pts_radioButton.setChecked(1) self.spaced_pts_radioButton.setChecked(0) self.middle_pts_radioButton.toggled.connect(self.method_update) self.spaced_pts_radioButton.toggled.connect(self.method_update) self.receiver_layer_pushButton.clicked.connect(self.outFile) self.buttonBox = self.buttonBox.button( QDialogButtonBox.Ok ) self.progressBar.setValue(0)
def __init__(self, parent, plugin): QDialog.__init__(self, parent) self.setupUi(self) self.plugin = plugin self.mResult = "" self.progressBar.setRange(0, 0) self.progressBar.setFormat("%p%") self.labelName.setText(plugin["name"]) self.buttonBox.clicked.connect(self.abort) url = QUrl(plugin["download_url"]) fileName = plugin["filename"] tmpDir = QDir.tempPath() tmpPath = QDir.cleanPath(tmpDir + "/" + fileName) self.file = QFile(tmpPath) self.request = QNetworkRequest(url) authcfg = repositories.all()[plugin["zip_repository"]]["authcfg"] if authcfg and isinstance(authcfg, str): if not QgsAuthManager.instance().updateNetworkRequest( self.request, authcfg.strip()): self.mResult = self.tr( "Update of network request with authentication " "credentials FAILED for configuration '{0}'").format(authcfg) self.request = None if self.request is not None: self.reply = QgsNetworkAccessManager.instance().get(self.request) self.reply.downloadProgress.connect(self.readProgress) self.reply.finished.connect(self.requestFinished) self.stateChanged(4)
def __init__(self, iface,layer_name): QDialog.__init__(self, iface.mainWindow()) self.iface = iface # Set up the user interface from Designer. self.setupUi(self) self.layer_name = layer_name # start definition self.POWER_P_emission_comboBoxes_dict = {'POWER_P_gen' : self.POWER_P_L_gen_comboBox, 'POWER_P_day' : self.POWER_P_L_day_comboBox, 'POWER_P_eve' : self.POWER_P_L_eve_comboBox, 'POWER_P_nig' : self.POWER_P_L_nig_comboBox } self.all_emission_comboBoxes = [self.POWER_P_L_gen_comboBox, self.POWER_P_L_day_comboBox, self.POWER_P_L_eve_comboBox, self.POWER_P_L_nig_comboBox] self.source_checkBoxes = [self.POWER_P_L_gen_checkBox,self.POWER_P_L_day_checkBox,self.POWER_P_L_eve_checkBox,self.POWER_P_L_nig_checkBox] self.source_POWER_P_period_checkBoxes = [self.POWER_P_L_day_checkBox,self.POWER_P_L_eve_checkBox,self.POWER_P_L_nig_checkBox] # end definitions self.source_fields_update() for source_checkBox in self.source_checkBoxes: source_checkBox.setChecked(0) source_checkBox.toggled.connect(self.source_checkBox_update) self.POWER_P_L_gen_checkBox.toggled.connect(self.source_checkBox_update) self.setToolTips() self.reload_settings()
def __init__(self): """Constructor for the dialog. """ QDialog.__init__(self) self.setupUi(self) self.comboBox.addItem('ESRI shape file') self.comboBox.addItem('Comma separated value (CSV)') self.comboBox.addItem('SQLite database') self.comboBox.addItem('Copy complete database') # self.comboBox.addItem('INSPIRE') self.comboBox.currentIndexChanged.connect(self.seler) self.comboBox_2.addItem(';') self.comboBox_2.addItem(',') self.comboBox_2.addItem('tab') self.tabWidget.setTabEnabled(0, False) self.tabWidget.setTabEnabled(1, False) self.seler() self.toolButton.clicked.connect(self.filer)
def __init__(self, model): QDialog.__init__(self) # Set up the user interface from Designer. self.ui = uic.loadUi(ui_file, self) self.resultModel = model self.constraintTableView.setModel(self.resultModel) self.constraintTableView.resizeColumnsToContents()
def accept(self): layer = self.get_current_layer() label = self.autoLabelCheckBox.isChecked() layerout = self.layerNameLine.text() self.UnitsComboBox.setCurrentIndex(self.UnitsComboBox.findData(layer.crs().mapUnits())) distance = self.distanceSpinBox.value() startpoint = self.startSpinBox.value() endpoint = self.endSpinBox.value() selected_only = self.selectOnlyRadioBtn.isChecked() force = self.forceLastCheckBox.isChecked() fo_fila = self.force_fl_CB.isChecked() divide = self.divideSpinBox.value() decimal = self.decimalSpinBox.value() projection_setting_key = "Projections/defaultBehaviour" old_projection_setting = self.qgisSettings.value(projection_setting_key) self.qgisSettings.setValue(projection_setting_key, "useGlobal") self.qgisSettings.sync() points_along_line( layerout, startpoint, endpoint, distance, label, layer, selected_only, force, fo_fila, divide, decimal) self.qgisSettings.setValue(projection_setting_key, old_projection_setting) QDialog.accept(self)
def __init__(self): """Constructor for the dialog. """ QDialog.__init__(self) self.setupUi(self) self.btnsave = self.buttonBox.button(QDialogButtonBox.Save) self.saveCtrl() re = QRegExp('[0-9.]+') val = QRegExpValidator(re) self.lineEdit.setValidator(val) self.lineEdit_2.setValidator(val) self.toolButton.setToolTip('Degree - decimal conversion') self.toolButton.clicked.connect(self.trafo) self.lineEdit_3.textChanged.connect(self.saveCtrl) self.lineEdit_5.textChanged.connect(self.saveCtrl) self.comboBox.currentIndexChanged.connect(self.saveCtrl) self.funcs = VetEpiGISFuncs()
def __init__(self, title, message, errors, username, parent=None): QDialog.__init__(self, parent) self.setWindowTitle(title) self.verticalLayout = QVBoxLayout(self) self.label = QLabel(message, self) self.verticalLayout.addWidget(self.label) self.plainTextEdit = QPlainTextEdit(self) self.plainTextEdit.setPlainText(errors) self.plainTextEdit.setReadOnly(True) self.verticalLayout.addWidget(self.plainTextEdit) self.buttonBox = QDialogButtonBox(self) self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Close) self.verticalLayout.addWidget(self.buttonBox) self.reportButton = self.buttonBox.addButton(self.tr("Report error"), QDialogButtonBox.ActionRole) self.reportButton.clicked.connect(self.__reportError) self.buttonBox.accepted.connect(self.accept) self.buttonBox.rejected.connect(self.reject) self.username = username self.metadata = MetaData()
def closeEvent(self, event): del self.previewDim # cancello il canvans di preview della quota chiamato QadPreviewDim return QDialog.closeEvent(self, event)
def accept(self): self.mode = self.cmbFillType.currentIndex() self.param_index = self.cmbParameters.currentIndex() QDialog.accept(self)
def accept(self): self.descriptions[self.currentName] = str(self.text.toPlainText()) QDialog.accept(self)
def reject(self): self.descriptions = None QDialog.reject(self)
def reject(self): self.executed = False QDialog.reject(self)
def accept(self): description = str(self.nameTextBox.text()) if description.strip() == '': QMessageBox.warning(self, self.tr('Unable to define parameter'), self.tr('Invalid parameter name')) return if self.param is None: validChars = \ 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' safeName = ''.join(c for c in description if c in validChars) name = safeName.lower() i = 2 while self.alg.parameterDefinition(name): name = safeName.lower() + str(i) i += 1 else: name = self.param.name() if (self.paramType == parameters.PARAMETER_BOOLEAN or isinstance(self.param, QgsProcessingParameterBoolean)): self.param = QgsProcessingParameterBoolean(name, description, self.state.isChecked()) elif (self.paramType == parameters.PARAMETER_TABLE_FIELD or isinstance(self.param, QgsProcessingParameterField)): if self.parentCombo.currentIndex() < 0: QMessageBox.warning( self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return parent = self.parentCombo.currentData() datatype = self.datatypeCombo.currentData() default = self.defaultTextBox.text() if not default: default = None self.param = QgsProcessingParameterField( name, description, defaultValue=default, parentLayerParameterName=parent, type=datatype, allowMultiple=self.multipleCheck.isChecked()) elif (self.paramType == parameters.PARAMETER_BAND or isinstance(self.param, QgsProcessingParameterBand)): if self.parentCombo.currentIndex() < 0: QMessageBox.warning( self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return parent = self.parentCombo.currentData() self.param = QgsProcessingParameterBand(name, description, None, parent) elif (self.paramType == parameters.PARAMETER_MAP_LAYER or isinstance(self.param, QgsProcessingParameterMapLayer)): self.param = QgsProcessingParameterMapLayer(name, description) elif (self.paramType == parameters.PARAMETER_RASTER or isinstance(self.param, QgsProcessingParameterRasterLayer)): self.param = QgsProcessingParameterRasterLayer(name, description) elif (self.paramType == parameters.PARAMETER_TABLE or isinstance(self.param, QgsProcessingParameterVectorLayer)): self.param = QgsProcessingParameterVectorLayer( name, description, [self.shapetypeCombo.currentData()]) elif (self.paramType == parameters.PARAMETER_VECTOR or isinstance(self.param, QgsProcessingParameterFeatureSource)): self.param = QgsProcessingParameterFeatureSource( name, description, [self.shapetypeCombo.currentData()]) elif (self.paramType == parameters.PARAMETER_MULTIPLE or isinstance(self.param, QgsProcessingParameterMultipleLayers)): self.param = QgsProcessingParameterMultipleLayers( name, description, self.datatypeCombo.currentData()) elif (self.paramType == parameters.PARAMETER_NUMBER or isinstance(self.param, QgsProcessingParameterNumber)): try: self.param = QgsProcessingParameterNumber( name, description, QgsProcessingParameterNumber.Double, self.defaultTextBox.text()) vmin = self.minTextBox.text().strip() if not vmin == '': self.param.setMinimum(float(vmin)) vmax = self.maxTextBox.text().strip() if not vmax == '': self.param.setMaximum(float(vmax)) except: QMessageBox.warning( self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return elif (self.paramType == parameters.PARAMETER_EXPRESSION or isinstance(self.param, QgsProcessingParameterExpression)): parent = self.parentCombo.currentData() self.param = QgsProcessingParameterExpression( name, description, str(self.defaultEdit.expression()), parent) elif (self.paramType == parameters.PARAMETER_STRING or isinstance(self.param, QgsProcessingParameterString)): self.param = QgsProcessingParameterString( name, description, str(self.defaultTextBox.text())) elif (self.paramType == parameters.PARAMETER_EXTENT or isinstance(self.param, QgsProcessingParameterExtent)): self.param = QgsProcessingParameterExtent(name, description) elif (self.paramType == parameters.PARAMETER_FILE or isinstance(self.param, QgsProcessingParameterFile)): isFolder = self.fileFolderCombo.currentIndex() == 1 self.param = QgsProcessingParameterFile( name, description, QgsProcessingParameterFile.Folder if isFolder else QgsProcessingParameterFile.File) elif (self.paramType == parameters.PARAMETER_POINT or isinstance(self.param, QgsProcessingParameterPoint)): self.param = QgsProcessingParameterPoint( name, description, str(self.defaultTextBox.text())) elif (self.paramType == parameters.PARAMETER_CRS or isinstance(self.param, QgsProcessingParameterCrs)): self.param = QgsProcessingParameterCrs( name, description, self.selector.crs().authid()) else: from processing.core.Processing import Processing param = Processing.registeredParameters()[self.paramType] self.param = param['parameter'](name, description, None) self.param.setMetadata(param['metadata']) if not self.requiredCheck.isChecked(): self.param.setFlags( self.param.flags() | QgsProcessingParameterDefinition.FlagOptional) settings = QgsSettings() settings.setValue( "/Processing/modelParametersDefinitionDialogGeometry", self.saveGeometry()) QDialog.accept(self)
def reject(self): self.mode = None self.param_index = None QDialog.reject(self)
def reject(self): self.selectedoptions = None QDialog.reject(self)
def reject(self): """back out of dialogue""" QDialog.reject(self) self.rubber_band.reset()
def __init__(self, iface): """init window""" QDialog.__init__(self) self.setupUi(self) self.iface = iface self.map = iface.mapCanvas() self.settings = QgsSettings() self.catalog = None self.catalog_url = None self.catalog_username = None self.catalog_password = None self.context = StaticContext() self.leKeywords.setShowSearchIcon(True) self.leKeywords.setPlaceholderText(self.tr('Search keywords')) self.setWindowTitle(self.tr('MetaSearch')) self.rubber_band = QgsRubberBand(self.map, True) # True = a polygon self.rubber_band.setColor(QColor(255, 0, 0, 75)) self.rubber_band.setWidth(5) # form inputs self.startfrom = 1 self.maxrecords = 10 self.timeout = 10 self.disable_ssl_verification = False self.constraints = [] # Servers tab self.cmbConnectionsServices.activated.connect(self.save_connection) self.cmbConnectionsSearch.activated.connect(self.save_connection) self.btnServerInfo.clicked.connect(self.connection_info) self.btnAddDefault.clicked.connect(self.add_default_connections) self.btnCapabilities.clicked.connect(self.show_xml) self.tabWidget.currentChanged.connect(self.populate_connection_list) # server management buttons self.btnNew.clicked.connect(self.add_connection) self.btnEdit.clicked.connect(self.edit_connection) self.btnDelete.clicked.connect(self.delete_connection) self.btnLoad.clicked.connect(self.load_connections) self.btnSave.clicked.connect(save_connections) # Search tab self.treeRecords.itemSelectionChanged.connect(self.record_clicked) self.treeRecords.itemDoubleClicked.connect(self.show_metadata) self.btnSearch.clicked.connect(self.search) self.leKeywords.returnPressed.connect(self.search) # prevent dialog from closing upon pressing enter self.buttonBox.button(QDialogButtonBox.Close).setAutoDefault(False) # launch help from button self.buttonBox.helpRequested.connect(self.help) self.btnCanvasBbox.setAutoDefault(False) self.btnCanvasBbox.clicked.connect(self.set_bbox_from_map) self.btnGlobalBbox.clicked.connect(self.set_bbox_global) # navigation buttons self.btnFirst.clicked.connect(self.navigate) self.btnPrev.clicked.connect(self.navigate) self.btnNext.clicked.connect(self.navigate) self.btnLast.clicked.connect(self.navigate) self.mActionAddWms.triggered.connect(self.add_to_ows) self.mActionAddWfs.triggered.connect(self.add_to_ows) self.mActionAddWcs.triggered.connect(self.add_to_ows) self.mActionAddAms.triggered.connect(self.add_to_ows) self.mActionAddAfs.triggered.connect(self.add_to_ows) self.mActionAddGisFile.triggered.connect(self.add_gis_file) self.btnShowXml.clicked.connect(self.show_xml) self.manageGui()
def setRoundness(self, roundness): self.mRoundness = min(0.0, max(100, roundness)) def setColor(self, color): self.mColor = color def setRevolutionsPerSecond(self, revolutionsPerSecond): self.mRevolutionsPerSecond = revolutionsPerSecond self.updateTimer() def setTrailFadePercentage(self, trail): self.mTrailFadePercentage = trail def setMinimumTrailOpacity(self, minimumTrailOpacity): self.mMinimumTrailOpacity = minimumTrailOpacity if __name__ == '__main__': import sys from PyQt5.QtWidgets import QApplication from qgis.PyQt.QtWidgets import QDialog from qgis.PyQt.QtCore import QRect app = QApplication(sys.argv) dial = QDialog() w = QtWaitingSpinner(dial) dial.show() w.start() QTimer.singleShot(5000, w.stop) sys.exit(app.exec_())
def __init__(self, interface, confHandler): """ :type confHandler: configHandler.ConfigHandler """ QDialog.__init__(self, interface.mainWindow()) self.iface = interface # Management of Parameters and settings self.confHandler = confHandler self.confHandler.setDialog(self) self.profile = self.confHandler.project.profile self.poles = self.confHandler.project.poles # Max distance the anchors can move away from initial position self.anchorBuffer = self.confHandler.project.heightSource.buffer # Load data self.originalData = {} self.result = {} self.cableline = {} self.status = None self.doReRun = False # Setup GUI from UI-file self.setupUi(self) self.drawTool = MapMarkerTool(self.iface.mapCanvas()) # Create plot self.plot = AdjustmentPlot(self) # Pan/Zoom tools for plot, pan already active tbar = MyNavigationToolbar(self.plot, self) tbar.pan() self.plot.setToolbar(tbar) self.plotLayout.addWidget(self.plot) self.plotLayout.addWidget(tbar, alignment=Qt.AlignHCenter | Qt.AlignTop) # Fill tab widget with data self.poleLayout = CustomPoleWidget(self.tabPoles, self.poleVGrid, self.poles) # self.poleLayout.sig_zoomIn.connect(self.zoomToPole) # self.poleLayout.sig_zoomOut.connect(self.zoomOut) self.poleLayout.sig_createPole.connect(self.addPole) self.poleLayout.sig_updatePole.connect(self.updatePole) self.poleLayout.sig_deletePole.connect(self.deletePole) # Threshold (thd) tab thdTblSize = [5, 6] self.thdLayout = AdjustmentDialogThresholds(self, thdTblSize) self.thdLayout.sig_clickedRow.connect(self.showThresholdInPlot) self.selectedThdRow = None self.thdUpdater = ThresholdUpdater(self.thdLayout, thdTblSize, self.showThresholdInPlot) self.paramLayout = AdjustmentDialogParams(self, self.confHandler.params) # Project header self.prHeaderFields = { 'PrVerf': self.fieldPrVerf, 'PrNr': self.fieldPrNr, 'PrGmd': self.fieldPrGmd, 'PrWald': self.fieldPrWald, 'PrBemerkung': self.fieldPrBemerkung, } # Thread for instant recalculation when poles or parameters are changed self.timer = QTimer() self.configurationHasChanged = False self.isRecalculating = False self.unsavedChanges = True # Save dialog self.saveDialog = DialogOutputOptions(self, self.confHandler) # Connect signals self.btnClose.clicked.connect(self.onClose) self.btnSave.clicked.connect(self.onSave) self.btnBackToStart.clicked.connect(self.onReturnToStart) for field in self.prHeaderFields.values(): field.textChanged.connect(self.onPrHeaderChanged) self.infoQ.clicked.connect(self.onShowInfoFieldQ)
def accept(self): self.__renderer = self.__sw.currentWidget().renderer().clone() self.update() return QDialog.accept(self)
def canvasReleaseEvent(self, event): """ Canvas is released. This means: * start digitizing * stop digitizing (create a rectangle * if the Ctrl-modifier is pressed, ask for the rectangle width :param event: coordinates etc. """ if event.button() == Qt.RightButton: self.deactivate() else: mousepos = self.canvas.getCoordinateTransform()\ .toMapCoordinates(event.pos().x(), event.pos().y()) self.rubberband.addPoint(mousepos) if self.firstPoint: # If the first point was set before, we are doing the second one lp1 = self.rubberband.asGeometry().asPolyline()[0] lp2 = self.rubberband.asGeometry().asPolyline()[1] width = 0.2 if QApplication.keyboardModifiers() & Qt.ControlModifier: dlg = QDialog() dlg.setLayout(QGridLayout()) dlg.layout().addWidget(QLabel(self.tr('Enter width'))) txt = QLineEdit('0.2') dlg.layout().addWidget(txt) bb = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) dlg.layout().addWidget(bb) bb.accepted.connect(dlg.accept) bb.rejected.connect(dlg.reject) if dlg.exec_(): try: width = float(txt.text()) except ValueError: width = 0.2 length = math.sqrt(math.pow(lp1.x() - lp2.x(), 2) + math.pow(lp1.y() - lp2.y(), 2)) xd = lp2.x() - lp1.x() yd = lp2.y() - lp1.y() pt1 = QgsPointXY(lp1.x() + width * (yd / length), lp1.y() - width * (xd / length)) pt2 = QgsPointXY(lp1.x() - width * (yd / length), lp1.y() + width * (xd / length)) pt3 = QgsPointXY(lp2.x() - width * (yd / length), lp2.y() + width * (xd / length)) pt4 = QgsPointXY(lp2.x() + width * (yd / length), lp2.y() - width * (xd / length)) self.geometry = QgsGeometry.fromPolygon([[pt1, pt2, pt3, pt4, pt1]]) self.geometryDigitized.emit() self.firstPoint = mousepos
def accept(self): description = self.nameTextBox.text() if description.strip() == '': QMessageBox.warning(self, self.tr('Unable to define parameter'), self.tr('Invalid parameter name')) return if self.param is None: validChars = \ 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' safeName = ''.join(c for c in description if c in validChars) name = safeName.lower() i = 2 while self.alg.parameterDefinition(name): name = safeName.lower() + str(i) i += 1 else: name = self.param.name() if (self.paramType == parameters.PARAMETER_BOOLEAN or isinstance(self.param, QgsProcessingParameterBoolean)): self.param = QgsProcessingParameterBoolean(name, description, self.state.isChecked()) elif (self.paramType == parameters.PARAMETER_TABLE_FIELD or isinstance(self.param, QgsProcessingParameterField)): if self.parentCombo.currentIndex() < 0: QMessageBox.warning( self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return parent = self.parentCombo.currentData() datatype = self.datatypeCombo.currentData() default = self.defaultTextBox.text() if not default: default = None self.param = QgsProcessingParameterField( name, description, defaultValue=default, parentLayerParameterName=parent, type=datatype, allowMultiple=self.multipleCheck.isChecked()) elif (self.paramType == parameters.PARAMETER_BAND or isinstance(self.param, QgsProcessingParameterBand)): if self.parentCombo.currentIndex() < 0: QMessageBox.warning( self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return parent = self.parentCombo.currentData() self.param = QgsProcessingParameterBand(name, description, None, parent) elif (self.paramType == parameters.PARAMETER_LAYOUTITEM or isinstance(self.param, QgsProcessingParameterLayoutItem)): if self.parentCombo.currentIndex() < 0: QMessageBox.warning( self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return parent = self.parentCombo.currentData() self.param = QgsProcessingParameterLayoutItem( name, description, None, parent) elif (self.paramType == parameters.PARAMETER_MAP_LAYER or isinstance(self.param, QgsProcessingParameterMapLayer)): self.param = QgsProcessingParameterMapLayer(name, description) elif (self.paramType == parameters.PARAMETER_RASTER or isinstance(self.param, QgsProcessingParameterRasterLayer)): self.param = QgsProcessingParameterRasterLayer(name, description) elif (self.paramType == parameters.PARAMETER_TABLE or isinstance(self.param, QgsProcessingParameterVectorLayer)): self.param = QgsProcessingParameterVectorLayer( name, description, [self.shapetypeCombo.currentData()]) elif (self.paramType == parameters.PARAMETER_VECTOR or isinstance(self.param, QgsProcessingParameterFeatureSource)): self.param = QgsProcessingParameterFeatureSource( name, description, [self.shapetypeCombo.currentData()]) elif (self.paramType == parameters.PARAMETER_MULTIPLE or isinstance(self.param, QgsProcessingParameterMultipleLayers)): self.param = QgsProcessingParameterMultipleLayers( name, description, self.datatypeCombo.currentData()) elif (self.paramType == parameters.PARAMETER_DISTANCE or isinstance(self.param, QgsProcessingParameterDistance)): self.param = QgsProcessingParameterDistance( name, description, self.defaultTextBox.text()) try: vmin = self.minTextBox.text().strip() if not vmin == '': self.param.setMinimum(float(vmin)) vmax = self.maxTextBox.text().strip() if not vmax == '': self.param.setMaximum(float(vmax)) except: QMessageBox.warning( self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return if self.parentCombo.currentIndex() < 0: QMessageBox.warning( self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return parent = self.parentCombo.currentData() if parent: self.param.setParentParameterName(parent) elif (self.paramType == parameters.PARAMETER_SCALE or isinstance(self.param, QgsProcessingParameterScale)): self.param = QgsProcessingParameterScale( name, description, self.defaultTextBox.text()) elif (self.paramType == parameters.PARAMETER_NUMBER or isinstance(self.param, QgsProcessingParameterNumber)): type = self.type_combo.currentData() self.param = QgsProcessingParameterNumber( name, description, type, self.defaultTextBox.text()) try: vmin = self.minTextBox.text().strip() if not vmin == '': self.param.setMinimum(float(vmin)) vmax = self.maxTextBox.text().strip() if not vmax == '': self.param.setMaximum(float(vmax)) except: QMessageBox.warning( self, self.tr('Unable to define parameter'), self.tr('Wrong or missing parameter values')) return elif (self.paramType == parameters.PARAMETER_EXPRESSION or isinstance(self.param, QgsProcessingParameterExpression)): parent = self.parentCombo.currentData() self.param = QgsProcessingParameterExpression( name, description, str(self.defaultEdit.expression()), parent) elif (self.paramType == parameters.PARAMETER_STRING or isinstance(self.param, QgsProcessingParameterString)): self.param = QgsProcessingParameterString( name, description, str(self.defaultTextBox.text())) elif (self.paramType == parameters.PARAMETER_EXTENT or isinstance(self.param, QgsProcessingParameterExtent)): self.param = QgsProcessingParameterExtent(name, description) elif (self.paramType == parameters.PARAMETER_FILE or isinstance(self.param, QgsProcessingParameterFile)): isFolder = self.fileFolderCombo.currentIndex() == 1 self.param = QgsProcessingParameterFile( name, description, QgsProcessingParameterFile.Folder if isFolder else QgsProcessingParameterFile.File) elif (self.paramType == parameters.PARAMETER_POINT or isinstance(self.param, QgsProcessingParameterPoint)): self.param = QgsProcessingParameterPoint( name, description, str(self.defaultTextBox.text())) elif (self.paramType == parameters.PARAMETER_CRS or isinstance(self.param, QgsProcessingParameterCrs)): self.param = QgsProcessingParameterCrs( name, description, self.selector.crs().authid()) elif (self.paramType == parameters.PARAMETER_ENUM or isinstance(self.param, QgsProcessingParameterEnum)): self.param = QgsProcessingParameterEnum( name, description, self.widget.options(), self.widget.allowMultiple(), self.widget.defaultOptions()) elif (self.paramType == parameters.PARAMETER_MATRIX or isinstance(self.param, QgsProcessingParameterMatrix)): self.param = QgsProcessingParameterMatrix( name, description, hasFixedNumberRows=self.widget.fixedRows(), headers=self.widget.headers(), defaultValue=self.widget.value()) # Destination parameter elif (isinstance(self.param, QgsProcessingParameterFeatureSink)): self.param = QgsProcessingParameterFeatureSink( name=name, description=self.param.description(), type=self.param.dataType(), defaultValue=self.defaultWidget.getValue()) elif (isinstance(self.param, QgsProcessingParameterFileDestination)): self.param = QgsProcessingParameterFileDestination( name=name, description=self.param.description(), fileFilter=self.param.fileFilter(), defaultValue=self.defaultWidget.getValue()) elif (isinstance(self.param, QgsProcessingParameterFolderDestination)): self.param = QgsProcessingParameterFolderDestination( name=name, description=self.param.description(), defaultValue=self.defaultWidget.getValue()) elif (isinstance(self.param, QgsProcessingParameterRasterDestination)): self.param = QgsProcessingParameterRasterDestination( name=name, description=self.param.description(), defaultValue=self.defaultWidget.getValue()) elif (isinstance(self.param, QgsProcessingParameterVectorDestination)): self.param = QgsProcessingParameterVectorDestination( name=name, description=self.param.description(), type=self.param.dataType(), defaultValue=self.defaultWidget.getValue()) else: if self.paramType: typeId = self.paramType else: typeId = self.param.type() paramTypeDef = QgsApplication.instance().processingRegistry( ).parameterType(typeId) if not paramTypeDef: msg = self.tr( 'The parameter `{}` is not registered, are you missing a required plugin?' .format(typeId)) raise UndefinedParameterException(msg) self.param = paramTypeDef.create(name) self.param.setDescription(description) self.param.setMetadata(paramTypeDef.metadata()) if not self.requiredCheck.isChecked(): self.param.setFlags( self.param.flags() | QgsProcessingParameterDefinition.FlagOptional) else: self.param.setFlags( self.param.flags() & ~QgsProcessingParameterDefinition.FlagOptional) settings = QgsSettings() settings.setValue( "/Processing/modelParametersDefinitionDialogGeometry", self.saveGeometry()) QDialog.accept(self)
def __init__(self, parent=None, qgis_utils=None, conn_manager=None): QDialog.__init__(self, parent) self.setupUi(self) self.logger = Logger() self.conn_manager = conn_manager self._db = None self.qgis_utils = qgis_utils self.db_source = COLLECTED_DB_SOURCE # default db source self._required_models = list() self._tab_pages_list = list() self.init_db_engine = None self._action_type = None self.dbs_supported = ConfigDbSupported() self.online_models_radio_button.setChecked(True) self.online_models_radio_button.toggled.connect( self.model_provider_toggle) self.custom_model_directories_line_edit.setText("") self.custom_models_dir_button.clicked.connect( self.show_custom_model_dir) self.custom_model_directories_line_edit.setVisible(False) self.custom_models_dir_button.setVisible(False) # Set connections self.buttonBox.accepted.disconnect() self.buttonBox.accepted.connect(self.accepted) self.buttonBox.helpRequested.connect(self.show_help) self.finished.connect(self.finished_slot) self.btn_test_connection.clicked.connect(self.test_connection) self.btn_test_ladm_col_structure.clicked.connect( self.test_ladm_col_structure) self.btn_test_service.clicked.connect(self.test_service) self.btn_test_service_transitional_system.clicked.connect( self.test_service_transitional_system) self.btn_default_value_sources.clicked.connect( self.set_default_value_source_service) self.btn_default_value_transitional_system.clicked.connect( self.set_default_value_transitional_system_service) self.chk_use_roads.toggled.connect(self.update_images_state) self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.layout().addWidget(self.bar, 0, 0, Qt.AlignTop) self.cbo_db_engine.clear() self._lst_db = self.dbs_supported.get_db_factories() self._lst_panel = dict() for key, value in self._lst_db.items(): self.cbo_db_engine.addItem(value.get_name(), key) self._lst_panel[key] = value.get_config_panel(self) self._lst_panel[key].notify_message_requested.connect( self.show_message) self.db_layout.addWidget(self._lst_panel[key]) self.db_engine_changed() # Trigger some default behaviours self.restore_db_source_settings( ) # restore settings with default db source self.restore_settings() self.roles = Role_Registry() self.load_roles() self.cbo_db_engine.currentIndexChanged.connect(self.db_engine_changed) self.rejected.connect(self.close_dialog)
def __init__(self): """Constructor for the dialog. """ QDialog.__init__(self) self.setupUi(self) self.btnsave = self.buttonBox.button(QDialogButtonBox.Save) # self.plugin_dir = os.path.dirname(__file__) # self.db = QSqlDatabase.addDatabase('QSPATIALITE') # self.db.setDatabaseName(os.path.join(self.plugin_dir, 'db.sqlite')) self.lrs = [] self.tlrs = [] self.toolButton_species_add.setToolTip('Add new cases') self.toolButton_species_add.clicked.connect(self.addNew) self.toolButton_2_species_remove.setToolTip('Delete selected row') self.toolButton_2_species_remove.clicked.connect(self.removeRec) self.toolButton_5_species_dots.setToolTip('Edit selected row') self.toolButton_5_species_dots.clicked.connect(self.editRec) self.toolButton_3_dms.setToolTip('Degree - decimal conversion') self.toolButton_3_dms.clicked.connect(self.trafo) self.comboBox_3_status.addItem('') self.comboBox_3_status.addItem('Suspected') self.comboBox_3_status.addItem('Confirmed') self.comboBox_3_status.addItem('Not confirmed') self.comboBox_3_status.addItem('Expired') self.comboBox_4_large_scale.addItem('') self.comboBox_4_large_scale.addItem('No') self.comboBox_4_large_scale.addItem('Yes') re = QRegExp('[0-9]+') val = QRegExpValidator(re) self.lineEdit_4_year.setValidator(val) self.lineEdit_6_num_animals.setValidator(val) re2 = QRegExp('[0-9.]+') val2 = QRegExpValidator(re2) self.lineEdit_longitude.setValidator(val2) self.lineEdit_2_latitude.setValidator(val2) # self.db.open() # query = QSqlQuery("select disease from xdiseases where lang='en' order by disease") # query.exec_() # while query.next(): # self.comboBox_2.addItem(query.value(0)) # # self.db.close() # # fnt = QFont() # fnt = self.tableWidget.horizontalHeader().font() # fnt.setBold(True) # fnt.setItalic(True) # # fnt.setFamily(u"DejaVu Sans") # # fnt.setPointSize(18) # # fnt.setWeight(8) # self.tableWidget.horizontalHeader().setFont(fnt) self.checkBox_dates_suspect.clicked.connect(self.date1set) self.checkBox_2_dates_confirmation.clicked.connect(self.date2set) self.checkBox_3_dates_expiration.clicked.connect(self.date3set) self.checkBox_dates_suspect.setChecked(False) self.checkBox_2_dates_confirmation.setChecked(False) self.checkBox_3_dates_expiration.setChecked(False) self.dateEdit_dates_suspect.setEnabled(False) self.dateEdit_2_dates_confirmation.setEnabled(False) self.dateEdit_3_dates_expiration.setEnabled(False) self.funcs = VetEpiGISFuncs() self.lineEdit_3_id.textChanged.connect(self.saveCtrl) self.lineEdit_4_year.textChanged.connect(self.saveCtrl) self.lineEdit_5_code.textChanged.connect(self.saveCtrl) self.comboBox_2_disease.currentIndexChanged.connect(self.saveCtrl) self.comboBox_3_status.currentIndexChanged.connect(self.saveCtrl) self.comboBox_4_large_scale.currentIndexChanged.connect(self.saveCtrl) self.lineEdit_6_num_animals.setText(str(1)) self.saveCtrl()
def reject(self): """back out of dialogue""" QDialog.reject(self)
def __init__(self, base_config, parent=None): QDialog.__init__(self, parent) self.setupUi(self) self.db_simple_factory = DbSimpleFactory() QgsGui.instance().enableAutoGeometryRestore(self); self.buttonBox.accepted.disconnect() self.buttonBox.clicked.connect(self.button_box_clicked) self.buttonBox.clear() self.buttonBox.addButton(QDialogButtonBox.Cancel) self.export_button_name = self.tr('Export') self.export_without_validate_button_name = self.tr('Export without validation') self.buttonBox.addButton(self.export_button_name, QDialogButtonBox.AcceptRole) self.buttonBox.addButton(QDialogButtonBox.Help) self.buttonBox.helpRequested.connect(self.help_requested) self.xtf_file_browse_button.clicked.connect( make_save_file_selector(self.xtf_file_line_edit, title=self.tr('Save in XTF Transfer File'), file_filter=self.tr('XTF Transfer File (*.xtf);;Interlis 1 Transfer File (*.itf);;XML (*.xml);;GML (*.gml)'), extension='.xtf', extensions=['.' + ext for ext in self.ValidExtensions])) self.xtf_file_browse_button.clicked.connect( self.xtf_browser_opened_to_true) self.xtf_browser_was_opened = False self.type_combo_box.clear() self._lst_panel = dict() for db_id in self.db_simple_factory.get_db_list(False): self.type_combo_box.addItem(displayDbIliMode[db_id], db_id) db_factory = self.db_simple_factory.create_factory(db_id) item_panel = db_factory.get_config_panel(self, DbActionType.EXPORT) self._lst_panel[db_id] = item_panel self.db_layout.addWidget(item_panel) self.validators = Validators() fileValidator = FileValidator(pattern=['*.' + ext for ext in self.ValidExtensions], allow_non_existing=True) self.xtf_file_line_edit.setValidator(fileValidator) self.xtf_file_line_edit.textChanged.connect( self.validators.validate_line_edits) self.xtf_file_line_edit.textChanged.connect( self.xtf_browser_opened_to_false) self.xtf_file_line_edit.textChanged.emit( self.xtf_file_line_edit.text()) # Remove export without validate button when xtf change self.xtf_file_line_edit.textChanged.connect( self.remove_export_without_validate_button) #refresh the models on changing values but avoid massive db connects by timer self.refreshTimer = QTimer() self.refreshTimer.setSingleShot(True) self.refreshTimer.timeout.connect(self.refresh_models) for key, value in self._lst_panel.items(): value.notify_fields_modified.connect(self.request_for_refresh_models) self.validate_data = True # validates exported data by default, We use --disableValidation when is False self.base_configuration = base_config self.restore_configuration() self.export_models_model = ExportModels() self.refresh_models() self.type_combo_box.currentIndexChanged.connect(self.type_changed)
def __init__(self, iface, parent=None): """Constructor.""" QDialog.__init__(self, parent) self.setupUi(self) self.iface = iface self.query_menu_index = 1 # Table mapping # Explaining quickly, these letters are referring to the panel # in the UI: # qq : Quick Query # q : Query # f : file self.external_panels = { Panels.QuickQuery: QuickQueryPanel(self), Panels.Query: QueryPanel(self), Panels.File: OsmFilePanel(self), Panels.Configuration: ConfigurationPanel(self), } self.places_edits = { Panels.QuickQuery: self.line_place_qq, Panels.Query: self.line_place_q, } self.query_type_buttons = { Panels.QuickQuery: self.combo_query_type_qq, Panels.Query: self.combo_query_type_q, } self.layers_buttons = { Panels.QuickQuery: self.combo_extent_layer_qq, Panels.Query: self.combo_extent_layer_q, } self.run_buttons = { Panels.QuickQuery: self.button_run_query_qq, Panels.Query: self.button_run_query_q, Panels.File: self.button_run_file, } self.output_buttons = { Panels.QuickQuery: [ self.checkbox_points_qq, self.checkbox_lines_qq, self.checkbox_multilinestrings_qq, self.checkbox_multipolygons_qq ], Panels.Query: [ self.checkbox_points_q, self.checkbox_lines_q, self.checkbox_multilinestrings_q, self.checkbox_multipolygons_q, ], Panels.File: [ self.checkbox_points_f, self.checkbox_lines_f, self.checkbox_multilinestrings_f, self.checkbox_multipolygons_f, ] } self.output_directories = { Panels.QuickQuery: self.output_directory_qq, Panels.Query: self.output_directory_q, Panels.File: self.output_directory_f } self.prefix_edits = { Panels.QuickQuery: self.line_file_prefix_qq, Panels.Query: self.line_file_prefix_q, Panels.File: self.line_file_prefix_file, } self.advanced_panels = { Panels.QuickQuery: self.advanced_qq, Panels.Query: self.advanced_q, } item = self.menu_widget.item(0) item.setIcon(QIcon(resources_path('icons', 'quick.png'))) item = self.menu_widget.item(1) item.setIcon(QIcon(resources_path('icons', 'edit.png'))) item = self.menu_widget.item(2) item.setIcon(QIcon(resources_path('icons', 'open.png'))) item = self.menu_widget.item(3) item.setIcon(QIcon(resources_path('icons', 'general.svg'))) item = self.menu_widget.item(4) item.setIcon(QIcon(resources_path('icons', 'info.png'))) self.label_gnu.setPixmap(QPixmap(resources_path('icons', 'gnu.png'))) # Set minimum width for the menu self.menu_widget.setMinimumWidth( self.menu_widget.sizeHintForColumn(0) + 10) self.progress_text.setText('') self.menu_widget.currentRowChanged['int'].connect( self.stacked_panels_widget.setCurrentIndex) for panel in self.external_panels.values(): panel.setup_panel() self.menu_widget.setCurrentRow(0)
def __init__(self, iface, base_config, parent=None): QDialog.__init__(self, parent) self.iface = iface self.setupUi(self) QgsGui.instance().enableAutoGeometryRestore(self) self.db_simple_factory = DbSimpleFactory() self.buttonBox.accepted.disconnect() self.buttonBox.clicked.connect(self.button_box_clicked) self.buttonBox.clear() self.buttonBox.addButton(QDialogButtonBox.Cancel) self.import_button_name = self.tr('Import Data') self.import_without_validate_button_name = self.tr( 'Import without validation') self.buttonBox.addButton(self.import_button_name, QDialogButtonBox.AcceptRole) self.buttonBox.addButton(QDialogButtonBox.Help) self.buttonBox.helpRequested.connect(self.help_requested) self.xtf_file_browse_button.clicked.connect( make_file_selector( self.xtf_file_line_edit, title=self.tr('Open Transfer or Catalog File'), file_filter=self. tr('Transfer File (*.xtf *.itf *.XTF *.ITF);;Catalogue File (*.xml *.XML *.xls *.XLS *.xlsx *.XLSX)' ))) self.type_combo_box.clear() self._lst_panel = dict() for db_id in self.db_simple_factory.get_db_list(False): self.type_combo_box.addItem(displayDbIliMode[db_id], db_id) db_factory = self.db_simple_factory.create_factory(db_id) item_panel = db_factory.get_config_panel(self, DbActionType.IMPORT_DATA) self._lst_panel[db_id] = item_panel self.db_layout.addWidget(item_panel) self.type_combo_box.currentIndexChanged.connect(self.type_changed) self.ili2db_options = Ili2dbOptionsDialog() self.ili2db_options_button.clicked.connect(self.ili2db_options.open) self.ili2db_options.finished.connect(self.fill_toml_file_info_label) self.multiple_models_dialog = MultipleModelsDialog(self) self.multiple_models_button.clicked.connect( self.multiple_models_dialog.open) self.multiple_models_dialog.accepted.connect( self.fill_models_line_edit) self.validate_data = True # validates imported data by default, We use --disableValidation when is False self.base_configuration = base_config self.restore_configuration() self.validators = Validators() fileValidator = FileValidator( pattern=['*.' + ext for ext in self.ValidExtensions]) self.xtf_file_line_edit.setValidator(fileValidator) self.ili_models_line_edit.setPlaceholderText( self.tr('[Search model in repository]')) self.ili_models_line_edit.textChanged.connect( self.complete_models_completer) self.ili_models_line_edit.punched.connect( self.complete_models_completer) self.xtf_file_line_edit.textChanged.connect( self.validators.validate_line_edits) self.xtf_file_line_edit.textChanged.emit( self.xtf_file_line_edit.text()) # Remove import without validate button when xtf changes self.xtf_file_line_edit.textChanged.connect( self.remove_import_without_validate_button) settings = QSettings() ilifile = settings.value('QgisModelBaker/ili2db/ilifile') self.ilicache = IliCache(base_config, ilifile or None) self.update_models_completer() self.ilicache.refresh()
def accepted(self): """ First check if connection to DB/schema is valid, if not, block the dialog. If valid, check it complies with LADM. If not, block the dialog. If it complies, we have two options: To emit db_connection changed or not. Finally, we store options in QSettings. """ ladm_col_schema = False db = self._get_db_connector_from_gui() test_level = EnumTestLevel.DB_SCHEMA if self._action_type == EnumDbActionType.SCHEMA_IMPORT: # Limit the validation (used in GeoPackage) test_level |= EnumTestLevel.SCHEMA_IMPORT res, code, msg = db.test_connection( test_level ) # No need to pass required_models, we don't test that much if res: if self._action_type != EnumDbActionType.SCHEMA_IMPORT: # Only check LADM-schema if we are not in an SCHEMA IMPORT. # We know in an SCHEMA IMPORT, at this point the schema is still not LADM. ladm_col_schema, code, msg = db.test_connection( EnumTestLevel.LADM, required_models=self._required_models) if not ladm_col_schema and self._action_type != EnumDbActionType.SCHEMA_IMPORT: self.show_message(msg, Qgis.Warning) return # Do not close the dialog else: self.show_message(msg, Qgis.Warning) return # Do not close the dialog # Connection is valid and complies with LADM current_db_engine = self.cbo_db_engine.currentData() if self._lst_panel[current_db_engine].state_changed( ) or self.init_db_engine != current_db_engine: # Emit db_connection_changed if self._db is not None: self._db.close_connection() self._db = db # Update db connect with new db conn self.conn_manager.set_db_connector_for_source( self._db, self.db_source) # Emmit signal when db source changes self.db_connection_changed.emit(self._db, ladm_col_schema, self.db_source) self.logger.debug( __name__, "Settings dialog emitted a db_connection_changed.") # Save settings from tabs other than database connection self.save_settings() QDialog.accept(self) # If active role changed, refresh the GUI selected_role = self.get_selected_role() if self.roles.get_active_role() != selected_role: self.logger.info( __name__, "The active role has changed from '{}' to '{}'.".format( self.roles.get_active_role(), selected_role)) self.roles.set_active_role(selected_role) self.active_role_changed.emit() self.close()
def __init__(self, iface, setupObject): QDialog.__init__(self) self.iface = iface self.setupUi(self) self.boundextBox.setEnabled(False) self.okButton.clicked.connect(lambda: self.setCreateMarxanInputFiles(setupObject))
def __init__(self): """Constructor for the dialog. """ QDialog.__init__(self) self.setupUi(self) self.btnok = self.buttonBox.button(QDialogButtonBox.Ok) self.toolButton.setToolTip('Add new cases') self.toolButton.clicked.connect(self.addNew) self.toolButton_2.setToolTip('Delete selected row') self.toolButton_2.clicked.connect(self.removeRec) # self.model = QSqlQueryModel() self.tablst = [] re = QRegExp('[a-z0-9\_]+') val = QRegExpValidator(re) self.lineEdit.setValidator(val) self.lineEdit.textChanged.connect(self.nameCtrl) # self.lineEdit.editingFinished.connect(self.nameCtrl) self.comboBox.currentIndexChanged.connect(self.nameCrea) self.comboBox_2.currentIndexChanged.connect(self.nameCrea) self.comboBox_3.addItem('') self.comboBox_3.addItem('Control') self.comboBox_3.addItem('Protection') self.comboBox_3.addItem('Surveillance') self.comboBox_3.addItem('Restriction') self.comboBox_3.addItem('Vaccination') # self.comboBox_3.addItem('Containment') # self.comboBox_3.addItem('Protection') # self.comboBox_3.addItem('Vaccination') self.comboBox_3.currentIndexChanged.connect(self.saveCtrl) self.comboBox_4.addItem('Intersections only') self.comboBox_4.addItem('Overlapped ROIs') self.comboBox_4.currentIndexChanged.connect(self.info) self.info() self.comboBox_5.addItem('') self.comboBox_5.addItem('Yes') self.comboBox_5.addItem('No') self.comboBox_6.addItem('') self.comboBox_6.addItem('Yes') self.comboBox_6.addItem('No') self.comboBox_7.addItem('') self.comboBox_7.addItem('Yes') self.comboBox_7.addItem('No') self.comboBox_8.addItem('') self.comboBox_8.addItem('Yes') self.comboBox_8.addItem('No') self.comboBox_9.addItem('') self.comboBox_9.addItem('Yes') self.comboBox_9.addItem('No') self.comboBox_10.addItem('') self.comboBox_10.addItem('Yes') self.comboBox_10.addItem('No') self.comboBox_11.addItem('') self.comboBox_11.addItem('Yes') self.comboBox_11.addItem('No') self.comboBox_12.addItem('') self.comboBox_12.addItem('Yes') self.comboBox_12.addItem('No')
def __init__(self, iface, db, qgis_utils, parent=None): QDialog.__init__(self) self.setupUi(self) self.iface = iface self.log = QgsApplication.messageLog() self._la_group_party_table = None self._members_table = None self._fraction_table = None self._col_party_layer = None self._db = db self.qgis_utils = qgis_utils self.help_strings = HelpStrings() self.data = {} # {t_id: [display_text, denominator, numerator]} self.current_selected_parties = [] # [t_ids] self.parties_to_group = {} # {t_id: [denominator, numerator]} # Fill combo of types la_group_party_type_table = self.qgis_utils.get_layer( self._db, LA_GROUP_PARTY_TYPE_TABLE, None, True) if la_group_party_type_table is None: self.iface.messageBar().pushMessage( "Asistente LADM_COL", QCoreApplication.translate( "CreateGroupPartyCadastreWizard", "Group Party Type Table couldn't be found... {}").format( self._db.get_description()), Qgis.Warning) return domain_key_index = la_group_party_type_table.fields().indexOf( DOMAIN_KEY_FIELD[self._db.mode]) domain_keys = list( la_group_party_type_table.uniqueValues(domain_key_index)) domain_keys.sort() self.cbo_group_type.addItems(domain_keys) self.txt_search_party.setText("") self.btn_select.setEnabled(False) self.btn_deselect.setEnabled(False) self.tbl_selected_parties.setColumnCount(3) self.tbl_selected_parties.setColumnWidth(0, 140) self.tbl_selected_parties.setColumnWidth(1, 90) self.tbl_selected_parties.setColumnWidth(2, 90) self.tbl_selected_parties.sortItems(0, Qt.AscendingOrder) self.txt_search_party.textEdited.connect(self.search) self.lst_all_parties.itemSelectionChanged.connect( self.selection_changed_all) self.tbl_selected_parties.itemSelectionChanged.connect( self.selection_changed_selected) self.tbl_selected_parties.cellChanged.connect(self.valueEdited) self.btn_select_all.clicked.connect(self.select_all) self.btn_deselect_all.clicked.connect(self.deselect_all) self.btn_select.clicked.connect(self.select) self.btn_deselect.clicked.connect(self.deselect) self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.setLayout(QGridLayout()) self.layout().addWidget(self.bar, 0, 0, Qt.AlignTop)
def __init__(self, iface, setupObject, targetsMetAction): QDialog.__init__(self) self.iface = iface self.setupUi(self) setDialogParameters(self, setupObject) self.startButton.clicked.connect(lambda: self.runMarxan(setupObject, targetsMetAction))
def reject(self): QDialog.reject(self)
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 __init__(self, parent=None): """ Constructor """ QDialog.__init__(self, parent) self.setupUi(self) # Set icons item = self.listWidget.item(0) item.setIcon(QIcon(resources_path('quick.png'))) item = self.listWidget.item(1) item.setIcon(QIcon(resources_path('edit.png'))) item = self.listWidget.item(2) item.setIcon(QIcon(resources_path('open.png'))) item = self.listWidget.item(3) item.setIcon(QIcon(resources_path('general.svg'))) item = self.listWidget.item(4) item.setIcon(QIcon(resources_path('info.png'))) self.label_gnu.setPixmap(QPixmap(resources_path('gnu.png'))) # Disabled in QGIS3 # self.set_help_web_view() self.restore_queries_group.setVisible(False) self.timestamp_group.setVisible(False) self.output_format_option.setVisible(False) self.help_file = None # Connect # noinspection PyUnresolvedReferences # self.pushButton_homeHelp.clicked.connect(self.get_root_help) QGIS 3 # noinspection PyUnresolvedReferences # self.pushButton_OAPI_timestamp.clicked.connect( # self.get_timestamp_overpass_api) # noinspection PyUnresolvedReferences self.comboBox_default_OAPI.currentIndexChanged[int].connect( self.set_server_overpass_api) self.query.signal_new_query_successful.connect( self.signal_new_query_successful.emit) # self.my_queries.signal_delete_query_successful.connect( # self.signal_delete_query_successful.emit) # noinspection PyUnresolvedReferences self.pushButton_restoreQueries.clicked.connect( self.restore_default_queries) # noinspection PyUnresolvedReferences self.radioButton_outputJson.toggled.connect(self.set_output_format) # Set settings about the overpass API self.defaultServer = get_setting('defaultOAPI') if self.defaultServer: index = self.comboBox_default_OAPI.findText(self.defaultServer) self.comboBox_default_OAPI.setCurrentIndex(index) else: self.defaultServer = self.comboBox_default_OAPI.currentText() set_setting('defaultOAPI', self.defaultServer) # Set settings about the output self.outputFormat = get_setting('outputFormat') if self.outputFormat == "geojson": self.radioButton_outputJson.setChecked(True) elif self.outputFormat == "shape": self.radioButton_outputShape.setChecked(True) else: set_setting('outputFormat', 'shape') self.radioButton_outputShape.setChecked(True) # Set minimum width for the menu self.listWidget.setMinimumWidth( self.listWidget.sizeHintForColumn(0) + 10)
def on_resolve_href_(dialog, layer, feature, field): """ @param dialog the dialog where the feature form is opened @param layer the layer on which the href link stands @param feature the current feature @param field the field name storing the href URL @param linked_layer_id the QGIS layer id of the already resolved layer, for update """ from .import_gmlas_panel import ImportGmlasPanel path = feature[field] if not path: return # if parent is a Dialog, we are in a feature form # else in a attribute table is_feature_form = isinstance(dialog.parent, QDialog) # The href is resolved thanks to the OGR GMLAS driver. # We need to determine what is the "root" layer of the imported # href, so that we can connect the xlink:href link to the # newly loaded set of layers. # There seems to be no way to determine what is the "root" layer # of a GMLAS database. # So, we rely on XML parsing to determine the root element # and on layer xpath found in metadata # Download the file so that it is used for XML parsing # and for GMLAS loading import tempfile from ..core.gml_utils import extract_features_from_file from ..core.qgis_urlopener import remote_open_from_qgis from ..core.xml_utils import no_ns, no_prefix with remote_open_from_qgis(path) as fi: with tempfile.NamedTemporaryFile(delete=False) as fo: fo.write(fi.read()) tmp_file = fo.name _, _, nodes = extract_features_from_file(tmp_file) if not nodes: raise RuntimeError("No feature found in linked document") root_tag = nodes[0].tag # reuse the GMLAS import panel widget dlg = QDialog() import_widget = ImportGmlasPanel(dlg, gml_path=tmp_file) path_edit = QLineEdit(path, dlg) path_edit.setEnabled(False) btn = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel, dlg) layout = QVBoxLayout() layout.addWidget(path_edit) layout.addWidget(import_widget) layout.addItem( QSpacerItem(0, 0, QSizePolicy.Minimum, QSizePolicy.Expanding)) layout.addWidget(btn) dlg.setLayout(layout) btn.accepted.connect(dlg.accept) btn.rejected.connect(dlg.reject) dlg.resize(400, 300) dlg.setWindowTitle("Options for xlink:href loading") if not dlg.exec_(): return # close the current form w = dialog while not isinstance(w, QDialog): w = w.parent() w.close() import_widget.do_load() # Add a link between the current layer # and the root layer of the newly loaded (complex) features # 1. determine the root layer and pkid of all its features root_layer = None for l in QgsProject.instance().mapLayers().values(): if no_ns(l.customProperty("xpath", "")) == no_prefix(root_tag): root_layer = l break if root_layer is None: raise RuntimeError("Cannot determine the root layer") pkid = layer.customProperty("pkid") pkid_value = feature[pkid] root_layer.startEditing() # 2. add a href_origin_pkid field in the root layer if "parent_href_pkid" not in [f.name() for f in root_layer.fields()]: new_field = QgsField(layer.fields().field(pkid)) new_field.setName("parent_href_pkid") root_layer.addAttribute(new_field) # 3. set its value to the id of current feature ids_to_change = [] for f in root_layer.getFeatures(): if f["parent_href_pkid"] is None: ids_to_change.append(f.id()) idx = root_layer.fields().indexFromName("parent_href_pkid") for fid in ids_to_change: # sets the pkid_value root_layer.changeAttributeValue(fid, idx, pkid_value) root_layer.commitChanges() # 4. declare a new QgsRelation rel_name = "1_n_" + layer.name() + "_" + field rel = QgsProject.instance().relationManager().relations().get(rel_name) if rel is None: rel = QgsRelation() rel.setId(rel_name) rel.setName(field) rel.setReferencedLayer(layer.id()) rel.setReferencingLayer(root_layer.id()) rel.addFieldPair("parent_href_pkid", pkid) QgsProject.instance().relationManager().addRelation(rel) # 5. declare the new relation in the form widgets # new 1:N in the current layer fc = layer.editFormConfig() rel_tab = fc.tabs()[1] rel_tab.addChildElement( QgsAttributeEditorRelation(rel.name(), rel, rel_tab)) # new field in the root layer fc = root_layer.editFormConfig() main_tab = fc.tabs()[0] main_tab.addChildElement( QgsAttributeEditorField("parent_href_pkid", idx, main_tab)) # declare as reference relation widget s = QgsEditorWidgetSetup( "RelationReference", { "AllowNULL": False, "ReadOnly": True, "Relation": rel.id(), "OrderByValue": False, "MapIdentification": False, "AllowAddFeatures": False, "ShowForm": True, }, ) root_layer.setEditorWidgetSetup(idx, s) # write metadata in layers href_resolved = layer.customProperty("href_resolved", []) if path not in href_resolved: layer.setCustomProperty("href_resolved", href_resolved + [path]) href_linked_layers = layer.customProperty("href_linked_layers", {}) href_linked_layers[field] = root_layer.id() layer.setCustomProperty("href_linked_layers", href_linked_layers) # 6. reload the current form from ..main import get_iface if is_feature_form: get_iface().openFeatureForm(layer, feature) else: get_iface().showAttributeTable(layer)