def testSetActive(self): """ Test setting the search as active - should set active flags to match search widget wrapper's defaults """ layer = QgsVectorLayer("Point?field=fldtext:string&field=fldint:integer", "test", "memory") parent = QWidget() w = QgsDefaultSearchWidgetWrapper(layer, 0, parent) setup = QgsGui.editorWidgetRegistry().findBest(layer, "fldint") wrapper = QgsGui.editorWidgetRegistry().create(layer, 0, None, parent) af = QgsAttributeFormEditorWidget(wrapper, setup.type(), None) af.setSearchWidgetWrapper(w) sb = af.findChild(QWidget, "SearchWidgetToolButton") # start with inactive sb.setActiveFlags(QgsSearchWidgetWrapper.FilterFlags()) # set to inactive sb.setActive() # check that correct default flag was taken from search widget wrapper self.assertTrue(sb.activeFlags() & QgsSearchWidgetWrapper.Contains) # try again with numeric field - default should be "EqualTo" w = QgsDefaultSearchWidgetWrapper(layer, 1, parent) af.setSearchWidgetWrapper(w) # start with inactive sb.setActiveFlags(QgsSearchWidgetWrapper.FilterFlags()) # set to inactive sb.setActive() # check that correct default flag was taken from search widget wrapper self.assertTrue(sb.activeFlags() & QgsSearchWidgetWrapper.EqualTo)
def __init__(self): super(HistoryDialog, self).__init__(None) self.setupUi(self) QgsGui.instance().enableAutoGeometryRestore(self) self.groupIcon = QgsApplication.getThemeIcon('mIconFolder.svg') self.keyIcon = self.style().standardIcon(QStyle.SP_FileIcon) self.clearButton = QPushButton(self.tr('Clear')) self.clearButton.setToolTip(self.tr('Clear history')) self.buttonBox.addButton(self.clearButton, QDialogButtonBox.ActionRole) self.saveButton = QPushButton(QCoreApplication.translate('HistoryDialog', 'Save As…')) self.saveButton.setToolTip(self.tr('Save history')) self.buttonBox.addButton(self.saveButton, QDialogButtonBox.ActionRole) self.tree.doubleClicked.connect(self.executeAlgorithm) self.tree.currentItemChanged.connect(self.changeText) self.clearButton.clicked.connect(self.clearLog) self.saveButton.clicked.connect(self.saveLog) self.tree.setContextMenuPolicy(Qt.CustomContextMenu) self.tree.customContextMenuRequested.connect(self.showPopupMenu) self.fillTree()
def testInstance(self): """ test retrieving global instance """ self.assertTrue(QgsGui.shortcutsManager()) # register an action to the singleton action = QAction('test', None) QgsGui.shortcutsManager().registerAction(action) # check that the same instance is returned self.assertEqual(QgsGui.shortcutsManager().listActions(), [action]) s2 = QgsShortcutsManager() self.assertEqual(s2.listActions(), [])
def setUpClass(cls): QgsGui.editorWidgetRegistry().initEditors() # Bring up a simple HTTP server os.chdir(unitTestDataPath() + '') handler = http.server.SimpleHTTPRequestHandler cls.httpd = socketserver.TCPServer(('localhost', 0), handler) cls.port = cls.httpd.server_address[1] cls.httpd_thread = threading.Thread(target=cls.httpd.serve_forever) cls.httpd_thread.setDaemon(True) cls.httpd_thread.start()
def setUpClass(cls): """Run before all tests""" cls.dbconn = 'dbname=\'qgis_test\'' if 'QGIS_PGTEST_DB' in os.environ: cls.dbconn = os.environ['QGIS_PGTEST_DB'] # Create test layers cls.vl = QgsVectorLayer(cls.dbconn + ' sslmode=disable key=\'pk\' srid=4326 type=POINT table="qgis_test"."someData" (geom) sql=', 'test', 'postgres') assert cls.vl.isValid() cls.source = cls.vl.dataProvider() cls.poly_vl = QgsVectorLayer(cls.dbconn + ' sslmode=disable key=\'pk\' srid=4326 type=POLYGON table="qgis_test"."some_poly_data" (geom) sql=', 'test', 'postgres') assert cls.poly_vl.isValid() cls.poly_provider = cls.poly_vl.dataProvider() QgsGui.editorWidgetRegistry().initEditors() cls.con = psycopg2.connect(cls.dbconn)
def testStringWithMaxLen(self): """ tests that text edit wrappers correctly handle string fields with a maximum length """ layer = QgsVectorLayer("none?field=fldint:integer", "layer", "memory") self.assertTrue(layer.isValid()) layer.dataProvider().addAttributes([QgsField('max', QVariant.String, 'string', 10), QgsField('nomax', QVariant.String, 'string', 0)]) layer.updateFields() QgsProject.instance().addMapLayer(layer) reg = QgsGui.editorWidgetRegistry() config = {'IsMultiline': 'True'} # first test for field without character limit editor = QTextEdit() editor.setPlainText('this_is_a_long_string') w = reg.create('TextEdit', layer, 2, config, editor, None) self.assertEqual(w.value(), 'this_is_a_long_string') # next test for field with character limit editor = QTextEdit() editor.setPlainText('this_is_a_long_string') w = reg.create('TextEdit', layer, 1, config, editor, None) self.assertEqual(w.value(), 'this_is_a_') QgsProject.instance().removeAllMapLayers()
def addAlgorithmEntry(alg, menuName, submenuName, actionText=None, icon=None, addButton=False): if actionText is None: if (QgsGui.higFlags() & QgsGui.HigMenuTextIsTitleCase) and not (alg.flags() & QgsProcessingAlgorithm.FlagDisplayNameIsLiteral): alg_title = QgsStringUtils.capitalize(alg.displayName(), QgsStringUtils.TitleCase) else: alg_title = alg.displayName() actionText = alg_title + QCoreApplication.translate('Processing', '…') action = QAction(icon or alg.icon(), actionText, iface.mainWindow()) alg_id = alg.id() action.setData(alg_id) action.triggered.connect(lambda: _executeAlgorithm(alg_id)) action.setObjectName("mProcessingUserMenu_%s" % alg_id) if menuName: menu = getMenu(menuName, iface.mainWindow().menuBar()) submenu = getMenu(submenuName, menu) submenu.addAction(action) if addButton: global algorithmsToolbar if algorithmsToolbar is None: algorithmsToolbar = iface.addToolBar(QCoreApplication.translate('MainWindow', 'Processing Algorithms')) algorithmsToolbar.setObjectName("ProcessingAlgorithms") algorithmsToolbar.setToolTip(QCoreApplication.translate('MainWindow', 'Processing Algorithms Toolbar')) algorithmsToolbar.addAction(action)
def __createBinaryWidget(self): """ create a binary widget """ reg = QgsGui.editorWidgetRegistry() configWdg = reg.createConfigWidget('Binary', self.layer, 1, None) config = configWdg.config() binary_widget = reg.create('Binary', self.layer, 1, config, None, None) return binary_widget
def testCurrentFilterExpression(self): """ Test creating an expression using the widget""" layer = QgsVectorLayer("Point?field=fldint:integer", "test", "memory") parent = QWidget() w = QgsDefaultSearchWidgetWrapper(layer, 0, parent) setup = QgsGui.editorWidgetRegistry().findBest(layer, "fldint") wrapper = QgsGui.editorWidgetRegistry().create(layer, 0, None, parent) af = QgsAttributeFormEditorWidget(wrapper, setup.type(), None) af.setSearchWidgetWrapper(w) # test that filter combines both current value in search widget wrapper and flags from search tool button w.lineEdit().setText('5.5') sb = af.findChild(QWidget, "SearchWidgetToolButton") sb.setActiveFlags(QgsSearchWidgetWrapper.EqualTo) self.assertEqual(af.currentFilterExpression(), '"fldint"=5.5') sb.setActiveFlags(QgsSearchWidgetWrapper.NotEqualTo) self.assertEqual(af.currentFilterExpression(), '"fldint"<>5.5')
def setUpClass(cls): """ Setup the involved layers and relations for a n:m relation :return: """ cls.mapCanvas = QgsMapCanvas() QgsGui.editorWidgetRegistry().initEditors(cls.mapCanvas) cls.dbconn = 'service=\'qgis_test\'' if 'QGIS_PGTEST_DB' in os.environ: cls.dbconn = os.environ['QGIS_PGTEST_DB'] # Create test layer cls.vl_b = QgsVectorLayer(cls.dbconn + ' sslmode=disable key=\'pk\' table="qgis_test"."books" sql=', 'books', 'postgres') cls.vl_a = QgsVectorLayer(cls.dbconn + ' sslmode=disable key=\'pk\' table="qgis_test"."authors" sql=', 'authors', 'postgres') cls.vl_link = QgsVectorLayer(cls.dbconn + ' sslmode=disable key=\'pk\' table="qgis_test"."books_authors" sql=', 'books_authors', 'postgres') QgsProject.instance().addMapLayer(cls.vl_b) QgsProject.instance().addMapLayer(cls.vl_a) QgsProject.instance().addMapLayer(cls.vl_link) cls.relMgr = QgsProject.instance().relationManager() cls.rel_a = QgsRelation() cls.rel_a.setReferencingLayer(cls.vl_link.id()) cls.rel_a.setReferencedLayer(cls.vl_a.id()) cls.rel_a.addFieldPair('fk_author', 'pk') cls.rel_a.setId('rel_a') assert(cls.rel_a.isValid()) cls.relMgr.addRelation(cls.rel_a) cls.rel_b = QgsRelation() cls.rel_b.setReferencingLayer(cls.vl_link.id()) cls.rel_b.setReferencedLayer(cls.vl_b.id()) cls.rel_b.addFieldPair('fk_book', 'pk') cls.rel_b.setId('rel_b') assert(cls.rel_b.isValid()) cls.relMgr.addRelation(cls.rel_b) # Our mock QgsVectorLayerTools, that allow injecting data where user input is expected cls.vltools = VlTools() assert(cls.vl_a.isValid()) assert(cls.vl_b.isValid()) assert(cls.vl_link.isValid())
def __init__(self, parent): QDialog.__init__(self, parent) self.setupUi(self) QgsGui.instance().enableAutoGeometryRestore(self) self.progressBar.setRange(0, len(repositories.allEnabled()) * 100) self.itemProgress = {} self.item = {} for key in repositories.allEnabled(): self.item[key] = QTreeWidgetItem(self.treeWidget) self.item[key].setText(0, key) if repositories.all()[key]["state"] > 1: self.itemProgress[key] = 100 self.displayState(key, 0) else: self.itemProgress[key] = 0 self.displayState(key, 2) self.treeWidget.resizeColumnToContents(0) repositories.repositoryFetched.connect(self.repositoryFetched) repositories.anythingChanged.connect(self.displayState)
def testEditorWidgetTypes(self): """Test that editor widget types can be fetched from the qgis_editor_widget_styles table""" vl = QgsVectorLayer('%s table="qgis_test"."widget_styles" sql=' % (self.dbconn), "widget_styles", "postgres") self.assertTrue(vl.isValid()) fields = vl.dataProvider().fields() setup1 = fields.field("fld1").editorWidgetSetup() self.assertFalse(setup1.isNull()) self.assertEqual(setup1.type(), "FooEdit") self.assertEqual(setup1.config(), {"param1": "value1", "param2": "2"}) best1 = QgsGui.editorWidgetRegistry().findBest(vl, "fld1") self.assertEqual(best1.type(), "FooEdit") self.assertEqual(best1.config(), setup1.config()) self.assertTrue(fields.field("fld2").editorWidgetSetup().isNull()) best2 = QgsGui.editorWidgetRegistry().findBest(vl, "fld2") self.assertEqual(best2.type(), "TextEdit")
def test_enableDisable(self): reg = QgsGui.editorWidgetRegistry() layer = QgsVectorLayer("none?field=number:integer", "layer", "memory") wrapper = reg.create('ValueRelation', layer, 0, {}, None, None) widget = wrapper.widget() self.assertTrue(widget.isEnabled()) wrapper.setEnabled(False) self.assertFalse(widget.isEnabled()) wrapper.setEnabled(True) self.assertTrue(widget.isEnabled())
def __init__(self, param, table): """ Constructor for FixedTableDialog :param param: linked processing parameter :param table: initial table contents - squashed to 1-dimensional! """ super().__init__(None) self.setupUi(self) QgsGui.instance().enableAutoGeometryRestore(self) self.tblView.setSelectionBehavior(QAbstractItemView.SelectRows) self.tblView.setSelectionMode(QAbstractItemView.ExtendedSelection) self.param = param self.rettable = None # Additional buttons self.btnAdd = QPushButton(self.tr('Add row')) self.buttonBox.addButton(self.btnAdd, QDialogButtonBox.ActionRole) self.btnRemove = QPushButton(self.tr('Remove row(s)')) self.buttonBox.addButton(self.btnRemove, QDialogButtonBox.ActionRole) self.btnRemoveAll = QPushButton(self.tr('Remove all')) self.buttonBox.addButton(self.btnRemoveAll, QDialogButtonBox.ActionRole) self.btnAdd.clicked.connect(self.addRow) self.btnRemove.clicked.connect(lambda: self.removeRows()) self.btnRemoveAll.clicked.connect(lambda: self.removeRows(True)) if self.param.hasFixedNumberRows(): self.btnAdd.setEnabled(False) self.btnRemove.setEnabled(False) self.btnRemoveAll.setEnabled(False) self.populateTable(table)
def __createRangeWidget(self, allownull=False): """ create a range widget """ reg = QgsGui.editorWidgetRegistry() configWdg = reg.createConfigWidget('Range', self.layer, 1, None) config = configWdg.config() # if null shall be allowed if allownull: config["AllowNull"] = allownull rangewidget = reg.create('Range', self.layer, 1, config, None, None) return rangewidget
def accept(self): keepOpen = ProcessingConfig.getSetting(ProcessingConfig.KEEP_DIALOG_OPEN) parameters = self.getParamValues() if parameters: with OverrideCursor(Qt.WaitCursor): self.feedback = FieldCalculatorFeedback(self) self.feedback.progressChanged.connect(self.setPercentage) context = dataobjects.createContext() ProcessingLog.addToLog(self.alg.asPythonCommand(parameters, context)) QgsGui.instance().processingRecentAlgorithmLog().push(self.alg.id()) self.executed, results = execute(self.alg, parameters, context, self.feedback) self.setPercentage(0) if self.executed: handleAlgorithmResults(self.alg, context, self.feedback, not keepOpen) self._wasExecuted = self.executed or self._wasExecuted if not keepOpen: QDialog.reject(self)
def test_ValueMap_set_get(self): layer = QgsVectorLayer("none?field=number:integer", "layer", "memory") self.assertTrue(layer.isValid()) QgsProject.instance().addMapLayer(layer) reg = QgsGui.editorWidgetRegistry() configWdg = reg.createConfigWidget('ValueMap', layer, 0, None) config = {'map': [{'two': '2'}, {'twoandhalf': '2.5'}, {'NULL text': 'NULL'}, {'nothing': self.VALUEMAP_NULL_TEXT}]} # Set a configuration containing values and NULL and check if it # is returned intact. configWdg.setConfig(config) self.assertEqual(configWdg.config(), config) QgsProject.instance().removeAllMapLayers()
def doAttributeTest(self, idx, expected): reg = QgsGui.editorWidgetRegistry() configWdg = reg.createConfigWidget('TextEdit', self.layer, idx, None) config = configWdg.config() editwidget = reg.create('TextEdit', self.layer, idx, config, None, None) editwidget.setValue('value') self.assertEqual(editwidget.value(), expected[0]) editwidget.setValue(123) self.assertEqual(editwidget.value(), expected[1]) editwidget.setValue(None) self.assertEqual(editwidget.value(), expected[2]) editwidget.setValue(NULL) self.assertEqual(editwidget.value(), expected[3])
def test_enableDisableOnTableWidget(self): reg = QgsGui.editorWidgetRegistry() layer = QgsVectorLayer("none?field=number:integer", "layer", "memory") wrapper = reg.create('ValueRelation', layer, 0, {'AllowMulti': 'True'}, None, None) widget = wrapper.widget() item = QTableWidgetItem('first item') widget.setItem(0, 0, item) # does not change the state the whole widget but the single items instead wrapper.setEnabled(False) # widget still true, but items false self.assertTrue(widget.isEnabled()) self.assertNotEqual(widget.item(0, 0).flags(), widget.item(0, 0).flags() | Qt.ItemIsEnabled) wrapper.setEnabled(True) self.assertTrue(widget.isEnabled()) self.assertEqual(widget.item(0, 0).flags(), widget.item(0, 0).flags() | Qt.ItemIsEnabled)
def __init__(self): super(ProcessingToolbox, self).__init__(None) self.tipWasClosed = False self.in_place_mode = False self.setupUi(self) self.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.processingToolbar.setIconSize(iface.iconSize(True)) self.algorithmTree.setRegistry(QgsApplication.processingRegistry(), QgsGui.instance().processingRecentAlgorithmLog()) filters = QgsProcessingToolboxProxyModel.Filters(QgsProcessingToolboxProxyModel.FilterToolbox) if ProcessingConfig.getSetting(ProcessingConfig.SHOW_ALGORITHMS_KNOWN_ISSUES): filters |= QgsProcessingToolboxProxyModel.FilterShowKnownIssues self.algorithmTree.setFilters(filters) self.searchBox.setShowSearchIcon(True) self.searchBox.textChanged.connect(self.set_filter_string) self.searchBox.returnPressed.connect(self.activateCurrent) self.algorithmTree.customContextMenuRequested.connect( self.showPopupMenu) self.algorithmTree.doubleClicked.connect(self.executeAlgorithm) self.txtTip.setVisible(self.disabledProviders()) def openSettings(url): if url == "close": self.txtTip.setVisible(False) self.tipWasClosed = True else: iface.showOptionsDialog(iface.mainWindow(), 'processingOptions') self.txtTip.setVisible(self.disabledProviders()) self.txtTip.linkActivated.connect(openSettings) if hasattr(self.searchBox, 'setPlaceholderText'): self.searchBox.setPlaceholderText(QCoreApplication.translate('ProcessingToolbox', 'Search…')) # connect to existing providers for p in QgsApplication.processingRegistry().providers(): if p.isActive(): self.addProviderActions(p) QgsApplication.processingRegistry().providerRemoved.connect(self.addProvider) QgsApplication.processingRegistry().providerRemoved.connect(self.removeProvider) iface.currentLayerChanged.connect(self.layer_changed)
def testBetweenFilter(self): """ Test creating a between type filter """ layer = QgsVectorLayer("Point?field=fldtext:string&field=fldint:integer", "test", "memory") form = QgsAttributeForm(layer) wrapper = QgsGui.editorWidgetRegistry().create(layer, 0, None, form) af = QgsAttributeFormEditorWidget(wrapper, 'DateTime', None) af.createSearchWidgetWrappers() d1 = af.findChildren(QDateTimeEdit)[0] d2 = af.findChildren(QDateTimeEdit)[1] d1.setDateTime(QDateTime(QDate(2013, 5, 6), QTime())) d2.setDateTime(QDateTime(QDate(2013, 5, 16), QTime())) sb = af.findChild(QWidget, "SearchWidgetToolButton") sb.setActiveFlags(QgsSearchWidgetWrapper.Between) self.assertEqual(af.currentFilterExpression(), '"fldtext">=\'2013-05-06\' AND "fldtext"<=\'2013-05-16\'') sb.setActiveFlags(QgsSearchWidgetWrapper.IsNotBetween) self.assertEqual(af.currentFilterExpression(), '"fldtext"<\'2013-05-06\' OR "fldtext">\'2013-05-16\'')
def initGui(self): self.toolbar = self.iface.addToolBar(P_E) self.toolbar.setObjectName(P_E) self.showdailyimages_act = self.add_action( os.path.join(plugin_path, "resources", "search.svg"), text=self.tr(P_E), callback=toggle_images_search, add_to_menu=True, add_to_toolbar=True, parent=self.iface.mainWindow()) self.showbasemaps_act = self.add_action( os.path.join(plugin_path, "resources", "basemap.svg"), text=self.tr("Show Basemaps Search"), callback=toggle_mosaics_search, add_to_menu=True, add_to_toolbar=True, parent=self.iface.mainWindow()) self.showinspector_act = self.add_action( os.path.join(plugin_path, "resources", "inspector.svg"), text=self.tr("Show Planet Inspector..."), callback=toggle_inspector, add_to_menu=False, add_to_toolbar=True, parent=self.iface.mainWindow()) self.showtasking_act = self.add_action(os.path.join( plugin_path, "resources", "tasking.svg"), text=self.tr("Show Tasking..."), callback=toggle_tasking_widget, add_to_menu=False, add_to_toolbar=True, parent=self.iface.mainWindow()) self.add_central_toolbar_button() self.showorders_act = self.add_action( os.path.join(plugin_path, "resources", "orders.svg"), text=self.tr("Show Orders Monitor..."), callback=toggle_orders_monitor, add_to_menu=False, add_to_toolbar=True, parent=self.iface.mainWindow()) self.add_user_button() self.add_info_button() addSettingsMenu(P_E, self.iface.addPluginToWebMenu) addAboutMenu(P_E, self.iface.addPluginToWebMenu) self.provider = BasemapLayerWidgetProvider() QgsGui.layerTreeEmbeddedWidgetRegistry().addProvider(self.provider) QgsProject.instance().projectSaved.connect(self.project_saved) QgsProject.instance().layersAdded.connect(self.layers_added) QgsProject.instance().layerRemoved.connect(self.layer_removed) PlanetClient.getInstance().loginChanged.connect(self.login_changed) self.enable_buttons(False)
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, parent=None): QDialog.__init__(self, parent) self.setupUi(self) QgsGui.instance().enableAutoGeometryRestore(self) self.button_box.button(QDialogButtonBox.Ok).setText(self.tr('Run'))
def test_gui_instance(self): self.assertIsNotNone(QgsGui.instance().processingRecentAlgorithmLog())
def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" self.provider = LayerTreeToggleLabelsProvider() QgsGui.layerTreeEmbeddedWidgetRegistry().addProvider(self.provider)
def __init__(self): self.sManager = QgsGui.shortcutsManager() self.objList = [] # lista di coppie (shortcut KeySequence) o (action KeySequence)
def setUpClass(cls): QgsGui.editorWidgetRegistry().initEditors()
def testRegistrySingleton(self): registry = QgsGui.sourceSelectProviderRegistry() self._testRegistry(registry) # Check that at least OGR and GDAL are here self.assertTrue(registry.providersByKey('ogr')) self.assertTrue(registry.providersByKey('gdal'))
def initWidgets(self): super().initWidgets() widget_context = QgsProcessingParameterWidgetContext() widget_context.setProject(QgsProject.instance()) if iface is not None: widget_context.setMapCanvas(iface.mapCanvas()) widget_context.setBrowserModel(iface.browserModel()) widget_context.setActiveLayer(iface.activeLayer()) widget_context.setMessageBar(self.parent().messageBar()) if isinstance(self.algorithm(), QgsProcessingModelAlgorithm): widget_context.setModel(self.algorithm()) # Create widgets and put them in layouts for param in self.algorithm().parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue if param.isDestination(): continue else: wrapper = WidgetWrapperFactory.create_wrapper(param, self.parent()) wrapper.setWidgetContext(widget_context) wrapper.registerProcessingContextGenerator(self.context_generator) wrapper.registerProcessingParametersGenerator(self) self.wrappers[param.name()] = wrapper # For compatibility with 3.x API, we need to check whether the wrapper is # the deprecated WidgetWrapper class. If not, it's the newer # QgsAbstractProcessingParameterWidgetWrapper class # TODO QGIS 4.0 - remove is_python_wrapper = issubclass(wrapper.__class__, WidgetWrapper) if not is_python_wrapper: widget = wrapper.createWrappedWidget(self.processing_context) else: widget = wrapper.widget if self.in_place and param.name() in ('INPUT', 'OUTPUT'): # don't show the input/output parameter widgets in in-place mode # we still need to CREATE them, because other wrappers may need to interact # with them (e.g. those parameters which need the input layer for field # selections/crs properties/etc) continue if widget is not None: if is_python_wrapper: widget.setToolTip(param.toolTip()) label = None if not is_python_wrapper: label = wrapper.createWrappedLabel() else: label = wrapper.label if label is not None: self.addParameterLabel(param, label) elif is_python_wrapper: desc = param.description() if isinstance(param, QgsProcessingParameterExtent): desc += self.tr(' (xmin, xmax, ymin, ymax)') if param.flags() & QgsProcessingParameterDefinition.FlagOptional: desc += self.tr(' [optional]') widget.setText(desc) self.addParameterWidget(param, widget) for output in self.algorithm().destinationParameterDefinitions(): if output.flags() & QgsProcessingParameterDefinition.FlagHidden: continue if self.in_place and output.name() in ('INPUT', 'OUTPUT'): continue wrapper = QgsGui.processingGuiRegistry().createParameterWidgetWrapper(output, QgsProcessingGui.Standard) wrapper.setWidgetContext(widget_context) wrapper.registerProcessingContextGenerator(self.context_generator) wrapper.registerProcessingParametersGenerator(self) self.wrappers[output.name()] = wrapper label = wrapper.createWrappedLabel() if label is not None: self.addOutputLabel(label) widget = wrapper.createWrappedWidget(self.processing_context) self.addOutputWidget(widget) # def skipOutputChanged(widget, checkbox, skipped): # TODO # enabled = not skipped # # # Do not try to open formats that are write-only. # value = widget.value() # if value and isinstance(value, QgsProcessingOutputLayerDefinition) and isinstance(output, ( # QgsProcessingParameterFeatureSink, QgsProcessingParameterVectorDestination)): # filename = value.sink.staticValue() # if filename not in ('memory:', ''): # path, ext = os.path.splitext(filename) # format = QgsVectorFileWriter.driverForExtension(ext) # drv = gdal.GetDriverByName(format) # if drv: # if drv.GetMetadataItem(gdal.DCAP_OPEN) is None: # enabled = False # # checkbox.setEnabled(enabled) # checkbox.setChecked(enabled) for wrapper in list(self.wrappers.values()): wrapper.postInitialize(list(self.wrappers.values()))
import qgis # NOQA from qgis.gui import (QgsSearchWidgetWrapper, QgsAttributeFormEditorWidget, QgsDefaultSearchWidgetWrapper, QgsAttributeForm, QgsSearchWidgetToolButton, QgsGui ) from qgis.core import (QgsVectorLayer) from qgis.PyQt.QtWidgets import QWidget, QDateTimeEdit from qgis.PyQt.QtCore import QDateTime, QDate, QTime from qgis.testing import start_app, unittest start_app() QgsGui.editorWidgetRegistry().initEditors() class PyQgsAttributeFormEditorWidget(unittest.TestCase): def testCurrentFilterExpression(self): """ Test creating an expression using the widget""" layer = QgsVectorLayer("Point?field=fldint:integer", "test", "memory") parent = QWidget() w = QgsDefaultSearchWidgetWrapper(layer, 0, parent) setup = QgsGui.editorWidgetRegistry().findBest(layer, "fldint") wrapper = QgsGui.editorWidgetRegistry().create(layer, 0, None, parent) af = QgsAttributeFormEditorWidget(wrapper, setup.type(), None) af.setSearchWidgetWrapper(w)
def testAppRegistry(self): # ensure there is an application instance self.assertIsNotNone(QgsGui.dataItemGuiProviderRegistry())
def runAlgorithm(self): self.feedback = self.createFeedback() self.context = dataobjects.createContext(self.feedback) checkCRS = ProcessingConfig.getSetting( ProcessingConfig.WARN_UNMATCHING_CRS) try: parameters = self.getParameterValues() if checkCRS and not self.algorithm().validateInputCrs( parameters, self.context): reply = QMessageBox.question( self, self.tr("Unmatching CRS's"), self.tr('Parameters do not all use the same CRS. This can ' 'cause unexpected results.\nDo you want to ' 'continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return ok, msg = self.algorithm().checkParameterValues( parameters, self.context) if not ok: QMessageBox.warning(self, self.tr('Unable to execute algorithm'), msg) return self.runButton().setEnabled(False) self.cancelButton().setEnabled(False) buttons = self.mainWidget().iterateButtons self.iterateParam = None for i in range(len(list(buttons.values()))): button = list(buttons.values())[i] if button.isChecked(): self.iterateParam = list(buttons.keys())[i] break self.clearProgress() self.feedback.pushVersionInfo(self.algorithm().provider()) self.setProgressText( QCoreApplication.translate('AlgorithmDialog', 'Processing algorithm…')) self.setInfo(QCoreApplication.translate( 'AlgorithmDialog', '<b>Algorithm \'{0}\' starting…</b>').format( self.algorithm().displayName()), escapeHtml=False) self.feedback.pushInfo(self.tr('Input parameters:')) display_params = [] for k, v in parameters.items(): display_params.append("'" + k + "' : " + self.algorithm( ).parameterDefinition(k).valueAsPythonString(v, self.context)) self.feedback.pushCommandInfo('{ ' + ', '.join(display_params) + ' }') self.feedback.pushInfo('') start_time = time.time() if self.iterateParam: # Make sure the Log tab is visible before executing the algorithm try: self.showLog() self.repaint() except: pass self.cancelButton().setEnabled( self.algorithm().flags() & QgsProcessingAlgorithm.FlagCanCancel) if executeIterating(self.algorithm(), parameters, self.iterateParam, self.context, self.feedback): self.feedback.pushInfo( self.tr('Execution completed in {0:0.2f} seconds'). format(time.time() - start_time)) self.cancelButton().setEnabled(False) self.finish(True, parameters, self.context, self.feedback) else: self.cancelButton().setEnabled(False) self.resetGui() else: command = self.algorithm().asPythonCommand( parameters, self.context) if command: ProcessingLog.addToLog(command) QgsGui.instance().processingRecentAlgorithmLog().push( self.algorithm().id()) self.cancelButton().setEnabled( self.algorithm().flags() & QgsProcessingAlgorithm.FlagCanCancel) def on_complete(ok, results): if ok: self.feedback.pushInfo( self.tr('Execution completed in {0:0.2f} seconds'). format(time.time() - start_time)) self.feedback.pushInfo(self.tr('Results:')) self.feedback.pushCommandInfo(pformat(results)) else: self.feedback.reportError( self.tr('Execution failed after {0:0.2f} seconds'). format(time.time() - start_time)) self.feedback.pushInfo('') if self.feedback_dialog is not None: self.feedback_dialog.close() self.feedback_dialog.deleteLater() self.feedback_dialog = None self.cancelButton().setEnabled(False) if not self.in_place: self.finish(ok, results, self.context, self.feedback) elif ok: self.close() self.feedback = None self.context = None if not self.in_place and not ( self.algorithm().flags() & QgsProcessingAlgorithm.FlagNoThreading): # Make sure the Log tab is visible before executing the algorithm self.showLog() task = QgsProcessingAlgRunnerTask(self.algorithm(), parameters, self.context, self.feedback) if task.isCanceled(): on_complete(False, {}) else: task.executed.connect(on_complete) self.setCurrentTask(task) else: self.proxy_progress = QgsProxyProgressTask( QCoreApplication.translate( "AlgorithmDialog", "Executing “{}”").format( self.algorithm().displayName())) QgsApplication.taskManager().addTask(self.proxy_progress) self.feedback.progressChanged.connect( self.proxy_progress.setProxyProgress) self.feedback_dialog = self.createProgressDialog() self.feedback_dialog.show() if self.in_place: ok, results = execute_in_place(self.algorithm(), parameters, self.context, self.feedback) else: ok, results = execute(self.algorithm(), parameters, self.context, self.feedback) self.feedback.progressChanged.disconnect() self.proxy_progress.finalize(ok) on_complete(ok, results) except AlgorithmDialogBase.InvalidParameterValue as e: try: self.buttonBox().accepted.connect( lambda e=e: e.widget.setPalette(QPalette())) palette = e.widget.palette() palette.setColor(QPalette.Base, QColor(255, 255, 0)) e.widget.setPalette(palette) except: pass self.messageBar().clearWidgets() self.messageBar().pushMessage( "", self.tr("Wrong or missing parameter value: {0}").format( e.parameter.description()), level=Qgis.Warning, duration=5) except AlgorithmDialogBase.InvalidOutputExtension as e: try: self.buttonBox().accepted.connect( lambda e=e: e.widget.setPalette(QPalette())) palette = e.widget.palette() palette.setColor(QPalette.Base, QColor(255, 255, 0)) e.widget.setPalette(palette) except: pass self.messageBar().clearWidgets() self.messageBar().pushMessage("", e.message, level=Qgis.Warning, duration=5)
def __init__(self, iface, db, qgis_utils): QDialog.__init__(self) self.setupUi(self) QgsGui.instance().enableAutoGeometryRestore(self) self.iface = iface self.db = db self.qgis_utils = qgis_utils self.base_configuration = BaseConfiguration() self.ilicache = IliCache(self.base_configuration) self.ilicache.refresh() self._conf_db = ConfigDbSupported() self._params = None self._current_db = None self.xtf_file_browse_button.clicked.connect( make_save_file_selector( self.xtf_file_line_edit, title=QCoreApplication.translate("DialogExportData", "Save in XTF Transfer File"), file_filter=QCoreApplication.translate( "DialogExportData", "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.validators = Validators() fileValidator = FileValidator( pattern=['*.' + ext for ext in self.ValidExtensions], allow_non_existing=True) self.xtf_file_line_edit.setPlaceholderText( QCoreApplication.translate("DialogExportData", "[Name of the XTF to be created]")) 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()) self.connection_setting_button.clicked.connect(self.show_settings) self.connection_setting_button.setText( QCoreApplication.translate("DialogExportData", "Connection Settings")) # LOG self.log_config.setTitle( QCoreApplication.translate("DialogExportData", "Show log")) self.log_config.setFlat(True) self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.layout().addWidget(self.bar, 0, 0, Qt.AlignTop) self.buttonBox.accepted.disconnect() self.buttonBox.accepted.connect(self.accepted) self.buttonBox.clear() self.buttonBox.addButton(QDialogButtonBox.Cancel) self._accept_button = self.buttonBox.addButton( QCoreApplication.translate("DialogExportData", "Export data"), QDialogButtonBox.AcceptRole) self.buttonBox.addButton(QDialogButtonBox.Help) self.buttonBox.helpRequested.connect(self.show_help) self.update_connection_info() self.update_model_names() self.restore_configuration()
def __init__(self, iface, db, qgis_utils): QDialog.__init__(self) self.setupUi(self) QgsGui.instance().enableAutoGeometryRestore(self) self.iface = iface self.db = db self.qgis_utils = qgis_utils self.base_configuration = BaseConfiguration() self.ilicache = IliCache(self.base_configuration) self.ilicache.refresh() self._conf_db = ConfigDbSupported() self._params = None self._current_db = None self.xtf_file_browse_button.clicked.connect( make_file_selector( self.xtf_file_line_edit, title=QCoreApplication.translate( "DialogImportData", 'Open Transfer or Catalog File'), file_filter=QCoreApplication.translate( "DialogImportData", 'Transfer File (*.xtf *.itf);;Catalogue File (*.xml *.xls *.xlsx)' ))) self.validators = Validators() self.xtf_file_line_edit.setPlaceholderText( QCoreApplication.translate("DialogImportData", "[Name of the XTF to be created]")) fileValidator = FileValidator(pattern=['*.xtf', '*.itf', '*.xml']) self.xtf_file_line_edit.setValidator(fileValidator) self.xtf_file_line_edit.textChanged.connect(self.update_import_models) self.xtf_file_line_edit.textChanged.emit( self.xtf_file_line_edit.text()) # db self.connection_setting_button.clicked.connect(self.show_settings) self.connection_setting_button.setText( QCoreApplication.translate("DialogImportData", 'Connection Settings')) # LOG self.log_config.setTitle( QCoreApplication.translate("DialogImportData", "Show log")) self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.layout().addWidget(self.bar, 0, 0, Qt.AlignTop) self.buttonBox.accepted.disconnect() self.buttonBox.accepted.connect(self.accepted) self.buttonBox.clear() self.buttonBox.addButton(QDialogButtonBox.Cancel) self._accept_button = self.buttonBox.addButton( QCoreApplication.translate("DialogImportData", "Import data"), QDialogButtonBox.AcceptRole) self.buttonBox.addButton(QDialogButtonBox.Help) self.buttonBox.helpRequested.connect(self.show_help) self.update_connection_info() self.restore_configuration()
def initGui(self): # port old log, ONCE ONLY! settings = QgsSettings() if not settings.value("/Processing/hasPortedOldLog", False, bool): processing_history_provider = QgsGui.historyProviderRegistry( ).providerById('processing') if processing_history_provider: processing_history_provider.portOldLog() settings.setValue("/Processing/hasPortedOldLog", True) self.options_factory = ProcessingOptionsFactory() self.options_factory.setTitle(self.tr('Processing')) iface.registerOptionsWidgetFactory(self.options_factory) self.drop_handler = ProcessingDropHandler() iface.registerCustomDropHandler(self.drop_handler) self.item_provider = ProcessingDataItemProvider() QgsApplication.dataItemProviderRegistry().addProvider( self.item_provider) self.locator_filter = AlgorithmLocatorFilter() iface.registerLocatorFilter(self.locator_filter) # Invalidate the locator filter for in-place when active layer changes iface.currentLayerChanged.connect( lambda _: self.iface.invalidateLocatorResults()) self.edit_features_locator_filter = InPlaceAlgorithmLocatorFilter() iface.registerLocatorFilter(self.edit_features_locator_filter) self.toolbox = ProcessingToolbox() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.toolbox) self.toolbox.hide() self.toolbox.visibilityChanged.connect(self.toolboxVisibilityChanged) self.toolbox.executeWithGui.connect(self.executeAlgorithm) self.resultsDock = ResultsDock() self.iface.addDockWidget(Qt.RightDockWidgetArea, self.resultsDock) self.resultsDock.hide() self.menu = QMenu(self.iface.mainWindow().menuBar()) self.menu.setObjectName('processing') self.menu.setTitle(self.tr('Pro&cessing')) self.toolboxAction = QAction(self.tr('&Toolbox'), self.iface.mainWindow()) self.toolboxAction.setCheckable(True) self.toolboxAction.setObjectName('toolboxAction') self.toolboxAction.setIcon( QgsApplication.getThemeIcon("/processingAlgorithm.svg")) self.iface.registerMainWindowAction( self.toolboxAction, QKeySequence('Ctrl+Alt+T').toString(QKeySequence.NativeText)) self.toolboxAction.toggled.connect(self.openToolbox) self.iface.attributesToolBar().insertAction( self.iface.actionOpenStatisticalSummary(), self.toolboxAction) self.menu.addAction(self.toolboxAction) self.modelerAction = QAction( QgsApplication.getThemeIcon("/processingModel.svg"), QCoreApplication.translate('ProcessingPlugin', '&Graphical Modeler…'), self.iface.mainWindow()) self.modelerAction.setObjectName('modelerAction') self.modelerAction.triggered.connect(self.openModeler) self.iface.registerMainWindowAction( self.modelerAction, QKeySequence('Ctrl+Alt+G').toString(QKeySequence.NativeText)) self.menu.addAction(self.modelerAction) self.historyAction = QAction( QgsApplication.getThemeIcon("/mIconHistory.svg"), QCoreApplication.translate('ProcessingPlugin', '&History…'), self.iface.mainWindow()) self.historyAction.setObjectName('historyAction') self.historyAction.triggered.connect(self.openHistory) self.iface.registerMainWindowAction( self.historyAction, QKeySequence('Ctrl+Alt+H').toString(QKeySequence.NativeText)) self.menu.addAction(self.historyAction) self.toolbox.processingToolbar.addAction(self.historyAction) self.resultsAction = QAction( QgsApplication.getThemeIcon("/processingResult.svg"), self.tr('&Results Viewer'), self.iface.mainWindow()) self.resultsAction.setObjectName('resultsViewer') self.resultsAction.setCheckable(True) self.iface.registerMainWindowAction( self.resultsAction, QKeySequence('Ctrl+Alt+R').toString(QKeySequence.NativeText)) self.menu.addAction(self.resultsAction) self.toolbox.processingToolbar.addAction(self.resultsAction) self.resultsDock.visibilityChanged.connect( self.resultsAction.setChecked) self.resultsAction.toggled.connect(self.resultsDock.setUserVisible) self.toolbox.processingToolbar.addSeparator() self.editInPlaceAction = QAction( QgsApplication.getThemeIcon("/mActionProcessSelected.svg"), self.tr('Edit Features In-Place'), self.iface.mainWindow()) self.editInPlaceAction.setObjectName('editInPlaceFeatures') self.editInPlaceAction.setCheckable(True) self.editInPlaceAction.toggled.connect(self.editSelected) self.menu.addAction(self.editInPlaceAction) self.toolbox.processingToolbar.addAction(self.editInPlaceAction) self.toolbox.processingToolbar.addSeparator() self.optionsAction = QAction( QgsApplication.getThemeIcon("/mActionOptions.svg"), self.tr('Options'), self.iface.mainWindow()) self.optionsAction.setObjectName('optionsAction') self.optionsAction.triggered.connect(self.openProcessingOptions) self.toolbox.processingToolbar.addAction(self.optionsAction) menuBar = self.iface.mainWindow().menuBar() menuBar.insertMenu(self.iface.firstRightStandardMenu().menuAction(), self.menu) self.menu.addSeparator() initializeMenus() createMenus() createButtons() # In-place editing button state sync self.iface.currentLayerChanged.connect(self.sync_in_place_button_state) self.iface.mapCanvas().selectionChanged.connect( self.sync_in_place_button_state) self.iface.actionToggleEditing().triggered.connect( partial(self.sync_in_place_button_state, None)) self.sync_in_place_button_state() # Sync project models self.projectModelsMenu = None self.projectMenuAction = None self.projectMenuSeparator = None self.projectProvider = QgsApplication.instance().processingRegistry( ).providerById("project") self.projectProvider.algorithmsLoaded.connect( self.updateProjectModelMenu)
def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" QgsGui.layerTreeEmbeddedWidgetRegistry().removeProvider( self.provider.id()) self.provider = None
def unload(self): QgsGui.codeEditorColorSchemeRegistry().removeColorScheme('synthwave')
def runAlgorithm(self): self.feedback = self.createFeedback() self.context = dataobjects.createContext(self.feedback) self.context.setLogLevel(self.logLevel()) checkCRS = ProcessingConfig.getSetting( ProcessingConfig.WARN_UNMATCHING_CRS) try: # messy as all heck, but we don't want to call the dialog's implementation of # createProcessingParameters as we want to catch the exceptions raised by the # parameter panel instead... parameters = {} if self.mainWidget() is None else self.mainWidget( ).createProcessingParameters() if checkCRS and not self.algorithm().validateInputCrs( parameters, self.context): reply = QMessageBox.question( self, self.tr("Unmatching CRS's"), self.tr('Parameters do not all use the same CRS. This can ' 'cause unexpected results.\nDo you want to ' 'continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return ok, msg = self.algorithm().checkParameterValues( parameters, self.context) if not ok: QMessageBox.warning(self, self.tr('Unable to execute algorithm'), msg) return self.blockControlsWhileRunning() self.setExecutedAnyResult(True) self.cancelButton().setEnabled(False) self.iterateParam = None for param in self.algorithm().parameterDefinitions(): if isinstance( parameters.get(param.name(), None), QgsProcessingFeatureSourceDefinition ) and parameters[param.name( )].flags & QgsProcessingFeatureSourceDefinition.FlagCreateIndividualOutputPerInputFeature: self.iterateParam = param.name() break self.clearProgress() self.feedback.pushVersionInfo(self.algorithm().provider()) if self.algorithm().provider().warningMessage(): self.feedback.reportError( self.algorithm().provider().warningMessage()) self.feedback.pushInfo( QCoreApplication.translate('AlgorithmDialog', 'Algorithm started at: {}').format( datetime.datetime.now().replace( microsecond=0).isoformat())) self.setInfo(QCoreApplication.translate( 'AlgorithmDialog', '<b>Algorithm \'{0}\' starting…</b>').format( self.algorithm().displayName()), escapeHtml=False) self.feedback.pushInfo(self.tr('Input parameters:')) display_params = [] for k, v in parameters.items(): display_params.append("'" + k + "' : " + self.algorithm( ).parameterDefinition(k).valueAsPythonString(v, self.context)) self.feedback.pushCommandInfo('{ ' + ', '.join(display_params) + ' }') self.feedback.pushInfo('') start_time = time.time() def elapsed_time(start_time, result): delta_t = time.time() - start_time hours = int(delta_t / 3600) minutes = int((delta_t % 3600) / 60) seconds = delta_t - hours * 3600 - minutes * 60 str_hours = [self.tr("hour"), self.tr("hours")][hours > 1] str_minutes = [self.tr("minute"), self.tr("minutes")][minutes > 1] str_seconds = [self.tr("second"), self.tr("seconds")][seconds != 1] if hours > 0: elapsed = '{0} {1:0.2f} {2} ({3} {4} {5} {6} {7:0.0f} {2})'.format( result, delta_t, str_seconds, hours, str_hours, minutes, str_minutes, seconds) elif minutes > 0: elapsed = '{0} {1:0.2f} {2} ({3} {4} {5:0.0f} {2})'.format( result, delta_t, str_seconds, minutes, str_minutes, seconds) else: elapsed = '{0} {1:0.2f} {2}'.format( result, delta_t, str_seconds) return (elapsed) if self.iterateParam: # Make sure the Log tab is visible before executing the algorithm try: self.showLog() self.repaint() except: pass self.cancelButton().setEnabled( self.algorithm().flags() & QgsProcessingAlgorithm.FlagCanCancel) if executeIterating(self.algorithm(), parameters, self.iterateParam, self.context, self.feedback): self.feedback.pushInfo( self.tr( elapsed_time(start_time, 'Execution completed in'))) self.cancelButton().setEnabled(False) self.finish(True, parameters, self.context, self.feedback) else: self.cancelButton().setEnabled(False) self.resetGui() else: self.history_details = { 'python_command': self.algorithm().asPythonCommand(parameters, self.context), 'algorithm_id': self.algorithm().id(), 'parameters': self.algorithm().asMap(parameters, self.context) } process_command, command_ok = self.algorithm( ).asQgisProcessCommand(parameters, self.context) if command_ok: self.history_details['process_command'] = process_command self.history_log_id, _ = QgsGui.historyProviderRegistry( ).addEntry('processing', self.history_details) QgsGui.instance().processingRecentAlgorithmLog().push( self.algorithm().id()) self.cancelButton().setEnabled( self.algorithm().flags() & QgsProcessingAlgorithm.FlagCanCancel) def on_complete(ok, results): if ok: self.feedback.pushInfo( self.tr( elapsed_time(start_time, 'Execution completed in'))) self.feedback.pushInfo(self.tr('Results:')) r = { k: v for k, v in results.items() if k not in ('CHILD_RESULTS', 'CHILD_INPUTS') } self.feedback.pushCommandInfo(pformat(r)) else: self.feedback.reportError( self.tr( elapsed_time(start_time, 'Execution failed after'))) self.feedback.pushInfo('') if self.history_log_id is not None: # can't deepcopy this! self.history_details['results'] = { k: v for k, v in results.items() if k != 'CHILD_INPUTS' } QgsGui.historyProviderRegistry().updateEntry( self.history_log_id, self.history_details) if self.feedback_dialog is not None: self.feedback_dialog.close() self.feedback_dialog.deleteLater() self.feedback_dialog = None self.cancelButton().setEnabled(False) self.finish(ok, results, self.context, self.feedback, in_place=self.in_place) self.feedback = None self.context = None if not self.in_place and not ( self.algorithm().flags() & QgsProcessingAlgorithm.FlagNoThreading): # Make sure the Log tab is visible before executing the algorithm self.showLog() task = QgsProcessingAlgRunnerTask(self.algorithm(), parameters, self.context, self.feedback) if task.isCanceled(): on_complete(False, {}) else: task.executed.connect(on_complete) self.setCurrentTask(task) else: self.proxy_progress = QgsProxyProgressTask( QCoreApplication.translate( "AlgorithmDialog", "Executing “{}”").format( self.algorithm().displayName())) QgsApplication.taskManager().addTask(self.proxy_progress) self.feedback.progressChanged.connect( self.proxy_progress.setProxyProgress) self.feedback_dialog = self.createProgressDialog() self.feedback_dialog.show() if self.in_place: ok, results = execute_in_place(self.algorithm(), parameters, self.context, self.feedback) else: ok, results = execute(self.algorithm(), parameters, self.context, self.feedback) self.feedback.progressChanged.disconnect() self.proxy_progress.finalize(ok) on_complete(ok, results) except AlgorithmDialogBase.InvalidParameterValue as e: self.flag_invalid_parameter_value(e.parameter.description(), e.widget) except AlgorithmDialogBase.InvalidOutputExtension as e: self.flag_invalid_output_extension(e.message, e.widget)
def setupUi(self): self.checkBoxes = {} self.showAdvanced = False self.wrappers = {} self.valueItems = {} self.dependentItems = {} self.algorithmItem = None self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok | QDialogButtonBox.Help) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(5) self.verticalLayout.setMargin(20) self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.verticalLayout.addWidget(self.bar) hLayout = QHBoxLayout() hLayout.setSpacing(5) hLayout.setMargin(0) descriptionLabel = QLabel(self.tr("Description")) self.descriptionBox = QLineEdit() self.descriptionBox.setText(self._alg.displayName()) hLayout.addWidget(descriptionLabel) hLayout.addWidget(self.descriptionBox) self.verticalLayout.addLayout(hLayout) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.verticalLayout.addWidget(line) self.algorithmItem = QgsGui.instance().processingGuiRegistry( ).algorithmConfigurationWidget(self._alg) if self.configuration: self.algorithmItem.setConfiguration(self.configuration) self.verticalLayout.addWidget(self.algorithmItem) widget_context = QgsProcessingParameterWidgetContext() if iface is not None: widget_context.setMapCanvas(iface.mapCanvas()) widget_context.setModel(self.model) widget_context.setModelChildAlgorithmId(self.childId) for param in self._alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: self.advancedButton = QPushButton() self.advancedButton.setText( self.tr('Show advanced parameters')) self.advancedButton.clicked.connect( self.showAdvancedParametersClicked) advancedButtonHLayout = QHBoxLayout() advancedButtonHLayout.addWidget(self.advancedButton) advancedButtonHLayout.addStretch() self.verticalLayout.addLayout(advancedButtonHLayout) break for param in self._alg.parameterDefinitions(): if param.isDestination( ) or param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue wrapper = WidgetWrapperFactory.create_wrapper(param, self) self.wrappers[param.name()] = wrapper if issubclass(wrapper.__class__, QgsProcessingModelerParameterWidget): wrapper.setWidgetContext(widget_context) wrapper.registerProcessingContextGenerator( self.context_generator) widget = wrapper else: widget = wrapper.widget if widget is not None: self.valueItems[param.name()] = widget if issubclass(wrapper.__class__, QgsProcessingModelerParameterWidget): label = wrapper.createLabel() else: tooltip = param.description() widget.setToolTip(tooltip) label = wrapper.label self.widget_labels[param.name()] = label if param.flags( ) & QgsProcessingParameterDefinition.FlagAdvanced: label.setVisible(self.showAdvanced) widget.setVisible(self.showAdvanced) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(widget) for dest in self._alg.destinationParameterDefinitions(): if dest.flags() & QgsProcessingParameterDefinition.FlagHidden: continue if isinstance(dest, (QgsProcessingParameterRasterDestination, QgsProcessingParameterVectorDestination, QgsProcessingParameterFeatureSink, QgsProcessingParameterFileDestination, QgsProcessingParameterFolderDestination)): label = QLabel(dest.description()) item = QgsFilterLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText( self.tr('[Enter name if this is a final result]')) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(item) self.valueItems[dest.name()] = item label = QLabel(' ') self.verticalLayout.addWidget(label) label = QLabel(self.tr('Parent algorithms')) self.dependenciesPanel = self.getDependenciesPanel() self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(self.dependenciesPanel) self.verticalLayout.addStretch(1000) self.setPreviousValues() self.setWindowTitle(self._alg.displayName()) self.verticalLayout2 = QVBoxLayout() self.verticalLayout2.setSpacing(2) self.verticalLayout2.setMargin(0) self.paramPanel = QWidget() self.paramPanel.setLayout(self.verticalLayout) self.scrollArea = QgsScrollArea() self.scrollArea.setWidget(self.paramPanel) self.scrollArea.setWidgetResizable(True) self.verticalLayout2.addWidget(self.scrollArea) self.verticalLayout2.addWidget(self.buttonBox) self.setLayout(self.verticalLayout2) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) self.buttonBox.helpRequested.connect(self.openHelp) QMetaObject.connectSlotsByName(self)
def get_widgets_for_field(cls, vl): """Get compatible widget names""" return [k for k, v in QgsGui.editorWidgetRegistry().factories().items() if v.supportsField(vl, 0)]
def __init__(self, _): QgsGui.codeEditorColorSchemeRegistry().addColorScheme( SynthwaveColorScheme())
def add_to_ows(self): """add to OWS provider connection list""" conn_name_matches = [] item = self.treeRecords.currentItem() if not item: return item_data = json.loads(get_item_data(item, 'link')) caller = self.sender().objectName() # stype = human name,/qgis/connections-%s,providername if caller == 'mActionAddWms': stype = ['OGC:WMS/OGC:WMTS', 'wms', 'wms'] data_url = item_data['wms'] elif caller == 'mActionAddWfs': stype = ['OGC:WFS', 'wfs', 'WFS'] data_url = item_data['wfs'] elif caller == 'mActionAddWcs': stype = ['OGC:WCS', 'wcs', 'wcs'] data_url = item_data['wcs'] elif caller == 'mActionAddAms': stype = ['ESRI:ArcGIS:MapServer', 'ams', 'arcgismapserver'] data_url = item_data['ams'].split('MapServer')[0] + 'MapServer' elif caller == 'mActionAddAfs': stype = ['ESRI:ArcGIS:FeatureServer', 'afs', 'arcgisfeatureserver'] data_url = item_data['afs'].split( 'FeatureServer')[0] + 'FeatureServer' sname = '%s from MetaSearch' % stype[1] # store connection # check if there is a connection with same name if caller in ['mActionAddAms', 'mActionAddAfs']: self.settings.beginGroup('/qgis/connections-%s' % stype[2]) else: self.settings.beginGroup('/qgis/connections-%s' % stype[1]) keys = self.settings.childGroups() self.settings.endGroup() for key in keys: if key.startswith(sname): conn_name_matches.append(key) if conn_name_matches: sname = conn_name_matches[-1] # check for duplicates if sname in keys: # duplicate found msg = self.tr('Connection {0} exists. Overwrite?').format(sname) res = QMessageBox.warning( self, self.tr('Saving server'), msg, QMessageBox.Yes | QMessageBox.No | QMessageBox.Cancel) if res == QMessageBox.No: # assign new name with serial sname = serialize_string(sname) elif res == QMessageBox.Cancel: return # no dups detected or overwrite is allowed if caller in ['mActionAddAms', 'mActionAddAfs']: self.settings.beginGroup('/qgis/connections-%s' % stype[2]) else: self.settings.beginGroup('/qgis/connections-%s' % stype[1]) self.settings.setValue('/%s/url' % sname, clean_ows_url(data_url)) self.settings.endGroup() # open provider window ows_provider = QgsGui.sourceSelectProviderRegistry( ).createSelectionWidget(stype[2], self, Qt.Widget, QgsProviderRegistry.WidgetMode.Embedded) service_type = stype[0] # connect dialog signals to iface slots if service_type == 'OGC:WMS/OGC:WMTS': ows_provider.addRasterLayer.connect(self.iface.addRasterLayer) conn_cmb = ows_provider.findChild(QWidget, 'cmbConnections') connect = 'btnConnect_clicked' elif service_type == 'OGC:WFS': def addVectorLayer(path, name): self.iface.mainWindow().addVectorLayer(path, name, 'WFS') ows_provider.addVectorLayer.connect(addVectorLayer) conn_cmb = ows_provider.findChild(QWidget, 'cmbConnections') connect = 'connectToServer' elif service_type == 'OGC:WCS': ows_provider.addRasterLayer.connect(self.iface.addRasterLayer) conn_cmb = ows_provider.findChild(QWidget, 'mConnectionsComboBox') connect = 'mConnectButton_clicked' elif service_type == 'ESRI:ArcGIS:MapServer': ows_provider.addRasterLayer.connect(self.iface.addRasterLayer) conn_cmb = ows_provider.findChild(QComboBox) connect = 'connectToServer' elif service_type == 'ESRI:ArcGIS:FeatureServer': def addAfsLayer(path, name): self.iface.mainWindow().addVectorLayer(path, name, 'afs') ows_provider.addVectorLayer.connect(addAfsLayer) conn_cmb = ows_provider.findChild(QComboBox) connect = 'connectToServer' ows_provider.setModal(False) ows_provider.show() # open provider dialogue against added OWS index = conn_cmb.findText(sname) if index > -1: conn_cmb.setCurrentIndex(index) # only for wfs if service_type == 'OGC:WFS': ows_provider.cmbConnections_activated(index) elif service_type in [ 'ESRI:ArcGIS:MapServer', 'ESRI:ArcGIS:FeatureServer' ]: ows_provider.cmbConnections_activated(index) getattr(ows_provider, connect)()
def setupUi(self): self.checkBoxes = {} self.showAdvanced = False self.wrappers = {} self.valueItems = {} self.dependentItems = {} self.algorithmItem = None self.resize(650, 450) self.buttonBox = QDialogButtonBox() self.buttonBox.setOrientation(Qt.Horizontal) self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel | QDialogButtonBox.Ok | QDialogButtonBox.Help) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.verticalLayout = QVBoxLayout() self.verticalLayout.setSpacing(5) self.verticalLayout.setMargin(20) self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.verticalLayout.addWidget(self.bar) hLayout = QHBoxLayout() hLayout.setSpacing(5) hLayout.setMargin(0) descriptionLabel = QLabel(self.tr("Description")) self.descriptionBox = QLineEdit() self.descriptionBox.setText(self._alg.displayName()) hLayout.addWidget(descriptionLabel) hLayout.addWidget(self.descriptionBox) self.verticalLayout.addLayout(hLayout) line = QFrame() line.setFrameShape(QFrame.HLine) line.setFrameShadow(QFrame.Sunken) self.verticalLayout.addWidget(line) widget_context = QgsProcessingParameterWidgetContext() widget_context.setProject(QgsProject.instance()) if iface is not None: widget_context.setMapCanvas(iface.mapCanvas()) widget_context.setModel(self.model) widget_context.setModelChildAlgorithmId(self.childId) self.algorithmItem = QgsGui.instance().processingGuiRegistry().algorithmConfigurationWidget(self._alg) if self.algorithmItem: self.algorithmItem.setWidgetContext(widget_context) self.algorithmItem.registerProcessingContextGenerator(self.context_generator) if self.configuration: self.algorithmItem.setConfiguration(self.configuration) self.verticalLayout.addWidget(self.algorithmItem) for param in self._alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: self.advancedButton = QPushButton() self.advancedButton.setText(self.tr('Show advanced parameters')) self.advancedButton.clicked.connect( self.showAdvancedParametersClicked) advancedButtonHLayout = QHBoxLayout() advancedButtonHLayout.addWidget(self.advancedButton) advancedButtonHLayout.addStretch() self.verticalLayout.addLayout(advancedButtonHLayout) break for param in self._alg.parameterDefinitions(): if param.isDestination() or param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue wrapper = WidgetWrapperFactory.create_wrapper(param, self) self.wrappers[param.name()] = wrapper wrapper.setWidgetContext(widget_context) wrapper.registerProcessingContextGenerator(self.context_generator) if issubclass(wrapper.__class__, QgsProcessingModelerParameterWidget): widget = wrapper else: widget = wrapper.widget if widget is not None: self.valueItems[param.name()] = widget if issubclass(wrapper.__class__, QgsProcessingModelerParameterWidget): label = wrapper.createLabel() else: tooltip = param.description() widget.setToolTip(tooltip) label = wrapper.label self.widget_labels[param.name()] = label if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: label.setVisible(self.showAdvanced) widget.setVisible(self.showAdvanced) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(widget) for dest in self._alg.destinationParameterDefinitions(): if dest.flags() & QgsProcessingParameterDefinition.FlagHidden: continue if isinstance(dest, (QgsProcessingParameterRasterDestination, QgsProcessingParameterVectorDestination, QgsProcessingParameterFeatureSink, QgsProcessingParameterFileDestination, QgsProcessingParameterFolderDestination)): label = QLabel(dest.description()) item = QgsFilterLineEdit() if hasattr(item, 'setPlaceholderText'): item.setPlaceholderText(self.tr('[Enter name if this is a final result]')) self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(item) self.valueItems[dest.name()] = item label = QLabel(' ') self.verticalLayout.addWidget(label) label = QLabel(self.tr('Parent algorithms')) self.dependenciesPanel = self.getDependenciesPanel() self.verticalLayout.addWidget(label) self.verticalLayout.addWidget(self.dependenciesPanel) self.verticalLayout.addStretch(1000) self.setPreviousValues() self.setWindowTitle(self._alg.displayName()) self.verticalLayout2 = QVBoxLayout() self.verticalLayout2.setSpacing(2) self.verticalLayout2.setMargin(0) self.paramPanel = QWidget() self.paramPanel.setLayout(self.verticalLayout) self.scrollArea = QgsScrollArea() self.scrollArea.setWidget(self.paramPanel) self.scrollArea.setWidgetResizable(True) self.verticalLayout2.addWidget(self.scrollArea) self.verticalLayout2.addWidget(self.buttonBox) self.setLayout(self.verticalLayout2) self.buttonBox.accepted.connect(self.okPressed) self.buttonBox.rejected.connect(self.cancelPressed) self.buttonBox.helpRequested.connect(self.openHelp) QMetaObject.connectSlotsByName(self)
def runAlgorithm(self): self.feedback = self.createFeedback() self.context = dataobjects.createContext(self.feedback) checkCRS = ProcessingConfig.getSetting(ProcessingConfig.WARN_UNMATCHING_CRS) try: parameters = self.getParameterValues() if checkCRS and not self.algorithm().validateInputCrs(parameters, self.context): reply = QMessageBox.question(self, self.tr("Unmatching CRS's"), self.tr('Parameters do not all use the same CRS. This can ' 'cause unexpected results.\nDo you want to ' 'continue?'), QMessageBox.Yes | QMessageBox.No, QMessageBox.No) if reply == QMessageBox.No: return ok, msg = self.algorithm().checkParameterValues(parameters, self.context) if not ok: QMessageBox.warning( self, self.tr('Unable to execute algorithm'), msg) return self.runButton().setEnabled(False) self.cancelButton().setEnabled(False) buttons = self.mainWidget().iterateButtons self.iterateParam = None for i in range(len(list(buttons.values()))): button = list(buttons.values())[i] if button.isChecked(): self.iterateParam = list(buttons.keys())[i] break self.clearProgress() self.setProgressText(QCoreApplication.translate('AlgorithmDialog', 'Processing algorithm…')) self.setInfo( QCoreApplication.translate('AlgorithmDialog', '<b>Algorithm \'{0}\' starting…</b>').format(self.algorithm().displayName()), escapeHtml=False) self.feedback.pushInfo(self.tr('Input parameters:')) display_params = [] for k, v in parameters.items(): display_params.append("'" + k + "' : " + self.algorithm().parameterDefinition(k).valueAsPythonString(v, self.context)) self.feedback.pushCommandInfo('{ ' + ', '.join(display_params) + ' }') self.feedback.pushInfo('') start_time = time.time() if self.iterateParam: # Make sure the Log tab is visible before executing the algorithm try: self.showLog() self.repaint() except: pass self.cancelButton().setEnabled(self.algorithm().flags() & QgsProcessingAlgorithm.FlagCanCancel) if executeIterating(self.algorithm(), parameters, self.iterateParam, self.context, self.feedback): self.feedback.pushInfo( self.tr('Execution completed in {0:0.2f} seconds').format(time.time() - start_time)) self.cancelButton().setEnabled(False) self.finish(True, parameters, self.context, self.feedback) else: self.cancelButton().setEnabled(False) self.resetGui() else: command = self.algorithm().asPythonCommand(parameters, self.context) if command: ProcessingLog.addToLog(command) QgsGui.instance().processingRecentAlgorithmLog().push(self.algorithm().id()) self.cancelButton().setEnabled(self.algorithm().flags() & QgsProcessingAlgorithm.FlagCanCancel) def on_complete(ok, results): if ok: self.feedback.pushInfo(self.tr('Execution completed in {0:0.2f} seconds').format(time.time() - start_time)) self.feedback.pushInfo(self.tr('Results:')) self.feedback.pushCommandInfo(pformat(results)) else: self.feedback.reportError( self.tr('Execution failed after {0:0.2f} seconds').format(time.time() - start_time)) self.feedback.pushInfo('') if self.feedback_dialog is not None: self.feedback_dialog.close() self.feedback_dialog.deleteLater() self.feedback_dialog = None self.cancelButton().setEnabled(False) if not self.in_place: self.finish(ok, results, self.context, self.feedback) elif ok: self.close() self.feedback = None self.context = None if not self.in_place and not (self.algorithm().flags() & QgsProcessingAlgorithm.FlagNoThreading): # Make sure the Log tab is visible before executing the algorithm self.showLog() task = QgsProcessingAlgRunnerTask(self.algorithm(), parameters, self.context, self.feedback) if task.isCanceled(): on_complete(False, {}) else: task.executed.connect(on_complete) self.setCurrentTask(task) else: self.proxy_progress = QgsProxyProgressTask(QCoreApplication.translate("AlgorithmDialog", "Executing “{}”").format(self.algorithm().displayName())) QgsApplication.taskManager().addTask(self.proxy_progress) self.feedback.progressChanged.connect(self.proxy_progress.setProxyProgress) self.feedback_dialog = self.createProgressDialog() self.feedback_dialog.show() if self.in_place: ok, results = execute_in_place(self.algorithm(), parameters, self.context, self.feedback) else: ok, results = execute(self.algorithm(), parameters, self.context, self.feedback) self.feedback.progressChanged.disconnect() self.proxy_progress.finalize(ok) on_complete(ok, results) except AlgorithmDialogBase.InvalidParameterValue as e: try: self.buttonBox().accepted.connect(lambda e=e: e.widget.setPalette(QPalette())) palette = e.widget.palette() palette.setColor(QPalette.Base, QColor(255, 255, 0)) e.widget.setPalette(palette) except: pass self.messageBar().clearWidgets() self.messageBar().pushMessage("", self.tr("Wrong or missing parameter value: {0}").format(e.parameter.description()), level=Qgis.Warning, duration=5) except AlgorithmDialogBase.InvalidOutputExtension as e: try: self.buttonBox().accepted.connect(lambda e=e: e.widget.setPalette(QPalette())) palette = e.widget.palette() palette.setColor(QPalette.Base, QColor(255, 255, 0)) e.widget.setPalette(palette) except: pass self.messageBar().clearWidgets() self.messageBar().pushMessage("", e.message, level=Qgis.Warning, duration=5)
def __init__(self, entity, model=None, parent=None, manage_documents=True, collect_model=False, parent_entity=None, exclude_columns=None, plugin=None, allow_str_creation=True): """ Class constructor. :param entity: Entity object corresponding to a table object. :type entity: Entity :param model: Data object for loading data into the form widgets. If the model is set, then the editor dialog is assumed to be in edit mode. :type model: object :param parent: Parent widget that the form belongs to. :type parent: QWidget :param manage_documents: True if the dialog should provide controls for managing supporting documents. Only applicable if the entity allows for supporting documents to be attached. :type manage_documents: bool :param collect_model: If set to True only returns the filled form model without saving it to the database. :type collect_model: Boolean :param parent_entity: The parent entity of the editor :type parent_entity: Object :param exclude_columns: List of columns to be excluded if in a list. :type exclude_columns: List :return: If collect_model, returns SQLAlchemy Model """ super().__init__(parent=parent, model=model, entity=entity) QgsGui.enableAutoGeometryRestore(self) self.collection_suffix = self.tr('Collection') # Set minimum width self.setMinimumWidth(450) self.plugin = plugin # Flag for mandatory columns self.has_mandatory = False self.reload_form = False self._entity = entity self.edit_model = model self.column_widgets = OrderedDict() self.columns = {} self._parent = parent self.exclude_columns = exclude_columns or [] self.entity_tab_widget = None self._disable_collections = False self.filter_val = None self.parent_entity = parent_entity self.child_models = OrderedDict() self.entity_scroll_area = None self.entity_editor_widgets = OrderedDict() self.details_tree_view = None # Set notification layout bar self.vlNotification = QVBoxLayout() self.vlNotification.setObjectName('vlNotification') self._notifBar = NotificationBar(self.vlNotification) self.do_not_check_dirty = False # Set manage documents only if the entity supports documents if self._entity.supports_documents: self._manage_documents = manage_documents else: self._manage_documents = False # Setup entity model self._ent_document_model = None if self._entity.supports_documents: self.ent_model, self._ent_document_model = entity_model( self._entity, with_supporting_document=True) else: self.ent_model = entity_model(self._entity) if model is not None: self.ent_model = model MapperMixin.__init__(self, self.ent_model, entity) self.collect_model = collect_model self.register_column_widgets() try: if isinstance(parent._parent, EntityEditorDialog): # hide collections form child editor self._disable_collections = True except AttributeError: self._parent._parent = None # Set title editor_trans = self.tr('Editor') if self._entity.label is not None: if self._entity.label != '': title_str = self._entity.label else: title_str = format_name(self._entity.short_name) else: title_str = format_name(self._entity.short_name) self.title = '{0} {1}'.format(title_str, editor_trans) self.setWindowTitle(self.title) # determine whether the entity is part of the STR relationship curr_profile = current_profile() self.participates_in_str, self.is_party_unit = curr_profile.social_tenure.entity_participates_in_str( self.entity) self._init_gui(show_str_tab=allow_str_creation and self.participates_in_str, is_party_unit=self.is_party_unit) self.adjustSize() self._get_entity_editor_widgets() if isinstance(parent._parent, EntityEditorDialog): self.parent_entity = parent.parent_entity self.set_parent_values() # make the size smaller to differentiate from parent and as it # only has few tabs. self.adjustSize() self.attribute_mappers = self._attr_mapper_collection # Exception title for editor extension exceptions self._ext_exc_msg = self.tr( 'An error has occured while executing Python code in the editor ' 'extension:') # Register custom editor extension if specified self._editor_ext = entity_dlg_extension(self) if self._editor_ext is not None: self._editor_ext.post_init() # Initialize CascadingFieldContext objects self._editor_ext.connect_cf_contexts()
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 setUpClass(cls): cls.mCanvas = QgsMapCanvas() QgsGui.editorWidgetRegistry().initEditors(cls.mCanvas)
def __init__(self, iface, base_config, parent=None): QDialog.__init__(self, parent) self.setupUi(self) self.iface = iface self.db_simple_factory = DbSimpleFactory() QgsGui.instance().enableAutoGeometryRestore(self) self.create_text = self.tr('Create') self.set_button_to_create_action = QAction(self.create_text, None) self.set_button_to_create_action.triggered.connect(self.set_button_to_create) self.create_without_constraints_text = self.tr('Create without constraints') self.set_button_to_create_without_constraints_action = QAction(self.create_without_constraints_text, None) self.set_button_to_create_without_constraints_action.triggered.connect(self.set_button_to_create_without_constraints) self.edit_command_action = QAction(self.tr('Edit ili2db command'), None) self.edit_command_action.triggered.connect(self.edit_command) self.create_tool_button.addAction(self.set_button_to_create_without_constraints_action) self.create_tool_button.addAction(self.edit_command_action) self.create_tool_button.setText(self.create_text) self.create_tool_button.clicked.connect(self.accepted) self.buttonBox.accepted.disconnect() self.buttonBox.clear() self.buttonBox.addButton(QDialogButtonBox.Cancel) self.create_constraints = True self.create_button.setText(self.tr('Create')) self.create_button.clicked.connect(self.accepted) self.ili_file_browse_button.clicked.connect( make_file_selector(self.ili_file_line_edit, title=self.tr('Open Interlis Model'), file_filter=self.tr('Interlis Model File (*.ili *.ILI)'))) self.buttonBox.addButton(QDialogButtonBox.Help) self.buttonBox.helpRequested.connect(self.help_requested) self.crs = QgsCoordinateReferenceSystem() 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.type_combo_box.clear() self._lst_panel = dict() for db_id in self.db_simple_factory.get_db_list(True): self.type_combo_box.addItem(displayDbIliMode[db_id], db_id) for db_id in self.db_simple_factory.get_db_list(False): db_factory = self.db_simple_factory.create_factory(db_id) item_panel = db_factory.get_config_panel(self, DbActionType.GENERATE) self._lst_panel[db_id] = item_panel self.db_layout.addWidget(item_panel) self.type_combo_box.currentIndexChanged.connect(self.type_changed) self.txtStdout.anchorClicked.connect(self.link_activated) self.crsSelector.crsChanged.connect(self.crs_changed) self.base_configuration = base_config self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.txtStdout.setLayout(QGridLayout()) self.txtStdout.layout().setContentsMargins(0, 0, 0, 0) self.txtStdout.layout().addWidget(self.bar, 0, 0, Qt.AlignTop) self.validators = Validators() nonEmptyValidator = NonEmptyStringValidator() fileValidator = FileValidator(pattern=['*.' + ext for ext in self.ValidExtensions], allow_empty=True) self.restore_configuration() self.ili_models_line_edit.setValidator(nonEmptyValidator) self.ili_file_line_edit.setValidator(fileValidator) self.ili_models_line_edit.textChanged.connect( self.validators.validate_line_edits) self.ili_models_line_edit.textChanged.emit( self.ili_models_line_edit.text()) self.ili_models_line_edit.textChanged.connect(self.on_model_changed) self.ili_models_line_edit.textChanged.connect(self.complete_models_completer) self.ili_models_line_edit.punched.connect(self.complete_models_completer) self.ilicache = IliCache(self.base_configuration) self.refresh_ili_cache() self.ili_models_line_edit.setPlaceholderText(self.tr('[Search model from repository]')) self.ili_file_line_edit.textChanged.connect( self.validators.validate_line_edits) self.ili_file_line_edit.textChanged.connect(self.ili_file_changed) self.ili_file_line_edit.textChanged.emit( self.ili_file_line_edit.text())
def __init__(self, filePath=None, parent=None): super(ScriptEditorDialog, self).__init__(parent) self.setupUi(self) QgsGui.instance().enableAutoGeometryRestore(self) self.editor.initLexer() self.searchWidget.setVisible(False) if iface is not None: self.toolBar.setIconSize(iface.iconSize()) self.setStyleSheet(iface.mainWindow().styleSheet()) self.actionOpenScript.setIcon( QgsApplication.getThemeIcon('/mActionScriptOpen.svg')) self.actionSaveScript.setIcon( QgsApplication.getThemeIcon('/mActionFileSave.svg')) self.actionSaveScriptAs.setIcon( QgsApplication.getThemeIcon('/mActionFileSaveAs.svg')) self.actionRunScript.setIcon( QgsApplication.getThemeIcon('/mActionStart.svg')) self.actionCut.setIcon( QgsApplication.getThemeIcon('/mActionEditCut.svg')) self.actionCopy.setIcon( QgsApplication.getThemeIcon('/mActionEditCopy.svg')) self.actionPaste.setIcon( QgsApplication.getThemeIcon('/mActionEditPaste.svg')) self.actionUndo.setIcon( QgsApplication.getThemeIcon('/mActionUndo.svg')) self.actionRedo.setIcon( QgsApplication.getThemeIcon('/mActionRedo.svg')) self.actionFindReplace.setIcon( QgsApplication.getThemeIcon('/mActionFindReplace.svg')) self.actionIncreaseFontSize.setIcon( QgsApplication.getThemeIcon('/mActionIncreaseFont.svg')) self.actionDecreaseFontSize.setIcon( QgsApplication.getThemeIcon('/mActionDecreaseFont.svg')) # Connect signals and slots self.actionOpenScript.triggered.connect(self.openScript) self.actionSaveScript.triggered.connect(self.save) self.actionSaveScriptAs.triggered.connect(self.saveAs) self.actionRunScript.triggered.connect(self.runAlgorithm) self.actionCut.triggered.connect(self.editor.cut) self.actionCopy.triggered.connect(self.editor.copy) self.actionPaste.triggered.connect(self.editor.paste) self.actionUndo.triggered.connect(self.editor.undo) self.actionRedo.triggered.connect(self.editor.redo) self.actionFindReplace.toggled.connect(self.toggleSearchBox) self.actionIncreaseFontSize.triggered.connect(self.editor.zoomIn) self.actionDecreaseFontSize.triggered.connect(self.editor.zoomOut) self.editor.textChanged.connect(lambda: self.setHasChanged(True)) self.leFindText.returnPressed.connect(self.find) self.btnFind.clicked.connect(self.find) self.btnReplace.clicked.connect(self.replace) self.lastSearch = None self.filePath = None if filePath is not None: self._loadFile(filePath) self.setHasChanged(False)
def __init__(self, filePath=None, parent=None): super(ScriptEditorDialog, self).__init__(parent) self.setupUi(self) QgsGui.instance().enableAutoGeometryRestore(self) self.editor.initLexer() self.searchWidget.setVisible(False) if iface is not None: self.toolBar.setIconSize(iface.iconSize()) self.setStyleSheet(iface.mainWindow().styleSheet()) self.actionOpenScript.setIcon( QgsApplication.getThemeIcon('/mActionScriptOpen.svg')) self.actionSaveScript.setIcon( QgsApplication.getThemeIcon('/mActionFileSave.svg')) self.actionSaveScriptAs.setIcon( QgsApplication.getThemeIcon('/mActionFileSaveAs.svg')) self.actionRunScript.setIcon( QgsApplication.getThemeIcon('/mActionStart.svg')) self.actionCut.setIcon( QgsApplication.getThemeIcon('/mActionEditCut.svg')) self.actionCopy.setIcon( QgsApplication.getThemeIcon('/mActionEditCopy.svg')) self.actionPaste.setIcon( QgsApplication.getThemeIcon('/mActionEditPaste.svg')) self.actionUndo.setIcon( QgsApplication.getThemeIcon('/mActionUndo.svg')) self.actionRedo.setIcon( QgsApplication.getThemeIcon('/mActionRedo.svg')) self.actionFindReplace.setIcon( QgsApplication.getThemeIcon('/mActionFindReplace.svg')) self.actionIncreaseFontSize.setIcon( QgsApplication.getThemeIcon('/mActionIncreaseFont.svg')) self.actionDecreaseFontSize.setIcon( QgsApplication.getThemeIcon('/mActionDecreaseFont.svg')) # Connect signals and slots self.actionOpenScript.triggered.connect(self.openScript) self.actionSaveScript.triggered.connect(self.save) self.actionSaveScriptAs.triggered.connect(self.saveAs) self.actionRunScript.triggered.connect(self.runAlgorithm) self.actionCut.triggered.connect(self.editor.cut) self.actionCopy.triggered.connect(self.editor.copy) self.actionPaste.triggered.connect(self.editor.paste) self.actionUndo.triggered.connect(self.editor.undo) self.actionRedo.triggered.connect(self.editor.redo) self.actionFindReplace.toggled.connect(self.toggleSearchBox) self.actionIncreaseFontSize.triggered.connect(self.editor.zoomIn) self.actionDecreaseFontSize.triggered.connect(self.editor.zoomOut) self.editor.textChanged.connect(lambda: self.setHasChanged(True)) self.leFindText.returnPressed.connect(self.find) self.btnFind.clicked.connect(self.find) self.btnReplace.clicked.connect(self.replace) self.lastSearch = None self.filePath = None if filePath is not None: self._loadFile(filePath) self.needUpdate = False self.setHasChanged(False)
def __init__(self, _): QgsGui.codeEditorColorSchemeRegistry().addColorScheme( MonokaiProSpectrumScheme())
def __init__(self, iface, parent=None): """Constructor.""" super().__init__(parent) self.setupUi(self) self.setObjectName('QQuakeDialog') QgsGui.enableAutoGeometryRestore(self) self.fsdn_event_filter = FilterParameterWidget(iface, SERVICE_MANAGER.FDSNEVENT) vl = QVBoxLayout() vl.setContentsMargins(0, 0, 0, 0) vl.addWidget(self.fsdn_event_filter) self.fsdn_event_filter_container.setLayout(vl) self.earthquake_service_info_widget = ServiceInformationWidget(iface) self.fsdn_by_id_filter = FilterByIdWidget(iface, SERVICE_MANAGER.FDSNEVENT) vl = QVBoxLayout() vl.setContentsMargins(0, 0, 0, 0) vl.addWidget(self.fsdn_by_id_filter) self.fsdn_by_id_container.setLayout(vl) self.fdsn_by_url_widget = FetchByUrlWidget(iface, SERVICE_MANAGER.FDSNEVENT) vl = QVBoxLayout() vl.setContentsMargins(0, 0, 0, 0) vl.addWidget(self.fdsn_by_url_widget) self.fsdn_by_url_container.setLayout(vl) vl = QVBoxLayout() vl.setContentsMargins(0, 0, 0, 0) vl.addWidget(self.earthquake_service_info_widget) self.earthquake_service_info_container.setLayout(vl) self.macro_filter = FilterParameterWidget(iface, SERVICE_MANAGER.MACROSEISMIC) vl = QVBoxLayout() vl.setContentsMargins(0, 0, 0, 0) vl.addWidget(self.macro_filter) self.macro_filter_container.setLayout(vl) self.macro_by_id_filter = FilterByIdWidget(iface, SERVICE_MANAGER.MACROSEISMIC) vl = QVBoxLayout() vl.setContentsMargins(0, 0, 0, 0) vl.addWidget(self.macro_by_id_filter) self.macro_by_id_container.setLayout(vl) self.macro_by_url_widget = FetchByUrlWidget(iface, SERVICE_MANAGER.MACROSEISMIC) vl = QVBoxLayout() vl.setContentsMargins(0, 0, 0, 0) vl.addWidget(self.macro_by_url_widget) self.macro_by_url_container.setLayout(vl) self.macro_service_info_widget = ServiceInformationWidget(iface) vl = QVBoxLayout() vl.setContentsMargins(0, 0, 0, 0) vl.addWidget(self.macro_service_info_widget) self.macro_service_info_container.setLayout(vl) self.station_filter = FilterParameterWidget(iface, SERVICE_MANAGER.FDSNSTATION) vl = QVBoxLayout() vl.setContentsMargins(0, 0, 0, 0) vl.addWidget(self.station_filter) self.station_filter_container.setLayout(vl) self.station_by_id_filter = FilterStationByIdWidget(iface, SERVICE_MANAGER.FDSNSTATION) vl = QVBoxLayout() vl.setContentsMargins(0, 0, 0, 0) vl.addWidget(self.station_by_id_filter) self.station_by_id_container.setLayout(vl) self.station_service_info_widget = ServiceInformationWidget(iface) vl = QVBoxLayout() vl.setContentsMargins(0, 0, 0, 0) vl.addWidget(self.station_service_info_widget) self.station_service_info_container.setLayout(vl) self.ogc_service_widget = OgcServiceWidget(iface) vl = QVBoxLayout() vl.setContentsMargins(0, 0, 0, 0) vl.addWidget(self.ogc_service_widget) self.ogc_widget_container.setLayout(vl) self.ogc_service_info_widget = ServiceInformationWidget(iface) vl = QVBoxLayout() vl.setContentsMargins(0, 0, 0, 0) vl.addWidget(self.ogc_service_info_widget) self.ogc_service_info_container.setLayout(vl) self.message_bar = QgsMessageBar() self.message_bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.verticalLayout.insertWidget(0, self.message_bar) self.fsdn_event_url_text_browser.viewport().setAutoFillBackground(False) self.fdsn_macro_url_text_browser.viewport().setAutoFillBackground(False) self.fdsn_station_url_text_browser.viewport().setAutoFillBackground(False) self.button_box.button(QDialogButtonBox.Ok).setText(self.tr('Fetch Data')) self.button_box.rejected.connect(self._save_settings) self.iface = iface # OGC self.ogc_combo.addItem(self.tr('Web Map Services (WMS)'), SERVICE_MANAGER.WMS) self.ogc_combo.addItem(self.tr('Web Feature Services (WFS)'), SERVICE_MANAGER.WFS) self.ogc_combo.currentIndexChanged.connect(self.refreshOgcWidgets) self.ogc_list.currentRowChanged.connect( self._ogc_service_changed) self._refresh_services() SERVICE_MANAGER.refreshed.connect(self._refresh_services) # connect to refreshing function to refresh the UI depending on the WS self._refresh_fdsnevent_widgets() self.refreshFdsnMacroseismicWidgets() self.refreshFdsnStationWidgets() # change the UI parameter according to the web service chosen self.fdsn_event_list.currentRowChanged.connect( self._refresh_fdsnevent_widgets) self.fdsn_macro_list.currentRowChanged.connect( self.refreshFdsnMacroseismicWidgets) self.fdsn_station_list.currentRowChanged.connect( self.refreshFdsnStationWidgets) self.fsdn_event_filter.changed.connect(lambda: self._refresh_url(SERVICE_MANAGER.FDSNEVENT)) self.fsdn_by_id_filter.changed.connect(lambda: self._refresh_url(SERVICE_MANAGER.FDSNEVENT)) self.fdsn_by_url_widget.changed.connect(lambda: self._refresh_url(SERVICE_MANAGER.FDSNEVENT)) self.fdsn_event_list.currentRowChanged.connect(lambda: self._refresh_url(SERVICE_MANAGER.FDSNEVENT)) self.macro_filter.changed.connect(lambda: self._refresh_url(SERVICE_MANAGER.MACROSEISMIC)) self.macro_by_id_filter.changed.connect(lambda: self._refresh_url(SERVICE_MANAGER.MACROSEISMIC)) self.macro_by_url_widget.changed.connect(lambda: self._refresh_url(SERVICE_MANAGER.MACROSEISMIC)) self.fdsn_macro_list.currentRowChanged.connect(lambda: self._refresh_url(SERVICE_MANAGER.MACROSEISMIC)) self.station_filter.changed.connect(lambda: self._refresh_url(SERVICE_MANAGER.FDSNSTATION)) self.station_by_id_filter.changed.connect(lambda: self._refresh_url(SERVICE_MANAGER.FDSNSTATION)) self.fdsn_station_list.currentRowChanged.connect(lambda: self._refresh_url(SERVICE_MANAGER.FDSNSTATION)) self.button_box.accepted.connect(self._getEventList) self.service_tab_widget.currentChanged.connect(lambda: self._refresh_url(None)) self.fetcher = None QgsGui.enableAutoGeometryRestore(self) self.fdsn_tab_widget.currentChanged.connect(lambda: self._refresh_url(SERVICE_MANAGER.FDSNEVENT)) self.macro_tab_widget.currentChanged.connect(lambda: self._refresh_url(SERVICE_MANAGER.MACROSEISMIC)) self.fdsnstation_tab_widget.currentChanged.connect(lambda: self._refresh_url(SERVICE_MANAGER.FDSNSTATION)) for b in [self.button_fdsn_new_service, self.button_macro_new_service, self.button_station_new_service, self.button_ogc_new_service]: self._build_add_service_menu(b) for b in [self.button_fdsn_edit_service, self.button_macro_edit_service, self.button_station_edit_service, self.button_ogc_edit_service]: b.clicked.connect(self._edit_service) for b in [self.button_fdsn_rename_service, self.button_macro_rename_service, self.button_station_rename_service, self.button_ogc_rename_service]: b.clicked.connect(self._rename_service) for b in [self.button_fdsn_remove_service, self.button_macro_remove_service, self.button_station_remove_service, self.button_ogc_remove_service]: b.clicked.connect(self._remove_service) for b in [self.button_fdsn_export_service, self.button_macro_export_service, self.button_station_export_service, self.button_ogc_export_service]: b.clicked.connect(self._export_service) self._restore_settings() self._refresh_url(SERVICE_MANAGER.FDSNEVENT) self._refresh_url(SERVICE_MANAGER.MACROSEISMIC) self._refresh_url(SERVICE_MANAGER.FDSNSTATION)