def __init__(self, iface): """Constructor. :param iface: An interface instance that will be passed to this class which provides the hook by which you can manipulate the QGIS application at run time. :type iface: QgsInterface """ # Save reference to the QGIS interface self.iface = iface # initialize plugin directory self.plugin_dir = dirname(__file__) # initialize locale locale = QSettings().value('locale/userLocale')[0:2] locale_path = join( self.plugin_dir, 'i18n', 'UnderMap_{}.qm'.format(locale)) if exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = UnderMapDialog() self.addop = AjouterOperateurDialog() self.addpdf = DialogAddPDF() self.splitpdf = DialogSplitPDF() self.importpoints = DialogImportPoint() self.zoomto = DialogZoomToFeature() # Initialise buttton self.init_button = QToolButton() self.init_button.setMenu(QMenu()) self.init_button.setPopupMode(QToolButton.MenuButtonPopup) # toolBar self.toolbar = self.iface.addToolBar('UnderMap') self.toolbar.setObjectName('UnderMap') # actions self.initialisePDFAction = None self.reportAction = None self.addOperatorAction = None self.initialiseFDPAction = None self.initialiseEmpriseAction = None self.addPDFAction = None self.splitPDFAction = None self.importPointsAction = None self.mergeFeaturesAction = None self.manageBufferAction = None self.saveAsGeoJsonAndTfwAction = None self.controlAction = None self.zoomToAction = None QgsSettings().setValue("qgis/digitizing/reuseLastValues", True) # For enable/disable the addpdf editor icon self.iface.currentLayerChanged.connect(self.layer_changed) # For load layer on qgis self.iface.projectRead.connect(self.load_layer)
def initGui(self): # Add GUI elements self.splash_screen = ui.SplashScreen(self) self.config_dialog = ui.ConfigDialog() self.tilesManager = tiles.TilesManager() self.toolbar = self.iface.addToolBar("Travel Time Platform Toolbar") # Logo button = QPushButton(resources.logo, "") button.setIconSize(QSize(112, 30)) button.setFlat(True) button.pressed.connect(self.show_splash) self.toolbar.addWidget(button) self.toolbar.addSeparator() # Show toolbox action self.action_show_toolbox = QAction(resources.icon_general, tr("Show the toolbox"), self.iface.mainWindow()) self.action_show_toolbox.triggered.connect(self.show_toolbox) self.toolbar.addAction(self.action_show_toolbox) self.iface.addPluginToMenu(u"&Travel Time Platform", self.action_show_toolbox) # Add tiles tiles_menu = QMenu() for key, tile in self.tilesManager.tiles.items(): action = QAction(tile["resource"], tile["label"], tiles_menu) action.triggered.connect( functools.partial(self.tilesManager.add_layer, key)) action.setEnabled(self.tilesManager.has_tiles) tiles_menu.addAction(action) if not self.tilesManager.has_tiles: action = QAction(tr("Request access to backgrounds"), tiles_menu) action.triggered.connect( lambda: self.tilesManager.request_access()) tiles_menu.addAction(action) tiles_button = QToolButton() tiles_button.setToolTip(tr("Add background")) tiles_button.setIcon(resources.icon_tiles) tiles_button.setMenu(tiles_menu) tiles_button.setPopupMode(QToolButton.InstantPopup) # self.action_show_toolbox.triggered.connect(self.show_toolbox) self.toolbar.addWidget(tiles_button) # self.iface.addPluginToMenu(u"&Travel Time Platform", self.action_show_toolbox) self.toolbar.addSeparator() # Show help actions self.action_show_help = QAction(resources.icon_help, tr("Help"), self.iface.mainWindow()) self.action_show_help.triggered.connect(self.show_splash) self.toolbar.addAction(self.action_show_help) self.iface.addPluginToMenu(u"&Travel Time Platform", self.action_show_help) # Show config actions self.action_show_config = QAction( resources.icon_config, tr("Configure Travel Time Platform plugin"), self.iface.mainWindow(), ) self.action_show_config.triggered.connect(self.show_config) self.toolbar.addAction(self.action_show_config) self.iface.addPluginToMenu(u"&Travel Time Platform", self.action_show_config) # Add the provider to the registry QgsApplication.processingRegistry().addProvider(self.provider) # Show splash screen if not QSettings().value( "travel_time_platform/spashscreen_dontshowagain", False, type=bool): self.show_splash()
def createWidget(self): if self.dialogType == DIALOG_STANDARD: widget = QWidget() layout = QHBoxLayout() layout.setMargin(0) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(2) self.combo = QgsMapLayerComboBox() layout.addWidget(self.combo) btn = QToolButton() btn.setText('...') btn.setToolTip(self.tr("Select file")) btn.clicked.connect(self.selectFile) layout.addWidget(btn) widget.setLayout(layout) if self.param.optional: self.combo.setAllowEmptyLayer(True) self.combo.setFilters(QgsMapLayerProxyModel.VectorLayer) self.combo.setExcludedProviders(['grass']) try: if iface.activeLayer().type() == QgsMapLayer.VectorLayer: self.combo.setLayer(iface.activeLayer()) except: pass self.combo.currentIndexChanged.connect( lambda: self.widgetValueHasChanged.emit(self)) self.combo.currentTextChanged.connect( lambda: self.widgetValueHasChanged.emit(self)) return widget elif self.dialogType == DIALOG_BATCH: return BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) else: self.combo = QComboBox() layers = self.dialog.getAvailableValuesOfType( ParameterRaster, OutputRaster) self.combo.setEditable(True) tables = self.dialog.getAvailableValuesOfType( ParameterTable, OutputTable) layers = self.dialog.getAvailableValuesOfType( ParameterVector, OutputVector) if self.param.optional: self.combo.addItem(self.NOT_SELECTED, None) for table in tables: self.combo.addItem(self.dialog.resolveValueDescription(table), table) for layer in layers: self.combo.addItem(self.dialog.resolveValueDescription(layer), layer) widget = QWidget() layout = QHBoxLayout() layout.setMargin(0) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(2) layout.addWidget(self.combo) btn = QToolButton() btn.setText('...') btn.setToolTip(self.tr("Select file")) btn.clicked.connect(self.selectFile) layout.addWidget(btn) widget.setLayout(layout) return widget
def initWidgets(self): # If there are advanced parameters — show corresponding groupbox for param in self.alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: self.grpAdvanced.show() break # Create widgets and put them in layouts for param in self.alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue if param.isDestination(): continue else: desc = param.description() if isinstance(param, QgsProcessingParameterExtent): desc += self.tr(' (xmin, xmax, ymin, ymax)') if isinstance(param, QgsProcessingParameterPoint): desc += self.tr(' (x, y)') if param.flags() & QgsProcessingParameterDefinition.FlagOptional: desc += self.tr(' [optional]') wrapper = WidgetWrapperFactory.create_wrapper(param, self.parent) self.wrappers[param.name()] = wrapper widget = wrapper.widget if widget is not None: if isinstance(param, QgsProcessingParameterFeatureSource): layout = QHBoxLayout() layout.setSpacing(6) layout.setMargin(0) layout.addWidget(widget) button = QToolButton() icon = QIcon(os.path.join(pluginPath, 'images', 'iterate.png')) button.setIcon(icon) button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) button.setToolTip(self.tr('Iterate over this layer, creating a separate output for every feature in the layer')) button.setCheckable(True) layout.addWidget(button) layout.setAlignment(button, Qt.AlignTop) self.iterateButtons[param.name()] = button button.toggled.connect(self.buttonToggled) widget = QWidget() widget.setLayout(layout) widget.setToolTip(param.toolTip()) if isinstance(widget, QCheckBox): # checkbox widget - so description is embedded in widget rather than a separate # label widget.setText(desc) else: label = QLabel(desc) # label.setToolTip(tooltip) self.labels[param.name()] = label if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: self.layoutAdvanced.addWidget(label) else: self.layoutMain.insertWidget( self.layoutMain.count() - 2, label) if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: self.layoutAdvanced.addWidget(widget) else: self.layoutMain.insertWidget( self.layoutMain.count() - 2, widget) for output in self.alg.destinationParameterDefinitions(): if output.flags() & QgsProcessingParameterDefinition.FlagHidden: continue label = QLabel(output.description()) widget = DestinationSelectionPanel(output, self.alg) self.layoutMain.insertWidget(self.layoutMain.count() - 1, label) self.layoutMain.insertWidget(self.layoutMain.count() - 1, widget) if isinstance(output, (QgsProcessingParameterRasterDestination, QgsProcessingParameterFeatureSink, QgsProcessingParameterVectorDestination)): check = QCheckBox() check.setText(self.tr('Open output file after running algorithm')) check.setChecked(True) self.layoutMain.insertWidget(self.layoutMain.count() - 1, check) self.checkBoxes[output.name()] = check widget.setToolTip(param.toolTip()) self.outputWidgets[output.name()] = widget for wrapper in list(self.wrappers.values()): wrapper.postInitialize(list(self.wrappers.values()))
def __init__(self, parent=None): QWidget.__init__(self, parent) self.setWindowTitle( QCoreApplication.translate("PythonConsole", "Python Console")) self.settings = QgsSettings() self.shell = ShellScintilla(self) self.setFocusProxy(self.shell) self.shellOut = ShellOutputScintilla(self) self.tabEditorWidget = EditorTabWidget(self) # ------------ UI ------------------------------- self.splitterEditor = QSplitter(self) self.splitterEditor.setOrientation(Qt.Horizontal) self.splitterEditor.setHandleWidth(6) self.splitterEditor.setChildrenCollapsible(True) self.shellOutWidget = QWidget(self) self.shellOutWidget.setLayout(QVBoxLayout()) self.shellOutWidget.layout().setContentsMargins(0, 0, 0, 0) self.shellOutWidget.layout().addWidget(self.shellOut) self.splitter = QSplitter(self.splitterEditor) self.splitter.setOrientation(Qt.Vertical) self.splitter.setHandleWidth(3) self.splitter.setChildrenCollapsible(False) self.splitter.addWidget(self.shellOutWidget) self.splitter.addWidget(self.shell) # self.splitterEditor.addWidget(self.tabEditorWidget) self.splitterObj = QSplitter(self.splitterEditor) self.splitterObj.setHandleWidth(3) self.splitterObj.setOrientation(Qt.Horizontal) # self.splitterObj.setSizes([0, 0]) # self.splitterObj.setStretchFactor(0, 1) self.widgetEditor = QWidget(self.splitterObj) self.widgetFind = QWidget(self) self.listClassMethod = QTreeWidget(self.splitterObj) self.listClassMethod.setColumnCount(2) objInspLabel = QCoreApplication.translate("PythonConsole", "Object Inspector") self.listClassMethod.setHeaderLabels([objInspLabel, '']) self.listClassMethod.setColumnHidden(1, True) self.listClassMethod.setAlternatingRowColors(True) # self.splitterEditor.addWidget(self.widgetEditor) # self.splitterObj.addWidget(self.listClassMethod) # self.splitterObj.addWidget(self.widgetEditor) # Hide side editor on start up self.splitterObj.hide() self.listClassMethod.hide() # Hide search widget on start up self.widgetFind.hide() icon_size = iface.iconSize( dockedToolbar=True) if iface else QSize(16, 16) sizes = self.splitter.sizes() self.splitter.setSizes(sizes) # ----------------Restore Settings------------------------------------ self.restoreSettingsConsole() # ------------------Toolbar Editor------------------------------------- # Action for Open File openFileBt = QCoreApplication.translate("PythonConsole", "Open Script…") self.openFileButton = QAction(self) self.openFileButton.setCheckable(False) self.openFileButton.setEnabled(True) self.openFileButton.setIcon( QgsApplication.getThemeIcon("mActionScriptOpen.svg")) self.openFileButton.setMenuRole(QAction.PreferencesRole) self.openFileButton.setIconVisibleInMenu(True) self.openFileButton.setToolTip(openFileBt) self.openFileButton.setText(openFileBt) openExtEditorBt = QCoreApplication.translate( "PythonConsole", "Open in External Editor") self.openInEditorButton = QAction(self) self.openInEditorButton.setCheckable(False) self.openInEditorButton.setEnabled(True) self.openInEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconShowEditorConsole.svg")) self.openInEditorButton.setMenuRole(QAction.PreferencesRole) self.openInEditorButton.setIconVisibleInMenu(True) self.openInEditorButton.setToolTip(openExtEditorBt) self.openInEditorButton.setText(openExtEditorBt) # Action for Save File saveFileBt = QCoreApplication.translate("PythonConsole", "Save") self.saveFileButton = QAction(self) self.saveFileButton.setCheckable(False) self.saveFileButton.setEnabled(False) self.saveFileButton.setIcon( QgsApplication.getThemeIcon("mActionFileSave.svg")) self.saveFileButton.setMenuRole(QAction.PreferencesRole) self.saveFileButton.setIconVisibleInMenu(True) self.saveFileButton.setToolTip(saveFileBt) self.saveFileButton.setText(saveFileBt) # Action for Save File As saveAsFileBt = QCoreApplication.translate("PythonConsole", "Save As…") self.saveAsFileButton = QAction(self) self.saveAsFileButton.setCheckable(False) self.saveAsFileButton.setEnabled(True) self.saveAsFileButton.setIcon( QgsApplication.getThemeIcon("mActionFileSaveAs.svg")) self.saveAsFileButton.setMenuRole(QAction.PreferencesRole) self.saveAsFileButton.setIconVisibleInMenu(True) self.saveAsFileButton.setToolTip(saveAsFileBt) self.saveAsFileButton.setText(saveAsFileBt) # Action Cut cutEditorBt = QCoreApplication.translate("PythonConsole", "Cut") self.cutEditorButton = QAction(self) self.cutEditorButton.setCheckable(False) self.cutEditorButton.setEnabled(True) self.cutEditorButton.setIcon( QgsApplication.getThemeIcon("mActionEditCut.svg")) self.cutEditorButton.setMenuRole(QAction.PreferencesRole) self.cutEditorButton.setIconVisibleInMenu(True) self.cutEditorButton.setToolTip(cutEditorBt) self.cutEditorButton.setText(cutEditorBt) # Action Copy copyEditorBt = QCoreApplication.translate("PythonConsole", "Copy") self.copyEditorButton = QAction(self) self.copyEditorButton.setCheckable(False) self.copyEditorButton.setEnabled(True) self.copyEditorButton.setIcon( QgsApplication.getThemeIcon("mActionEditCopy.svg")) self.copyEditorButton.setMenuRole(QAction.PreferencesRole) self.copyEditorButton.setIconVisibleInMenu(True) self.copyEditorButton.setToolTip(copyEditorBt) self.copyEditorButton.setText(copyEditorBt) # Action Paste pasteEditorBt = QCoreApplication.translate("PythonConsole", "Paste") self.pasteEditorButton = QAction(self) self.pasteEditorButton.setCheckable(False) self.pasteEditorButton.setEnabled(True) self.pasteEditorButton.setIcon( QgsApplication.getThemeIcon("mActionEditPaste.svg")) self.pasteEditorButton.setMenuRole(QAction.PreferencesRole) self.pasteEditorButton.setIconVisibleInMenu(True) self.pasteEditorButton.setToolTip(pasteEditorBt) self.pasteEditorButton.setText(pasteEditorBt) # Action Run Script (subprocess) runScriptEditorBt = QCoreApplication.translate("PythonConsole", "Run Script") self.runScriptEditorButton = QAction(self) self.runScriptEditorButton.setCheckable(False) self.runScriptEditorButton.setEnabled(True) self.runScriptEditorButton.setIcon( QgsApplication.getThemeIcon("mActionStart.svg")) self.runScriptEditorButton.setMenuRole(QAction.PreferencesRole) self.runScriptEditorButton.setIconVisibleInMenu(True) self.runScriptEditorButton.setToolTip(runScriptEditorBt) self.runScriptEditorButton.setText(runScriptEditorBt) # Action Run Script (subprocess) commentEditorBt = QCoreApplication.translate("PythonConsole", "Comment") self.commentEditorButton = QAction(self) self.commentEditorButton.setCheckable(False) self.commentEditorButton.setEnabled(True) self.commentEditorButton.setIcon( QgsApplication.getThemeIcon( "console/iconCommentEditorConsole.svg")) self.commentEditorButton.setMenuRole(QAction.PreferencesRole) self.commentEditorButton.setIconVisibleInMenu(True) self.commentEditorButton.setToolTip(commentEditorBt) self.commentEditorButton.setText(commentEditorBt) # Action Run Script (subprocess) uncommentEditorBt = QCoreApplication.translate("PythonConsole", "Uncomment") self.uncommentEditorButton = QAction(self) self.uncommentEditorButton.setCheckable(False) self.uncommentEditorButton.setEnabled(True) self.uncommentEditorButton.setIcon( QgsApplication.getThemeIcon( "console/iconUncommentEditorConsole.svg")) self.uncommentEditorButton.setMenuRole(QAction.PreferencesRole) self.uncommentEditorButton.setIconVisibleInMenu(True) self.uncommentEditorButton.setToolTip(uncommentEditorBt) self.uncommentEditorButton.setText(uncommentEditorBt) # Action for Object browser objList = QCoreApplication.translate("PythonConsole", "Object Inspector…") self.objectListButton = QAction(self) self.objectListButton.setCheckable(True) self.objectListButton.setEnabled( self.settings.value("pythonConsole/enableObjectInsp", False, type=bool)) self.objectListButton.setIcon( QgsApplication.getThemeIcon("console/iconClassBrowserConsole.svg")) self.objectListButton.setMenuRole(QAction.PreferencesRole) self.objectListButton.setIconVisibleInMenu(True) self.objectListButton.setToolTip(objList) self.objectListButton.setText(objList) # Action for Find text findText = QCoreApplication.translate("PythonConsole", "Find Text") self.findTextButton = QAction(self) self.findTextButton.setCheckable(True) self.findTextButton.setEnabled(True) self.findTextButton.setIcon( QgsApplication.getThemeIcon("console/iconSearchEditorConsole.svg")) self.findTextButton.setMenuRole(QAction.PreferencesRole) self.findTextButton.setIconVisibleInMenu(True) self.findTextButton.setToolTip(findText) self.findTextButton.setText(findText) # ----------------Toolbar Console------------------------------------- # Action Show Editor showEditor = QCoreApplication.translate("PythonConsole", "Show Editor") self.showEditorButton = QAction(self) self.showEditorButton.setEnabled(True) self.showEditorButton.setCheckable(True) self.showEditorButton.setIcon( QgsApplication.getThemeIcon("console/iconShowEditorConsole.svg")) self.showEditorButton.setMenuRole(QAction.PreferencesRole) self.showEditorButton.setIconVisibleInMenu(True) self.showEditorButton.setToolTip(showEditor) self.showEditorButton.setText(showEditor) # Action for Clear button clearBt = QCoreApplication.translate("PythonConsole", "Clear Console") self.clearButton = QAction(self) self.clearButton.setCheckable(False) self.clearButton.setEnabled(True) self.clearButton.setIcon( QgsApplication.getThemeIcon("console/iconClearConsole.svg")) self.clearButton.setMenuRole(QAction.PreferencesRole) self.clearButton.setIconVisibleInMenu(True) self.clearButton.setToolTip(clearBt) self.clearButton.setText(clearBt) # Action for settings optionsBt = QCoreApplication.translate("PythonConsole", "Options…") self.optionsButton = QAction(self) self.optionsButton.setCheckable(False) self.optionsButton.setEnabled(True) self.optionsButton.setIcon( QgsApplication.getThemeIcon("console/iconSettingsConsole.svg")) self.optionsButton.setMenuRole(QAction.PreferencesRole) self.optionsButton.setIconVisibleInMenu(True) self.optionsButton.setToolTip(optionsBt) self.optionsButton.setText(optionsBt) # Action for Run script runBt = QCoreApplication.translate("PythonConsole", "Run Command") self.runButton = QAction(self) self.runButton.setCheckable(False) self.runButton.setEnabled(True) self.runButton.setIcon( QgsApplication.getThemeIcon("console/mIconRunConsole.svg")) self.runButton.setMenuRole(QAction.PreferencesRole) self.runButton.setIconVisibleInMenu(True) self.runButton.setToolTip(runBt) self.runButton.setText(runBt) # Help button self.helpConsoleAction = QAction(self) self.helpConsoleAction.setEnabled(True) self.helpConsoleAction.setText( QCoreApplication.translate("PythonConsole", "Python Console Help")) self.helpAPIAction = QAction(self) self.helpAPIAction.setEnabled(True) self.helpAPIAction.setText( QCoreApplication.translate("PythonConsole", "PyQGIS API Documentation")) self.helpCookbookAction = QAction(self) self.helpCookbookAction.setEnabled(True) self.helpCookbookAction.setText( QCoreApplication.translate("PythonConsole", "PyQGIS Cookbook")) self.helpMenu = QMenu(self) self.helpMenu.addAction(self.helpConsoleAction) self.helpMenu.addAction(self.helpAPIAction) self.helpMenu.addAction(self.helpCookbookAction) helpBt = QCoreApplication.translate("PythonConsole", "Help…") self.helpButton = QToolButton(self) self.helpButton.setPopupMode(QToolButton.InstantPopup) self.helpButton.setEnabled(True) self.helpButton.setIcon( QgsApplication.getThemeIcon("console/iconHelpConsole.svg")) self.helpButton.setToolTip(helpBt) self.helpButton.setMenu(self.helpMenu) self.toolBar = QToolBar() self.toolBar.setEnabled(True) self.toolBar.setFocusPolicy(Qt.NoFocus) self.toolBar.setContextMenuPolicy(Qt.DefaultContextMenu) self.toolBar.setLayoutDirection(Qt.LeftToRight) self.toolBar.setIconSize(icon_size) self.toolBar.setMovable(False) self.toolBar.setFloatable(False) self.toolBar.addAction(self.clearButton) self.toolBar.addAction(self.runButton) self.toolBar.addSeparator() self.toolBar.addAction(self.showEditorButton) self.toolBar.addSeparator() self.toolBar.addAction(self.optionsButton) self.toolBar.addWidget(self.helpButton) self.toolBarEditor = QToolBar() self.toolBarEditor.setEnabled(False) self.toolBarEditor.setFocusPolicy(Qt.NoFocus) self.toolBarEditor.setContextMenuPolicy(Qt.DefaultContextMenu) self.toolBarEditor.setLayoutDirection(Qt.LeftToRight) self.toolBarEditor.setIconSize(icon_size) self.toolBarEditor.setMovable(False) self.toolBarEditor.setFloatable(False) self.toolBarEditor.addAction(self.openFileButton) self.toolBarEditor.addAction(self.openInEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.saveFileButton) self.toolBarEditor.addAction(self.saveAsFileButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.runScriptEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.cutEditorButton) self.toolBarEditor.addAction(self.copyEditorButton) self.toolBarEditor.addAction(self.pasteEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.findTextButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.commentEditorButton) self.toolBarEditor.addAction(self.uncommentEditorButton) self.toolBarEditor.addSeparator() self.toolBarEditor.addAction(self.objectListButton) self.widgetButton = QWidget() sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.widgetButton.sizePolicy().hasHeightForWidth()) self.widgetButton.setSizePolicy(sizePolicy) self.widgetButtonEditor = QWidget(self.widgetEditor) sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.widgetButtonEditor.sizePolicy().hasHeightForWidth()) self.widgetButtonEditor.setSizePolicy(sizePolicy) sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.shellOut.sizePolicy().hasHeightForWidth()) self.shellOut.setSizePolicy(sizePolicy) self.shellOut.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) self.shell.setVerticalScrollBarPolicy(Qt.ScrollBarAsNeeded) # ------------ Layout ------------------------------- self.mainLayout = QGridLayout(self) self.mainLayout.setMargin(0) self.mainLayout.setSpacing(0) self.mainLayout.addWidget(self.widgetButton, 0, 0, 1, 1) self.mainLayout.addWidget(self.splitterEditor, 0, 1, 1, 1) self.shellOutWidget.layout().insertWidget(0, self.toolBar) self.layoutEditor = QGridLayout(self.widgetEditor) self.layoutEditor.setMargin(0) self.layoutEditor.setSpacing(0) self.layoutEditor.addWidget(self.toolBarEditor, 0, 1, 1, 1) self.layoutEditor.addWidget(self.widgetButtonEditor, 1, 0, 2, 1) self.layoutEditor.addWidget(self.tabEditorWidget, 1, 1, 1, 1) self.layoutEditor.addWidget(self.widgetFind, 2, 1, 1, 1) # Layout for the find widget self.layoutFind = QGridLayout(self.widgetFind) self.layoutFind.setContentsMargins(0, 0, 0, 0) self.lineEditFind = QgsFilterLineEdit() self.lineEditFind.setShowSearchIcon(True) placeHolderTxt = QCoreApplication.translate("PythonConsole", "Enter text to find…") self.lineEditFind.setPlaceholderText(placeHolderTxt) self.toolBarFindText = QToolBar() self.toolBarFindText.setIconSize(icon_size) self.findNextButton = QAction(self) self.findNextButton.setEnabled(False) toolTipfindNext = QCoreApplication.translate("PythonConsole", "Find Next") self.findNextButton.setToolTip(toolTipfindNext) self.findNextButton.setIcon( QgsApplication.getThemeIcon( "console/iconSearchNextEditorConsole.svg")) self.findPrevButton = QAction(self) self.findPrevButton.setEnabled(False) toolTipfindPrev = QCoreApplication.translate("PythonConsole", "Find Previous") self.findPrevButton.setToolTip(toolTipfindPrev) self.findPrevButton.setIcon( QgsApplication.getThemeIcon( "console/iconSearchPrevEditorConsole.svg")) self.caseSensitive = QCheckBox() caseSensTr = QCoreApplication.translate("PythonConsole", "Case Sensitive") self.caseSensitive.setText(caseSensTr) self.wholeWord = QCheckBox() wholeWordTr = QCoreApplication.translate("PythonConsole", "Whole Word") self.wholeWord.setText(wholeWordTr) self.wrapAround = QCheckBox() self.wrapAround.setChecked(True) wrapAroundTr = QCoreApplication.translate("PythonConsole", "Wrap Around") self.wrapAround.setText(wrapAroundTr) self.toolBarFindText.addWidget(self.lineEditFind) self.toolBarFindText.addAction(self.findPrevButton) self.toolBarFindText.addAction(self.findNextButton) self.toolBarFindText.addWidget(self.caseSensitive) self.toolBarFindText.addWidget(self.wholeWord) self.toolBarFindText.addWidget(self.wrapAround) self.layoutFind.addWidget(self.toolBarFindText, 0, 1, 1, 1) # ------------ Add first Tab in Editor ------------------------------- # self.tabEditorWidget.newTabEditor(tabName='first', filename=None) # ------------ Signal ------------------------------- self.findTextButton.triggered.connect(self._toggleFind) self.objectListButton.toggled.connect(self.toggleObjectListWidget) self.commentEditorButton.triggered.connect(self.commentCode) self.uncommentEditorButton.triggered.connect(self.uncommentCode) self.runScriptEditorButton.triggered.connect(self.runScriptEditor) self.cutEditorButton.triggered.connect(self.cutEditor) self.copyEditorButton.triggered.connect(self.copyEditor) self.pasteEditorButton.triggered.connect(self.pasteEditor) self.showEditorButton.toggled.connect(self.toggleEditor) self.clearButton.triggered.connect(self.shellOut.clearConsole) self.optionsButton.triggered.connect(self.openSettings) self.runButton.triggered.connect(self.shell.entered) self.openFileButton.triggered.connect(self.openScriptFile) self.openInEditorButton.triggered.connect(self.openScriptFileExtEditor) self.saveFileButton.triggered.connect(self.saveScriptFile) self.saveAsFileButton.triggered.connect(self.saveAsScriptFile) self.helpConsoleAction.triggered.connect(self.openHelpConsole) self.helpAPIAction.triggered.connect(self.openHelpAPI) self.helpCookbookAction.triggered.connect(self.openHelpCookbook) self.listClassMethod.itemClicked.connect(self.onClickGoToLine) self.lineEditFind.returnPressed.connect(self._findNext) self.findNextButton.triggered.connect(self._findNext) self.findPrevButton.triggered.connect(self._findPrev) self.lineEditFind.textChanged.connect(self._textFindChanged) self.findScut = QShortcut(QKeySequence.Find, self.widgetEditor) self.findScut.setContext(Qt.WidgetWithChildrenShortcut) self.findScut.activated.connect(self._openFind) self.findNextScut = QShortcut(QKeySequence.FindNext, self.widgetEditor) self.findNextScut.setContext(Qt.WidgetWithChildrenShortcut) self.findNextScut.activated.connect(self._findNext) self.findPreviousScut = QShortcut(QKeySequence.FindPrevious, self.widgetEditor) self.findPreviousScut.setContext(Qt.WidgetWithChildrenShortcut) self.findPreviousScut.activated.connect(self._findPrev) # Escape on editor hides the find bar self.findScut = QShortcut(Qt.Key_Escape, self.widgetEditor) self.findScut.setContext(Qt.WidgetWithChildrenShortcut) self.findScut.activated.connect(self._closeFind)
def initGui(self): '''Initialize Lot Lon Tools GUI.''' # Initialize the Settings Dialog box self.settingsDialog = SettingsWidget(self, self.iface, self.iface.mainWindow()) # Add Interface for Coordinate Capturing icon = QIcon(os.path.dirname(__file__) + "/images/copyicon.svg") self.copyAction = QAction(icon, "Copy/Display Coordinate", self.iface.mainWindow()) self.copyAction.setObjectName('latLonToolsCopy') self.copyAction.triggered.connect(self.startCapture) self.copyAction.setCheckable(True) self.toolbar.addAction(self.copyAction) self.iface.addPluginToMenu("Lat Lon Tools", self.copyAction) # Add Interface for External Map icon = QIcon(os.path.dirname(__file__) + "/images/mapicon.png") self.externMapAction = QAction(icon, "Show in External Map", self.iface.mainWindow()) self.externMapAction.setObjectName('latLonToolsExternalMap') self.externMapAction.triggered.connect(self.setShowMapTool) self.externMapAction.setCheckable(True) self.toolbar.addAction(self.externMapAction) self.iface.addPluginToMenu("Lat Lon Tools", self.externMapAction) # Add Interface for Zoom to Coordinate icon = QIcon(os.path.dirname(__file__) + "/images/zoomicon.svg") self.zoomToAction = QAction(icon, "Zoom To Coordinate", self.iface.mainWindow()) self.zoomToAction.setObjectName('latLonToolsZoom') self.zoomToAction.triggered.connect(self.showZoomToDialog) self.toolbar.addAction(self.zoomToAction) self.iface.addPluginToMenu('Lat Lon Tools', self.zoomToAction) self.zoomToDialog = ZoomToLatLon(self, self.iface, self.iface.mainWindow()) self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.zoomToDialog) self.zoomToDialog.hide() # Add Interface for Multi point zoom icon = QIcon(os.path.dirname(__file__) + '/images/multizoom.svg') self.multiZoomToAction = QAction(icon, "Multi-location Zoom", self.iface.mainWindow()) self.multiZoomToAction.setObjectName('latLonToolsMultiZoom') self.multiZoomToAction.triggered.connect(self.multiZoomTo) self.toolbar.addAction(self.multiZoomToAction) self.iface.addPluginToMenu('Lat Lon Tools', self.multiZoomToAction) self.multiZoomDialog = MultiZoomWidget(self, self.settingsDialog, self.iface.mainWindow()) self.multiZoomDialog.hide() self.multiZoomDialog.setFloating(True) menu = QMenu() # Add Interface for copying the canvas extent icon = QIcon(os.path.dirname(__file__) + "/images/copycanvas.svg") self.copyCanvasAction = menu.addAction(icon, 'Copy Canvas Extent', self.copyCanvas) self.copyCanvasAction.setObjectName('latLonToolsCopyCanvasExtent') # Add Interface for copying an interactive extent icon = QIcon(os.path.dirname(__file__) + "/images/copyextent.svg") self.copyExtentAction = menu.addAction(icon, 'Copy Selected Area Extent', self.copyExtent) self.copyExtentAction.setCheckable(True) self.copyExtentAction.setObjectName( 'latLonToolsCopySelectedAreaExtent') # Add Interface for copying a layer extent icon = QIcon(os.path.dirname(__file__) + "/images/copylayerextent.svg") self.copyLayerExtentAction = menu.addAction(icon, 'Copy Layer Extent', self.copyLayerExtent) self.copyLayerExtentAction.setObjectName('latLonToolsCopyLayerExtent') # Add Interface for copying the extent of selected features icon = QIcon( os.path.dirname(__file__) + "/images/copyselectedlayerextent.svg") self.copySelectedFeaturesExtentAction = menu.addAction( icon, 'Copy Selected Features Extent', self.copySelectedFeaturesExtent) self.copySelectedFeaturesExtentAction.setObjectName( 'latLonToolsCopySelectedFeaturesExtent') # Add the copy extent tools to the menu icon = QIcon(os.path.dirname(__file__) + '/images/copylayerextent.svg') self.copyExtentsAction = QAction(icon, 'Copy Extents to Clipboard', self.iface.mainWindow()) self.copyExtentsAction.setMenu(menu) self.iface.addPluginToMenu('Lat Lon Tools', self.copyExtentsAction) # Add the copy extent tools to the toolbar self.copyExtentButton = QToolButton() self.copyExtentButton.setMenu(menu) self.copyExtentButton.setDefaultAction(self.copyCanvasAction) self.copyExtentButton.setPopupMode(QToolButton.MenuButtonPopup) self.copyExtentButton.triggered.connect(self.copyExtentTriggered) self.copyExtentToolbar = self.toolbar.addWidget(self.copyExtentButton) # Create the coordinate converter menu icon = QIcon(':/images/themes/default/mIconProjectionEnabled.svg') self.convertCoordinatesAction = QAction(icon, "Coordinate Conversion", self.iface.mainWindow()) self.convertCoordinatesAction.setObjectName( 'latLonToolsCoordinateConversion') self.convertCoordinatesAction.triggered.connect( self.convertCoordinatesTool) self.toolbar.addAction(self.convertCoordinatesAction) self.iface.addPluginToMenu("Lat Lon Tools", self.convertCoordinatesAction) # Create the conversions menu menu = QMenu() icon = QIcon(os.path.dirname(__file__) + '/images/field2geom.svg') action = menu.addAction(icon, "Fields to point layer", self.field2geom) action.setObjectName('latLonToolsField2Geom') icon = QIcon(os.path.dirname(__file__) + '/images/geom2field.svg') action = menu.addAction(icon, "Point layer to fields", self.geom2Field) action.setObjectName('latLonToolsGeom2Field') icon = QIcon(os.path.dirname(__file__) + '/images/pluscodes.svg') action = menu.addAction(icon, "Plus Codes to point layer", self.PlusCodestoLayer) action.setObjectName('latLonToolsPlusCodes2Geom') action = menu.addAction(icon, "Point layer to Plus Codes", self.toPlusCodes) action.setObjectName('latLonToolsGeom2PlusCodes') icon = QIcon(os.path.dirname(__file__) + '/images/mgrs2point.svg') action = menu.addAction(icon, "MGRS to point layer", self.MGRStoLayer) action.setObjectName('latLonToolsMGRS2Geom') icon = QIcon(os.path.dirname(__file__) + '/images/point2mgrs.svg') action = menu.addAction(icon, "Point layer to MGRS", self.toMGRS) action.setObjectName('latLonToolsGeom2MGRS') self.conversionsAction = QAction(icon, "Conversions", self.iface.mainWindow()) self.conversionsAction.setMenu(menu) self.iface.addPluginToMenu('Lat Lon Tools', self.conversionsAction) # Add to Digitize Toolbar icon = QIcon(os.path.dirname(__file__) + '/images/latLonDigitize.svg') self.digitizeAction = QAction(icon, "Lat Lon Digitize", self.iface.mainWindow()) self.digitizeAction.setObjectName('latLonToolsDigitize') self.digitizeAction.triggered.connect(self.digitizeClicked) self.digitizeAction.setEnabled(False) self.toolbar.addAction(self.digitizeAction) self.iface.addPluginToMenu('Lat Lon Tools', self.digitizeAction) # Initialize the Settings Dialog Box settingsicon = QIcon(':/images/themes/default/mActionOptions.svg') self.settingsAction = QAction(settingsicon, "Settings", self.iface.mainWindow()) self.settingsAction.setObjectName('latLonToolsSettings') self.settingsAction.setToolTip('Lat Lon Tools Settings') self.settingsAction.triggered.connect(self.settings) self.toolbar.addAction(self.settingsAction) self.iface.addPluginToMenu('Lat Lon Tools', self.settingsAction) # Help icon = QIcon(os.path.dirname(__file__) + '/images/help.svg') self.helpAction = QAction(icon, "Help", self.iface.mainWindow()) self.helpAction.setObjectName('latLonToolsHelp') self.helpAction.triggered.connect(self.help) self.iface.addPluginToMenu('Lat Lon Tools', self.helpAction) self.iface.currentLayerChanged.connect(self.currentLayerChanged) self.canvas.mapToolSet.connect(self.resetTools) self.enableDigitizeTool() # Add the processing provider QgsApplication.processingRegistry().addProvider(self.provider) InitLatLonFunctions()
def initWidgets(self): # If there are advanced parameters — show corresponding groupbox for param in self.alg.parameters: if param.isAdvanced: self.grpAdvanced.show() break # Create widgets and put them in layouts for param in self.alg.parameters: if param.hidden: continue desc = param.description if isinstance(param, ParameterExtent): desc += self.tr(' (xmin, xmax, ymin, ymax)') if isinstance(param, ParameterPoint): desc += self.tr(' (x, y)') if param.optional: desc += self.tr(' [optional]') wrapper = self.getWidgetWrapperFromParameter(param) self.wrappers[param.name] = wrapper self.valueItems[param.name] = wrapper.widget widget = wrapper.widget if isinstance(param, ParameterVector): layout = QHBoxLayout() layout.setSpacing(2) layout.setMargin(0) layout.addWidget(widget) button = QToolButton() icon = QIcon(os.path.join(pluginPath, 'images', 'iterate.png')) button.setIcon(icon) button.setToolTip(self.tr('Iterate over this layer')) button.setCheckable(True) layout.addWidget(button) self.iterateButtons[param.name] = button button.toggled.connect(self.buttonToggled) widget = QWidget() widget.setLayout(layout) tooltips = self.alg.getParameterDescriptions() widget.setToolTip(tooltips.get(param.name, param.description)) label = QLabel(desc) # label.setToolTip(tooltip) self.labels[param.name] = label if param.isAdvanced: self.layoutAdvanced.addWidget(label) self.layoutAdvanced.addWidget(widget) else: self.layoutMain.insertWidget(self.layoutMain.count() - 2, label) self.layoutMain.insertWidget(self.layoutMain.count() - 2, widget) self.widgets[param.name] = widget for output in self.alg.outputs: if output.hidden: continue label = QLabel(output.description) widget = OutputSelectionPanel(output, self.alg) self.layoutMain.insertWidget(self.layoutMain.count() - 1, label) self.layoutMain.insertWidget(self.layoutMain.count() - 1, widget) if isinstance(output, (OutputRaster, OutputVector, OutputTable)): check = QCheckBox() check.setText( self.tr('Open output file after running algorithm')) check.setChecked(True) self.layoutMain.insertWidget(self.layoutMain.count() - 1, check) self.checkBoxes[output.name] = check self.valueItems[output.name] = widget for wrapper in list(self.wrappers.values()): wrapper.postInitialize(list(self.wrappers.values()))
def initGui(self): self.azDigitizerTool = AzDigitizerTool(self.iface) self.lineDigitizerTool = LineDigitizerTool(self.iface) # Initialize the create shape menu item icon = QIcon(os.path.dirname(__file__) + '/images/shapes.png') self.shapeAction = QAction(icon, tr('Create shapes'), self.iface.mainWindow()) self.shapeAction.setObjectName('stCreateShapes') self.shapeAction.triggered.connect(self.shapeTool) self.iface.addPluginToVectorMenu('Shape Tools', self.shapeAction) self.toolbar.addAction(self.shapeAction) # Initialize the XY to Line menu item icon = QIcon(os.path.dirname(__file__) + '/images/xyline.png') self.xyLineAction = QAction(icon, tr('XY to Line'), self.iface.mainWindow()) self.xyLineAction.setObjectName('stXYtoLine') self.xyLineAction.triggered.connect(self.xyLineTool) self.iface.addPluginToVectorMenu('Shape Tools', self.xyLineAction) self.toolbar.addAction(self.xyLineAction) # Initialize the Geodesic Densifier menu item icon = QIcon( os.path.dirname(__file__) + '/images/geodesicDensifier.png') self.geodesicDensifyAction = QAction(icon, tr('Geodesic shape densifier'), self.iface.mainWindow()) self.geodesicDensifyAction.setObjectName('stGeodesicDensifier') self.geodesicDensifyAction.triggered.connect(self.geodesicDensifyTool) self.iface.addPluginToVectorMenu('Shape Tools', self.geodesicDensifyAction) self.toolbar.addAction(self.geodesicDensifyAction) # Initialize the Geodesic line break menu item icon = QIcon(os.path.dirname(__file__) + '/images/idlbreak.png') self.geodesicLineBreakAction = QAction( icon, tr('Geodesic line break at -180,180'), self.iface.mainWindow()) self.geodesicLineBreakAction.setObjectName('stGeodesicLineBreak') self.geodesicLineBreakAction.triggered.connect( self.geodesicLineBreakTool) self.iface.addPluginToVectorMenu('Shape Tools', self.geodesicLineBreakAction) self.toolbar.addAction(self.geodesicLineBreakAction) # Initialize Geodesic Measure Tool self.geodesicMeasureTool = GeodesicMeasureTool(self.iface, self.iface.mainWindow()) icon = QIcon(os.path.dirname(__file__) + '/images/measure.png') self.measureAction = QAction(icon, tr('Geodesic measure tool'), self.iface.mainWindow()) self.measureAction.setObjectName('stGeodesicMeasureTool') self.measureAction.triggered.connect(self.measureTool) self.measureAction.setCheckable(True) self.iface.addPluginToVectorMenu('Shape Tools', self.measureAction) self.toolbar.addAction(self.measureAction) # Initialize Geodesic Measurement layer icon = QIcon(os.path.dirname(__file__) + '/images/measureLine.png') self.measureLayerAction = QAction(icon, tr('Geodesic measurement layer'), self.iface.mainWindow()) self.measureLayerAction.setObjectName('stGeodesicLineBreak') self.measureLayerAction.triggered.connect(self.measureLayerTool) self.iface.addPluginToVectorMenu('Shape Tools', self.measureLayerAction) self.toolbar.addAction(self.measureLayerAction) menu = QMenu() # Initialize Geodesic transformation tool icon = QIcon(os.path.dirname(__file__) + '/images/transformShape.png') self.transformationsAction = menu.addAction( icon, tr('Geodesic transformations'), self.transformTool) self.transformationsAction.setObjectName('stGeodesicTransformations') icon = QIcon(os.path.dirname(__file__) + '/images/flip.png') self.flipRotateAction = menu.addAction(icon, tr('Geodesic flip and rotate'), self.flipRotateTool) self.flipRotateAction.setObjectName('stGeodesicFlipRotate') icon = QIcon(os.path.dirname(__file__) + '/images/flipHorizontal.png') self.flipHorizontalAction = menu.addAction(icon, tr('Flip horizontal'), self.flipHorizontalTool) self.flipHorizontalAction.setObjectName('stGeodesicFlipHorizontal') self.flipHorizontalAction.setEnabled(False) icon = QIcon(os.path.dirname(__file__) + '/images/flipVertical.png') self.flipVerticalAction = menu.addAction(icon, tr('Flip vertical'), self.flipVerticalTool) self.flipVerticalAction.setObjectName('stGeodesicFlipVertical') self.flipVerticalAction.setEnabled(False) icon = QIcon(os.path.dirname(__file__) + '/images/rotate180.png') self.rotate180Action = menu.addAction(icon, tr('Rotate 180\xb0'), self.rotate180Tool) self.rotate180Action.setObjectName('stGeodesicRotate180') self.rotate180Action.setEnabled(False) icon = QIcon(os.path.dirname(__file__) + '/images/rotatecw.png') self.rotate90CWAction = menu.addAction(icon, tr('Rotate 90\xb0 CW'), self.rotate90CWTool) self.rotate90CWAction.setObjectName('stGeodesicRotate90CW') self.rotate90CWAction.setEnabled(False) icon = QIcon(os.path.dirname(__file__) + '/images/rotateccw.png') self.rotate90CCWAction = menu.addAction(icon, tr('Rotate 90\xb0 CCW'), self.rotate90CCWTool) self.rotate90CCWAction.setObjectName('stGeodesicRotate90CCW') self.rotate90CCWAction.setEnabled(False) self.transformsAction = QAction(icon, tr('Geodesic Transforms'), self.iface.mainWindow()) self.transformsAction.setMenu(menu) self.iface.addPluginToVectorMenu('Shape Tools', self.transformsAction) self.transformationButton = QToolButton() self.transformationButton.setMenu(menu) self.transformationButton.setDefaultAction(self.transformationsAction) self.transformationButton.setPopupMode(QToolButton.MenuButtonPopup) self.transformationButton.triggered.connect(self.toolButtonTriggered) self.tranformToolbar = self.toolbar.addWidget( self.transformationButton) # Initialize the Azimuth Distance Digitize function icon = QIcon(os.path.dirname(__file__) + '/images/dazdigitize.png') self.digitizeAction = QAction(icon, tr('Azimuth distance digitizer'), self.iface.mainWindow()) self.digitizeAction.setObjectName('stAzDistanceDigitizer') self.digitizeAction.triggered.connect(self.setShowAzDigitizerTool) self.digitizeAction.setCheckable(True) self.digitizeAction.setEnabled(False) self.iface.addPluginToVectorMenu(u'Shape Tools', self.digitizeAction) self.toolbar.addAction(self.digitizeAction) # Initialize the multi point azimuth Digitize function icon = QIcon(os.path.dirname(__file__) + '/images/linedigitize.png') self.lineDigitizeAction = QAction( icon, tr('Azimuth distance sequence digitizer'), self.iface.mainWindow()) self.lineDigitizeAction.setObjectName('stLineDigitizer') self.lineDigitizeAction.triggered.connect(self.setShowLineDigitizeTool) self.lineDigitizeAction.setCheckable(True) self.lineDigitizeAction.setEnabled(False) self.iface.addPluginToVectorMenu(u'Shape Tools', self.lineDigitizeAction) self.toolbar.addAction(self.lineDigitizeAction) # Settings icon = QIcon(os.path.dirname(__file__) + '/images/settings.png') self.settingsAction = QAction(icon, tr('Settings'), self.iface.mainWindow()) self.settingsAction.setObjectName('shapeToolsSettings') self.settingsAction.triggered.connect(self.settings) self.iface.addPluginToVectorMenu('Shape Tools', self.settingsAction) # Help icon = QIcon(os.path.dirname(__file__) + '/images/help.png') self.helpAction = QAction(icon, tr('Shape Tools help'), self.iface.mainWindow()) self.helpAction.setObjectName('shapeToolsHelp') self.helpAction.triggered.connect(self.help) self.iface.addPluginToVectorMenu('Shape Tools', self.helpAction) self.iface.currentLayerChanged.connect(self.currentLayerChanged) self.canvas.mapToolSet.connect(self.unsetTool) self.enableTools() # Add the processing provider QgsApplication.processingRegistry().addProvider(self.provider)
def initWidgets(self): # If there are advanced parameters — show corresponding groupbox for param in self.alg.parameters: if param.isAdvanced: self.grpAdvanced.show() break # Create widgets and put them in layouts for param in self.alg.parameters: if param.hidden: continue desc = param.description if isinstance(param, ParameterExtent): desc += self.tr(' (xmin, xmax, ymin, ymax)') if isinstance(param, ParameterPoint): desc += self.tr(' (x, y)') try: if param.optional: desc += self.tr(' [optional]') except: pass widget = self.getWidgetFromParameter(param) self.valueItems[param.name] = widget if isinstance(param, ParameterVector) and \ not self.alg.allowOnlyOpenedLayers: layout = QHBoxLayout() layout.setSpacing(2) layout.setMargin(0) layout.addWidget(widget) button = QToolButton() icon = QIcon(os.path.join(pluginPath, 'images', 'iterate.png')) button.setIcon(icon) button.setToolTip(self.tr('Iterate over this layer')) button.setCheckable(True) layout.addWidget(button) self.iterateButtons[param.name] = button button.toggled.connect(self.buttonToggled) widget = QWidget() widget.setLayout(layout) tooltips = self.alg.getParameterDescriptions() widget.setToolTip(tooltips.get(param.name, param.description)) if isinstance(param, ParameterBoolean): widget.setText(desc) if param.isAdvanced: self.layoutAdvanced.addWidget(widget) else: self.layoutMain.insertWidget( self.layoutMain.count() - 2, widget) else: label = QLabel(desc) #label.setToolTip(tooltip) self.labels[param.name] = label if param.isAdvanced: self.layoutAdvanced.addWidget(label) self.layoutAdvanced.addWidget(widget) else: self.layoutMain.insertWidget( self.layoutMain.count() - 2, label) self.layoutMain.insertWidget( self.layoutMain.count() - 2, widget) self.widgets[param.name] = widget for output in self.alg.outputs: if output.hidden: continue label = QLabel(output.description) widget = OutputSelectionPanel(output, self.alg) self.layoutMain.insertWidget(self.layoutMain.count() - 1, label) self.layoutMain.insertWidget(self.layoutMain.count() - 1, widget) if isinstance(output, (OutputRaster, OutputVector, OutputTable)): check = QCheckBox() check.setText(self.tr('Open output file after running algorithm')) check.setChecked(True) self.layoutMain.insertWidget(self.layoutMain.count() - 1, check) self.checkBoxes[output.name] = check self.valueItems[output.name] = widget if isinstance(output, OutputVector): if output.base_input in self.dependentItems: items = self.dependentItems[output.base_input] else: items = [] self.dependentItems[output.base_input] = items items.append(output) base_input = self.alg.getParameterFromName(output.base_input) if isinstance(base_input, ParameterVector): layers = dataobjects.getVectorLayers(base_input.datatype) else: layers = dataobjects.getTables() if len(layers) > 0: output.base_layer = layers[0]
def fill_tree_with_element(widget, treeItem, elt, ns_imap={}, custom_viewers={}, ns_map={}): """ :param widget: the QTreeWidget :param treeItem: a QTreeWidgetItem to fill :param elt: the XML node :param ns_imap: an "inverse" namespace map { uri : prefix } :param custom_viewers: a dict giving a custom viewer plugin (QWidget) for some elements {tag : constructor} :param ns_map: a namespace map { prefix : uri } """ is_root = treeItem == widget.invisibleRootItem() # tag ns, tag = split_tag(elt.tag) if ns and ns_imap.get(ns): treeItem.setText(0, ns_imap[ns] + ":" + tag) else: treeItem.setText(0, tag) f = treeItem.font(0) f.setBold(True) treeItem.setFont(0, f) # custom viewer if elt.tag in custom_viewers: custom_viewer_widget, filter = custom_viewers[elt.tag] if filter is None or elt.find(filter, ns_map) is not None: btn = QToolButton(widget) btn.setIcon(custom_viewer_widget.icon()) btn.setIconSize(QSize(32, 32)) def show_viewer(btn): widget.w = custom_viewer_widget.init_from_xml(elt) widget.w.setWindowModality(Qt.WindowModal) widget.w.show() btn.clicked.connect(show_viewer) w = QWidget(widget) l = QHBoxLayout() l.addWidget(btn) l.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding)) w.setLayout(l) if is_root: # insert an item child = QTreeWidgetItem() treeItem.addChild(child) widget.setItemWidget(child, 0, w) else: widget.setItemWidget(treeItem, 1, w) # attributes for k, v in elt.attrib.items(): child = QTreeWidgetItem() treeItem.addChild(child) if "}" in k: i = k.index("}") ns = k[1:i] # get ns prefix from ns uri p = ns_imap.get(ns) if p is not None: n = p + ":" + k[i + 1:] else: n = k[i + 1:] else: n = no_prefix(k) child.setText(0, "@" + n) if n == "xlink:href" and v.startswith("http"): html = QLabel(widget) html.setOpenExternalLinks(True) html.setTextFormat(Qt.RichText) html.setText('<a href="{}">{}</a>'.format(v, v)) child.setData(1, Qt.UserRole, v) widget.setItemWidget(child, 1, html) else: child.setText(1, v) # text if elt.text: treeItem.setText(1, elt.text) # children for xmlChild in elt: child = QTreeWidgetItem() treeItem.addChild(child) fill_tree_with_element(widget, child, xmlChild, ns_imap, custom_viewers, ns_map)
def __init__(self, iface): locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(os.path.dirname(__file__), 'i18n', 'annotationManager_{}.qm'.format(locale)) self.translator = None if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) self.iface = iface self.iface.projectRead.connect(self.projectOpen) self.dock = QDockWidget(self.tr('Annotations')) self.manager = QWidget() toolbar = QToolBar() self.annotationList = QListWidget() self.annotationList.setSelectionMode( QAbstractItemView.ExtendedSelection) self.annotationList.itemSelectionChanged.connect(self.selectAnnotation) self.annotationList.itemChanged.connect(self.checkItem) action_refresh = QAction( QIcon(':/plugins/annotationManager/resources/mActionDraw.png'), self.tr('Refresh the annotations list'), self.manager) action_refresh.triggered.connect(self.refreshAnnotations) action_remove = QAction( QIcon( ':/plugins/annotationManager/resources/mActionRemoveAnnotation.png' ), self.tr('Remove the selected annotation'), self.manager) action_remove.triggered.connect(self.removeAnnotation) viewMenu = QMenu() action_showAll = QAction( QIcon(':/plugins/annotationManager/resources/mActionShowAll.png'), self.tr('Show all annotations'), self.manager) action_showAll.triggered.connect(self.showAll) action_hideAll = QAction( QIcon(':/plugins/annotationManager/resources/mActionHideAll.png'), self.tr('Hide all annotations'), self.manager) action_hideAll.triggered.connect(self.hideAll) action_showAllSelected = QAction( QIcon(':/plugins/annotationManager/resources/mActionShowAll.png'), self.tr('Show all selected annotations'), self.manager) action_showAllSelected.triggered.connect(self.showAllSelected) action_hideAllSelected = QAction( QIcon(':/plugins/annotationManager/resources/mActionHideAll.png'), self.tr('Hide all selected annotations'), self.manager) action_hideAllSelected.triggered.connect(self.hideAllSelected) viewMenu.addAction(action_showAll) viewMenu.addAction(action_hideAll) viewMenu.addAction(action_showAllSelected) viewMenu.addAction(action_hideAllSelected) viewButton = QToolButton() viewButton.setIcon( QIcon(':/plugins/annotationManager/resources/mActionShowAll.png')) viewButton.setPopupMode(2) viewButton.setMenu(viewMenu) toolbar.addAction(action_refresh) toolbar.addAction(action_remove) toolbar.addWidget(viewButton) toolbar.setIconSize(QSize(16, 16)) p1_vertical = QVBoxLayout() p1_vertical.setContentsMargins(0, 0, 0, 0) p1_vertical.addWidget(toolbar) p1_vertical.addWidget(self.annotationList) self.manager.setLayout(p1_vertical) self.dock.setWidget(self.manager) self.dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dock) self.rb = QgsRubberBand(self.iface.mapCanvas(), QgsWkbTypes.PolygonGeometry) self.project = QgsProject.instance() self.annotationManager = self.project.annotationManager() self.annotationManager.annotationAdded.connect(self.refreshAnnotations) self.annotationManager.annotationRemoved.connect( self.refreshAnnotations)
def __init__(self, iface): self.translator = None self.iface = iface self.project = None # type: Project self.link_layer = None # type: QgsVectorLayer self.node_layer = None # type: QgsVectorLayer self.dock = QDockWidget(self.trlt('AequilibraE')) self.manager = QWidget() # The self.toolbar will hold everything self.toolbar = QToolBar() self.toolbar.setOrientation(2) # # ######################################################################## # # ####################### PROJECT SUB-MENU ############################ projectMenu = QMenu() self.open_project_action = QAction(self.trlt('Open Project'), self.manager) self.open_project_action.triggered.connect(self.run_load_project) projectMenu.addAction(self.open_project_action) self.project_from_osm_action = QAction( self.trlt('Create project from OSM'), self.manager) self.project_from_osm_action.triggered.connect( self.run_project_from_osm) projectMenu.addAction(self.project_from_osm_action) self.create_transponet_action = QAction( self.trlt('Create Project from layers'), self.manager) self.create_transponet_action.triggered.connect( self.run_create_transponet) projectMenu.addAction(self.create_transponet_action) projectButton = QToolButton() projectButton.setText(self.trlt('Project')) projectButton.setPopupMode(2) projectButton.setMenu(projectMenu) self.toolbar.addWidget(projectButton) # # ######################################################################## # # ################# NETWORK MANIPULATION SUB-MENU ####################### netMenu = QMenu() self.action_netPrep = QAction(self.trlt('Network Preparation'), self.manager) self.action_netPrep.triggered.connect(self.run_net_prep) netMenu.addAction(self.action_netPrep) self.add_connectors_action = QAction( self.trlt('Add centroid connectors'), self.manager) self.add_connectors_action.triggered.connect(self.run_add_connectors) netMenu.addAction(self.add_connectors_action) netbutton = QToolButton() netbutton.setText(self.trlt('Network Manipulation')) netbutton.setMenu(netMenu) netbutton.setPopupMode(2) self.toolbar.addWidget(netbutton) # # ######################################################################## # # #################### DATA UTILITIES SUB-MENU ######################### dataMenu = QMenu() self.display_custom_formats_action = QAction( self.trlt('Display AequilibraE formats'), self.manager) self.display_custom_formats_action.triggered.connect( self.run_display_aequilibrae_formats) dataMenu.addAction(self.display_custom_formats_action) self.load_matrix_action = QAction(self.trlt('Import matrices'), self.manager) self.load_matrix_action.triggered.connect(self.run_load_matrices) dataMenu.addAction(self.load_matrix_action) self.load_database_action = QAction(self.trlt('Import dataset'), self.manager) self.load_database_action.triggered.connect(self.run_load_database) dataMenu.addAction(self.load_database_action) databutton = QToolButton() databutton.setText(self.trlt('Data')) databutton.setPopupMode(2) databutton.setMenu(dataMenu) self.toolbar.addWidget(databutton) # # # ######################################################################## # # # ################## TRIP DISTRIBUTION SUB-MENU ######################## distributionButton = QToolButton() distributionButton.setText(self.trlt('Trip Distribution')) distributionButton.clicked.connect(self.run_distribution_models) self.toolbar.addWidget(distributionButton) # # ######################################################################## # # ################### PATH COMPUTATION SUB-MENU ####################### pathMenu = QMenu() self.shortest_path_action = QAction(self.trlt('Shortest path'), self.manager) self.shortest_path_action.triggered.connect(self.run_shortest_path) pathMenu.addAction(self.shortest_path_action) self.dist_matrix_action = QAction(self.trlt('Impedance matrix'), self.manager) self.dist_matrix_action.triggered.connect(self.run_dist_matrix) pathMenu.addAction(self.dist_matrix_action) self.traffic_assignment_action = QAction( self.trlt('Traffic Assignment'), self.manager) self.traffic_assignment_action.triggered.connect( self.run_traffic_assig) pathMenu.addAction(self.traffic_assignment_action) pathButton = QToolButton() pathButton.setText(self.trlt('Paths and assignment')) pathButton.setPopupMode(2) pathButton.setMenu(pathMenu) self.toolbar.addWidget(pathButton) # # ######################################################################## # # ####################### ROUTING SUB-MENU ########################### if has_ortools: routingMenu = QMenu() self.tsp_action = QAction(self.trlt('Travelling Salesman Problem'), self.manager) self.tsp_action.triggered.connect(self.run_tsp) routingMenu.addAction(self.tsp_action) routingButton = QToolButton() routingButton.setText(self.trlt('Routing')) routingButton.setPopupMode(2) routingButton.setMenu(routingMenu) self.toolbar.addWidget(routingButton) # # ######################################################################## # # ####################### TRANSIT SUB-MENU ########################### transitMenu = QMenu() self.gtfs_import_action = QAction( self.trlt('Convert GTFS to SpatiaLite'), self.manager) self.gtfs_import_action.triggered.connect(self.run_import_gtfs) transitMenu.addAction(self.gtfs_import_action) transitButton = QToolButton() transitButton.setText(self.trlt('Public Transport')) transitButton.setPopupMode(2) transitButton.setMenu(transitMenu) self.toolbar.addWidget(transitButton) # ######################################################################## # ################# GIS TOOLS SUB-MENU ######################### gisMenu = QMenu() self.simple_tag_action = QAction(self.trlt('Simple tag'), self.manager) self.simple_tag_action.triggered.connect(self.run_simple_tag) gisMenu.addAction(self.simple_tag_action) self.lcd_action = QAction(self.trlt('Lowest common denominator'), self.manager) self.lcd_action.triggered.connect(self.run_lcd) gisMenu.addAction(self.lcd_action) self.dlines_action = QAction(self.trlt('Desire Lines'), self.manager) self.dlines_action.triggered.connect(self.run_dlines) gisMenu.addAction(self.dlines_action) self.bandwidth_action = QAction(self.trlt('Stacked Bandwidth'), self.manager) self.bandwidth_action.triggered.connect(self.run_bandwidth) gisMenu.addAction(self.bandwidth_action) self.scenario_comparison_action = QAction( self.trlt('Scenario Comparison'), self.manager) self.scenario_comparison_action.triggered.connect( self.run_scenario_comparison) gisMenu.addAction(self.scenario_comparison_action) gisButton = QToolButton() gisButton.setText(self.trlt('GIS')) gisButton.setPopupMode(2) gisButton.setMenu(gisMenu) self.toolbar.addWidget(gisButton) # ######################################################################## # ################# LOOSE STUFF ######################### parametersButton = QToolButton() parametersButton.setText(self.trlt('Parameters')) parametersButton.clicked.connect(self.run_change_parameters) self.toolbar.addWidget(parametersButton) aboutButton = QToolButton() aboutButton.setText(self.trlt('About')) aboutButton.clicked.connect(self.run_about) self.toolbar.addWidget(aboutButton) logButton = QToolButton() logButton.setText(self.trlt('logfile')) logButton.clicked.connect(self.run_log) self.toolbar.addWidget(logButton) helpButton = QToolButton() helpButton.setText(self.trlt('Help')) helpButton.clicked.connect(self.run_help) self.toolbar.addWidget(helpButton) if no_binary: binariesButton = QToolButton() binariesButton.setText(self.trlt('Download binaries')) binariesButton.clicked.connect(self.run_binary_download) self.toolbar.addWidget(binariesButton) if not extra_packages: xtrapkgButton = QToolButton() xtrapkgButton.setText(self.trlt('Install extra packages')) xtrapkgButton.clicked.connect(self.install_extra_packages) self.toolbar.addWidget(xtrapkgButton) # ######################################################################## # ################# PROJECT MANAGER ######################### self.showing = QCheckBox() self.showing.setText('Show project info') self.showing.setChecked(True) self.toolbar.addWidget(self.showing) self.showing.toggled.connect(self.hide_info_pannel) self.projectManager = QTabWidget() self.toolbar.addWidget(self.projectManager) # # # ######################################################################## self.tabContents = [] self.toolbar.setIconSize(QSize(16, 16)) p1_vertical = QVBoxLayout() p1_vertical.setContentsMargins(0, 0, 0, 0) p1_vertical.addWidget(self.toolbar) self.manager.setLayout(p1_vertical) self.dock.setWidget(self.manager) self.dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dock)
def initGui(self): """startup""" parent = self.iface.mainWindow() ######## action, button icon = QIcon("%s/%s" % (config.PLUGIN_DIR, "images/xyz.png")) icon_bbox = QIcon("%s/%s" % (config.PLUGIN_DIR, "images/bbox.svg")) self.action_connect = QAction(icon, "New XYZ Hub Connection", parent) self.action_connect.setWhatsThis( QCoreApplication.translate(PLUGIN_NAME, "WhatsThis message")) self.action_connect.setStatusTip( QCoreApplication.translate(PLUGIN_NAME, "status tip message")) self.action_clear_cache = QAction("Clear cache", parent) self.action_upload = QAction("Upload to New XYZ Geospace", parent) self.action_basemap = QAction("Add HERE Map Tile", parent) self.action_magic_sync = QAction("Magic Sync (EXPERIMENTAL)", parent) self.action_manage = QAction("Manage XYZ Geospace (EXPERIMENTAL)", parent) self.action_edit = QAction("Edit/Delete XYZ Geospace (EXPERIMENTAL)", parent) if self.iface.activeLayer() is None: # self.action_upload.setEnabled(False) self.action_edit.setEnabled(False) self.action_magic_sync.setEnabled(False) # self.action_magic_sync.setVisible(False) # disable magic sync ######## CONNECT action, button self.action_connect.triggered.connect(self.open_connection_dialog) self.action_manage.triggered.connect(self.open_manage_dialog) self.action_edit.triggered.connect(self.open_edit_dialog) self.action_upload.triggered.connect(self.open_upload_dialog) self.action_magic_sync.triggered.connect(self.open_magic_sync_dialog) self.action_clear_cache.triggered.connect(self.open_clear_cache_dialog) self.action_basemap.triggered.connect(self.open_basemap_dialog) ######## Add the toolbar + button self.toolbar = self.iface.addToolBar(PLUGIN_NAME) self.toolbar.setObjectName("XYZ Hub Connector") tool_btn = QToolButton(self.toolbar) self.actions = [ self.action_connect, self.action_upload, self.action_basemap, self.action_clear_cache ] # , self.action_magic_sync, self.action_manage, self.action_edit for a in self.actions: tool_btn.addAction(a) self.iface.addPluginToWebMenu(self.web_menu, a) tool_btn.setDefaultAction(self.action_connect) tool_btn.setPopupMode(tool_btn.MenuButtonPopup) self.xyz_widget_action = self.toolbar.addWidget(tool_btn) self.action_help = None self.action_reload = QAction(icon_bbox, "Reload BBox", parent) self.action_reload.triggered.connect(self.layer_reload_bbox) self.action_reload.setVisible(False) # disable self.toolbar.addAction(self.action_reload) progress = QProgressBar() progress.setMinimum(0) progress.setMaximum(0) progress.reset() progress.hide() # progress = self.iface.statusBarIface().children()[2] # will be hidden by qgis self.iface.statusBarIface().addPermanentWidget(progress) self.pb = progress
def initGui(self): settings = QgsSettings() icon_paius = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'hfflogo.png')) self.action = QAction(QIcon(icon_paius), "HFF Main Panel", self.iface.mainWindow()) self.action.triggered.connect(self.showHideDockWidget) # dock widget self.dockWidget = HffPluginDialog(self.iface) self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockWidget) # TOOLBAR self.toolBar = self.iface.addToolBar("HFF") self.toolBar.setObjectName("HFF") self.toolBar.addAction(self.action) self.dataToolButton = QToolButton(self.toolBar) self.dataToolButton.setPopupMode(QToolButton.MenuButtonPopup) ###### Section dedicated to the basic data entry # add Actions data self.siteToolButton = QToolButton(self.toolBar) self.siteToolButton.setPopupMode(QToolButton.MenuButtonPopup) icon_site = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'iconSite.png')) self.actionSite = QAction(QIcon(icon_site), "Site", self.iface.mainWindow()) self.actionSite.setWhatsThis("Site") self.actionSite.triggered.connect(self.runSite) icon_eamena = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'eamena.jpg')) self.actionEamena = QAction(QIcon(icon_eamena), "Eamena", self.iface.mainWindow()) self.actionEamena.setWhatsThis("Eamena") self.actionEamena.triggered.connect(self.runEamena) self.siteToolButton.addActions([self.actionSite, self.actionEamena]) self.siteToolButton.setDefaultAction(self.actionSite) self.toolBar.addWidget(self.siteToolButton) self.toolBar.addSeparator() ###### Section dedicated to the UnderWater data entry # add Actions data icon_UW = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'snorkel.png')) self.actionUW = QAction(QIcon(icon_UW), "Divelog Form", self.iface.mainWindow()) self.actionUW.setWhatsThis("Divelog") self.actionUW.triggered.connect(self.runUW) icon_ANC = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'iconANC.png')) self.actionANC = QAction(QIcon(icon_ANC), "Anchor", self.iface.mainWindow()) self.actionANC.setWhatsThis("Anchor") self.actionANC.triggered.connect(self.runANC) icon_ART = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'radar.png')) self.actionART = QAction(QIcon(icon_ART), "Artefact", self.iface.mainWindow()) self.actionART.setWhatsThis("Artefact") self.actionART.triggered.connect(self.runART) icon_Pottery = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'pottery.png')) self.actionPottery = QAction(QIcon(icon_Pottery), "Pottery", self.iface.mainWindow()) self.actionPottery.setWhatsThis("Pottery") self.actionPottery.triggered.connect(self.runPottery) self.dataToolButton.addActions([ self.actionUW, self.actionART, self.actionANC, self.actionPottery ]) self.dataToolButton.setDefaultAction(self.actionUW) self.toolBar.addWidget(self.dataToolButton) self.toolBar.addSeparator() ###### Section dedicated to the shipwreck # add Actions documentation self.ShipwreckToolButton = QToolButton(self.toolBar) icon_shipwreck = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'Shipwreck.png')) self.actionShipwreck = QAction(QIcon(icon_shipwreck), "Shipwreck", self.iface.mainWindow()) self.actionShipwreck.setWhatsThis("Shipwreck") self.actionShipwreck.triggered.connect(self.runShipwreck) self.ShipwreckToolButton.addActions([self.actionShipwreck]) self.ShipwreckToolButton.setDefaultAction(self.actionShipwreck) self.toolBar.addWidget(self.ShipwreckToolButton) self.toolBar.addSeparator() ###### Section dedicated to the documentation # add Actions documentation self.docToolButton = QToolButton(self.toolBar) self.docToolButton.setPopupMode(QToolButton.MenuButtonPopup) icon_imageViewer = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'photo.png')) self.actionimageViewer = QAction(QIcon(icon_imageViewer), "Media manager", self.iface.mainWindow()) self.actionimageViewer.setWhatsThis("Media manager") self.actionimageViewer.triggered.connect(self.runImageViewer) icon_Directory_export = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'directoryExp.png')) self.actionImages_Directory_export = QAction( QIcon(icon_Directory_export), "Download image", self.iface.mainWindow()) self.actionImages_Directory_export.setWhatsThis("Download image") self.actionImages_Directory_export.triggered.connect( self.runImages_directory_export) icon_excel_exp = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'excel-export.png')) self.actionexcelExp = QAction(QIcon(icon_excel_exp), "Download EXCEL", self.iface.mainWindow()) self.actionexcelExp.setWhatsThis("Download EXCEL") self.actionexcelExp.triggered.connect(self.runPdfexp) self.docToolButton.addActions([ self.actionexcelExp, self.actionimageViewer, self.actionexcelExp, self.actionImages_Directory_export ]) self.docToolButton.setDefaultAction(self.actionimageViewer) #if self.PARAMS_DICT['EXPERIMENTAL'] == 'Si': self.actionImages_Directory_export.setCheckable(True) self.actionexcelExp.setCheckable(True) self.actionimageViewer.setCheckable(True) self.toolBar.addWidget(self.docToolButton) self.toolBar.addSeparator() ###### Section dedicated to the plugin management self.manageToolButton = QToolButton(self.toolBar) self.manageToolButton.setPopupMode(QToolButton.MenuButtonPopup) icon_Con = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'iconConn.png')) self.actionConf = QAction(QIcon(icon_Con), "Config plugin", self.iface.mainWindow()) self.actionConf.setWhatsThis("Config plugin") self.actionConf.triggered.connect(self.runConf) icon_Dbmanagment = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'backup.png')) self.actionDbmanagment = QAction(QIcon(icon_Dbmanagment), "Database manager", self.iface.mainWindow()) self.actionDbmanagment.setWhatsThis("Database manager") self.actionDbmanagment.triggered.connect(self.runDbmanagment) icon_Info = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'iconInfo.png')) self.actionInfo = QAction(QIcon(icon_Info), "Plugin info", self.iface.mainWindow()) self.actionInfo.setWhatsThis("Plugin info") self.actionInfo.triggered.connect(self.runInfo) self.manageToolButton.addActions( [self.actionConf, self.actionDbmanagment, self.actionInfo]) self.manageToolButton.setDefaultAction(self.actionConf) self.toolBar.addWidget(self.manageToolButton) self.toolBar.addSeparator() # menu self.iface.addPluginToMenu("HFF - Survey UW Archaeological GIS Tools", self.actionUW) self.iface.addPluginToMenu("HFF - Survey UW Archaeological GIS Tools", self.actionANC) self.iface.addPluginToMenu("HFF - Survey UW Archaeological GIS Tools", self.actionART) self.iface.addPluginToMenu("HFF - Survey UW Archaeological GIS Tools", self.actionPottery) self.iface.addPluginToMenu("HFF - Survey UW Archaeological GIS Tools", self.actionShipwreck) self.iface.addPluginToMenu( "HFF - Survey Terrestrial Archaeological GIS Tools", self.actionSite) self.iface.addPluginToMenu( "HFF - Survey Terrestrial Archaeological GIS Tools", self.actionEamena) self.iface.addPluginToMenu("HFF - Media manager GIS Tools", self.actionimageViewer) self.iface.addPluginToMenu("HFF - Media manager GIS Tools", self.actionexcelExp) self.iface.addPluginToMenu("HFF - Media manager GIS Tools", self.actionImages_Directory_export) self.iface.addPluginToMenu("HFF - Config GIS Tools", self.actionConf) self.iface.addPluginToMenu("HFF - Config GIS Tools", self.actionDbmanagment) self.iface.addPluginToMenu("HFF - Info GIS Tools", self.actionInfo) # MENU self.menu = QMenu("HFF") self.menu.addActions([self.actionSite, self.actionEamena]) self.menu.addSeparator() self.menu.addActions([self.actionShipwreck]) self.menu.addSeparator() self.menu.addActions([ self.actionUW, self.actionART, self.actionANC, self.actionPottery ]) self.menu.addActions([ self.actionimageViewer, self.actionexcelExp, self.actionImages_Directory_export ]) self.menu.addSeparator() self.menu.addActions( [self.actionConf, self.actionDbmanagment, self.actionInfo]) menuBar = self.iface.mainWindow().menuBar() menuBar.addMenu(self.menu)
def initGui(self): settings = QgsSettings() icon_paius = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'pai_us.png')) self.action = QAction(QIcon(icon_paius), "pyArchInit Main Panel", self.iface.mainWindow()) self.action.triggered.connect(self.showHideDockWidget) # dock widget self.dockWidget = PyarchinitPluginDialog(self.iface) self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.dockWidget) # TOOLBAR self.toolBar = self.iface.addToolBar("pyArchInit") self.toolBar.setObjectName("pyArchInit") self.toolBar.addAction(self.action) self.dataToolButton = QToolButton(self.toolBar) self.dataToolButton.setPopupMode(QToolButton.MenuButtonPopup) ###### Section dedicated to the basic data entry # add Actions data icon_site = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'iconSite.png')) self.actionSite = QAction(QIcon(icon_site), "Siti", self.iface.mainWindow()) self.actionSite.setWhatsThis("Siti") self.actionSite.triggered.connect(self.runSite) icon_US = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'iconSus.png')) self.actionUS = QAction(QIcon((icon_US)), u"US", self.iface.mainWindow()) self.actionUS.setWhatsThis(u"US") self.actionUS.triggered.connect(self.runUS) icon_Finds = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'iconFinds.png')) self.actionInr = QAction(QIcon(icon_Finds), "Reperti", self.iface.mainWindow()) self.actionInr.setWhatsThis("Reperti") self.actionInr.triggered.connect(self.runInr) icon_camp_exp = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'champion.png')) self.actionCampioni = QAction(QIcon(icon_camp_exp), "Campioni", self.iface.mainWindow()) self.actionCampioni.setWhatsThis("Campioni") self.actionCampioni.triggered.connect(self.runCampioni) icon_Lapidei = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'iconAlma.png')) self.actionLapidei = QAction(QIcon(icon_Lapidei), "Lapidei", self.iface.mainWindow()) self.actionLapidei.setWhatsThis("Lapidei") self.actionLapidei.triggered.connect(self.runLapidei) self.dataToolButton.addActions([ self.actionSite, self.actionUS, self.actionInr, self.actionCampioni, self.actionLapidei ]) self.dataToolButton.setDefaultAction(self.actionSite) self.toolBar.addWidget(self.dataToolButton) self.toolBar.addSeparator() ###### Section dedicated to the interpretations # add Actions interpretation self.interprToolButton = QToolButton(self.toolBar) self.interprToolButton.setPopupMode(QToolButton.MenuButtonPopup) icon_per = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'iconPer.png')) self.actionPer = QAction(QIcon(icon_per), "Periodizzazione", self.iface.mainWindow()) self.actionPer.setWhatsThis("Periodizzazione") self.actionPer.triggered.connect(self.runPer) icon_Struttura = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'iconStrutt.png')) self.actionStruttura = QAction(QIcon(icon_Struttura), "Strutture", self.iface.mainWindow()) self.actionPer.setWhatsThis("Strutture") self.actionStruttura.triggered.connect(self.runStruttura) self.interprToolButton.addActions( [self.actionStruttura, self.actionPer]) self.interprToolButton.setDefaultAction(self.actionStruttura) self.toolBar.addWidget(self.interprToolButton) self.toolBar.addSeparator() ###### Section dedicated to the funerary archaeology # add Actions funerary archaeology self.funeraryToolButton = QToolButton(self.toolBar) self.funeraryToolButton.setPopupMode(QToolButton.MenuButtonPopup) icon_Schedaind = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'iconIND.png')) self.actionSchedaind = QAction(QIcon(icon_Schedaind), "Individui", self.iface.mainWindow()) self.actionSchedaind.setWhatsThis("Individui") self.actionSchedaind.triggered.connect(self.runSchedaind) icon_Tafonomia = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'iconGrave.png')) self.actionTafonomia = QAction(QIcon(icon_Tafonomia), "Tafonomica/Sepolture", self.iface.mainWindow()) self.actionTafonomia.setWhatsThis("Tafonomica/Sepolture") self.actionTafonomia.triggered.connect(self.runTafonomia) if self.PARAMS_DICT['EXPERIMENTAL'] == 'Si': icon_Detsesso = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'iconSesso.png')) self.actionDetsesso = QAction(QIcon(icon_Detsesso), "Determinazione Sesso", self.iface.mainWindow()) self.actionDetsesso.setWhatsThis("Determinazione del sesso") self.actionDetsesso.triggered.connect(self.runDetsesso) icon_Deteta = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'iconEta.png')) self.actionDeteta = QAction(QIcon(icon_Deteta), u"Determinazione dell'età", self.iface.mainWindow()) self.actionSchedaind.setWhatsThis(u"Determinazione dell'età") self.actionDeteta.triggered.connect(self.runDeteta) self.funeraryToolButton.addActions( [self.actionSchedaind, self.actionTafonomia]) self.funeraryToolButton.setDefaultAction(self.actionSchedaind) if self.PARAMS_DICT['EXPERIMENTAL'] == 'Si': self.funeraryToolButton.addActions( [self.actionDetsesso, self.actionDeteta]) self.toolBar.addWidget(self.funeraryToolButton) self.toolBar.addSeparator() ###### Section dedicated to the topographical research if self.PARAMS_DICT['EXPERIMENTAL'] == 'Si': self.topoToolButton = QToolButton(self.toolBar) self.topoToolButton.setPopupMode(QToolButton.MenuButtonPopup) icon_UT = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'iconUT.png')) self.actionUT = QAction(QIcon(icon_UT), u"Unità Topografiche", self.iface.mainWindow()) self.actionUT.setWhatsThis(u"Unità Topografiche") self.actionUT.triggered.connect(self.runUT) self.topoToolButton.addActions([self.actionUT]) self.topoToolButton.setDefaultAction(self.actionUT) self.toolBar.addWidget(self.topoToolButton) self.toolBar.addSeparator() ###### Section dedicated to the documentation # add Actions documentation self.docToolButton = QToolButton(self.toolBar) self.docToolButton.setPopupMode(QToolButton.MenuButtonPopup) icon_documentazione = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'icondoc.png')) self.actionDocumentazione = QAction(QIcon(icon_documentazione), "Scheda Documentazione", self.iface.mainWindow()) self.actionDocumentazione.setWhatsThis("Documentazione") self.actionDocumentazione.triggered.connect(self.runDocumentazione) if self.PARAMS_DICT['EXPERIMENTAL'] == 'Si': icon_imageViewer = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'photo.png')) self.actionimageViewer = QAction(QIcon(icon_imageViewer), "Gestione immagini", self.iface.mainWindow()) self.actionimageViewer.setWhatsThis("Gestione immagini") self.actionimageViewer.triggered.connect(self.runImageViewer) icon_Directory_export = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'directoryExp.png')) self.actionImages_Directory_export = QAction( QIcon(icon_Directory_export), "Esportazione immagini", self.iface.mainWindow()) self.actionImages_Directory_export.setWhatsThis( "Esportazione immagini") self.actionImages_Directory_export.triggered.connect( self.runImages_directory_export) icon_pdf_exp = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'pdf-icon.png')) self.actionpdfExp = QAction(QIcon(icon_pdf_exp), "Esportazione PDF", self.iface.mainWindow()) self.actionpdfExp.setWhatsThis("Esportazione PDF") self.actionpdfExp.triggered.connect(self.runPdfexp) self.docToolButton.addActions([self.actionDocumentazione]) if self.PARAMS_DICT['EXPERIMENTAL'] == 'Si': self.docToolButton.addActions([ self.actionpdfExp, self.actionimageViewer, self.actionpdfExp, self.actionImages_Directory_export ]) self.docToolButton.setDefaultAction(self.actionDocumentazione) if self.PARAMS_DICT['EXPERIMENTAL'] == 'Si': self.actionImages_Directory_export.setCheckable(True) self.actionpdfExp.setCheckable(True) self.actionimageViewer.setCheckable(True) self.toolBar.addWidget(self.docToolButton) self.toolBar.addSeparator() ###### Section dedicated to elaborations if self.PARAMS_DICT['EXPERIMENTAL'] == 'Si': self.elabToolButton = QToolButton(self.toolBar) self.elabToolButton.setPopupMode(QToolButton.MenuButtonPopup) # add Actions elaboration icon_Archeozoology = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'iconMegacero.png')) self.actionArcheozoology = QAction(QIcon(icon_Archeozoology), "Statistiche Archeozoologiche", self.iface.mainWindow()) self.actionArcheozoology.setWhatsThis( "Statistiche Archeozoologiche") self.actionArcheozoology.triggered.connect(self.runArcheozoology) icon_GisTimeController = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'iconTimeControll.png')) self.actionGisTimeController = QAction( QIcon(icon_GisTimeController), "Time Manager", self.iface.mainWindow()) self.actionGisTimeController.setWhatsThis("Time Manager") self.actionGisTimeController.triggered.connect( self.runGisTimeController) icon_Comparision = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'comparision.png')) self.actionComparision = QAction(QIcon(icon_Comparision), "Comparazione immagini", self.iface.mainWindow()) self.actionComparision.setWhatsThis("Comparazione immagini") self.actionComparision.triggered.connect(self.runComparision) self.elabToolButton.addActions([ self.actionArcheozoology, self.actionComparision, self.actionGisTimeController ]) self.elabToolButton.setDefaultAction(self.actionArcheozoology) self.toolBar.addWidget(self.elabToolButton) self.toolBar.addSeparator() ###### Section dedicated to the plugin management self.manageToolButton = QToolButton(self.toolBar) self.manageToolButton.setPopupMode(QToolButton.MenuButtonPopup) icon_thesaurus = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'thesaurusicon.png')) self.actionThesaurus = QAction(QIcon(icon_thesaurus), "Thesaurus sigle", self.iface.mainWindow()) self.actionThesaurus.setWhatsThis("Thesaurus sigle") self.actionThesaurus.triggered.connect(self.runThesaurus) icon_Con = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'iconConn.png')) self.actionConf = QAction(QIcon(icon_Con), "Configurazione plugin", self.iface.mainWindow()) self.actionConf.setWhatsThis("Configurazione plugin") self.actionConf.triggered.connect(self.runConf) icon_Dbmanagment = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'backup.png')) self.actionDbmanagment = QAction(QIcon(icon_Dbmanagment), "Gestione database", self.iface.mainWindow()) self.actionDbmanagment.setWhatsThis("Gestione database") self.actionDbmanagment.triggered.connect(self.runDbmanagment) icon_Info = '{}{}'.format( filepath, os.path.join(os.sep, 'resources', 'icons', 'iconInfo.png')) self.actionInfo = QAction(QIcon(icon_Info), "Plugin info", self.iface.mainWindow()) self.actionInfo.setWhatsThis("Plugin info") self.actionInfo.triggered.connect(self.runInfo) self.manageToolButton.addActions([ self.actionConf, self.actionThesaurus, self.actionDbmanagment, self.actionInfo ]) self.manageToolButton.setDefaultAction(self.actionConf) self.toolBar.addWidget(self.manageToolButton) self.toolBar.addSeparator() # menu self.iface.addPluginToMenu("&pyArchInit - Archaeological GIS Tools", self.actionSite) self.iface.addPluginToMenu("&pyArchInit - Archaeological GIS Tools", self.actionUS) self.iface.addPluginToMenu("&pyArchInit - Archaeological GIS Tools", self.actionInr) self.iface.addPluginToMenu("&pyArchInit - Archaeological GIS Tools", self.actionCampioni) self.iface.addPluginToMenu("&pyArchInit - Archaeological GIS Tools", self.actionLapidei) self.iface.addPluginToMenu("&pyArchInit - Archaeological GIS Tools", self.actionStruttura) self.iface.addPluginToMenu("&pyArchInit - Archaeological GIS Tools", self.actionPer) self.iface.addPluginToMenu("&pyArchInit - Archaeological GIS Tools", self.actionSchedaind) self.iface.addPluginToMenu("&pyArchInit - Archaeological GIS Tools", self.actionTafonomia) if self.PARAMS_DICT['EXPERIMENTAL'] == 'Si': self.iface.addPluginToMenu( "&pyArchInit - Archaeological GIS Tools", self.actionDetsesso) self.iface.addPluginToMenu( "&pyArchInit - Archaeological GIS Tools", self.actionDeteta) self.iface.addPluginToMenu( "&pyArchInit - Archaeological GIS Tools", self.actionUT) self.iface.addPluginToMenu("&pyArchInit - Archaeological GIS Tools", self.actionDocumentazione) if self.PARAMS_DICT['EXPERIMENTAL'] == 'Si': self.iface.addPluginToMenu( "&pyArchInit - Archaeological GIS Tools", self.actionimageViewer) self.iface.addPluginToMenu( "&pyArchInit - Archaeological GIS Tools", self.actionpdfExp) self.iface.addPluginToMenu( "&pyArchInit - Archaeological GIS Tools", self.actionImages_Directory_export) self.iface.addPluginToMenu( "&pyArchInit - Archaeological GIS Tools", self.actionArcheozoology) self.iface.addPluginToMenu( "&pyArchInit - Archaeological GIS Tools", self.actionComparision) self.iface.addPluginToMenu( "&pyArchInit - Archaeological GIS Tools", self.actionGisTimeController) self.iface.addPluginToMenu("&pyArchInit - Archaeological GIS Tools", self.actionConf) self.iface.addPluginToMenu("&pyArchInit - Archaeological GIS Tools", self.actionThesaurus) self.iface.addPluginToMenu("&pyArchInit - Archaeological GIS Tools", self.actionDbmanagment) self.iface.addPluginToMenu("&pyArchInit - Archaeological GIS Tools", self.actionInfo) # MENU self.menu = QMenu("pyArchInit") # self.pyarchinitSite = pyarchinit_Site(self.iface) self.menu.addActions([ self.actionSite, self.actionUS, self.actionInr, self.actionCampioni, self.actionLapidei ]) self.menu.addSeparator() self.menu.addActions([self.actionPer, self.actionStruttura]) self.menu.addSeparator() self.menu.addActions([self.actionTafonomia, self.actionSchedaind]) if self.PARAMS_DICT['EXPERIMENTAL'] == 'Si': self.menu.addActions([self.actionDetsesso, self.actionDeteta]) self.menu.addSeparator() if self.PARAMS_DICT['EXPERIMENTAL'] == 'Si': self.menu.addActions([self.actionUT]) self.menu.addActions([self.actionDocumentazione]) if self.PARAMS_DICT['EXPERIMENTAL'] == 'Si': self.menu.addActions([ self.actionimageViewer, self.actionpdfExp, self.actionImages_Directory_export ]) self.menu.addSeparator() if self.PARAMS_DICT['EXPERIMENTAL'] == 'Si': self.menu.addActions([ self.actionArcheozoology, self.actionComparision, self.actionGisTimeController ]) self.menu.addSeparator() self.menu.addActions([ self.actionConf, self.actionThesaurus, self.actionDbmanagment, self.actionInfo ]) menuBar = self.iface.mainWindow().menuBar() menuBar.addMenu(self.menu)
def __init__(self, parent=None): """Constructor.""" super(CoordinateCaptureDockWidget, self).__init__(parent) self.setWindowTitle(self.tr("Coordinate Capture")) self.setGeometry(0, 0, 300, 228) self.dockWidgetContents = QWidget(self) self.setWidget(self.dockWidgetContents) self.gridLayout = QGridLayout() self.dockWidgetContents.setLayout(self.gridLayout) self.dockWidgetContents.layout().setColumnMinimumWidth(0, 36) self.userCrsToolButton = QToolButton(self.dockWidgetContents) self.userCrsToolButton.setIcon( QIcon(":/plugins/coordinate_capture/mIconProjectionEnabled.svg")) self.userCrsToolButton.setToolTip( self.tr("Click to select the CRS to use for coordinate display")) self.userCrsLabel = QLabel(self.dockWidgetContents) self.userCrsLabel.setPixmap( QPixmap(":/plugins/coordinate_capture/transformed.svg")) self.userCrsLabel.setGeometry(self.userCrsToolButton.geometry()) self.userCrsEdit = QLineEdit(self.dockWidgetContents) self.userCrsEdit.setReadOnly(True) self.userCrsEdit.setToolTip( self.tr("Coordinate in your selected CRS (lat,lon or east,north)")) self.copyUserCrsCoordinatesAction = self.userCrsEdit.addAction( QIcon(":/plugins/coordinate_capture/mActionEditCopy.svg"), QLineEdit.TrailingPosition) self.copyUserCrsCoordinatesAction.triggered.connect( self.copyUserCrsCoordinates) self.canvasCrsEdit = QLineEdit(self.dockWidgetContents) self.canvasCrsEdit.setReadOnly(True) self.canvasCrsEdit.setToolTip( self. tr("Coordinate in map canvas coordinate reference system (lat,lon or east,north)" )) self.copyCanvasCrsCoordinatesAction = self.canvasCrsEdit.addAction( QIcon(":/plugins/coordinate_capture/mActionEditCopy.svg"), QLineEdit.TrailingPosition) self.copyCanvasCrsCoordinatesAction.triggered.connect( self.copyCanvasCrsCoordinates) self.trackMouseButton = QToolButton(self.dockWidgetContents) self.trackMouseButton.setIcon( QIcon(":/plugins/coordinate_capture/tracking.svg")) self.trackMouseButton.setCheckable(True) self.trackMouseButton.setToolTip( self.tr( "Click to enable mouse tracking. Click the canvas to stop")) self.trackMouseButton.setChecked(False) # Create the action for tool self.captureButton = QPushButton(self.dockWidgetContents) self.captureButton.setText(self.tr("Start Capture")) self.captureButton.setToolTip( self.tr("Click to enable coordinate capture")) self.captureButton.setIcon( QIcon(":/plugins/coordinate_capture/coordinate_capture.png")) self.captureButton.setWhatsThis( self. tr("Click on the map to view coordinates and capture to clipboard." )) # // Set the icons # setCurrentTheme(QString()); self.dockWidgetContents.layout().addWidget(self.userCrsToolButton, 0, 0) self.dockWidgetContents.layout().addWidget(self.userCrsEdit, 0, 1) self.dockWidgetContents.layout().addWidget(self.userCrsLabel, 1, 0) self.dockWidgetContents.layout().addWidget(self.canvasCrsEdit, 1, 1) self.dockWidgetContents.layout().addWidget(self.trackMouseButton, 2, 0) self.dockWidgetContents.layout().addWidget(self.captureButton, 2, 1)
def update_layers(self): if self.tabWidget.currentIndex() != 2: return if self.layerSelection.currentIndex() == 3: # by selection string self.selectionStringLineEdit.setEnabled(True) else: self.selectionStringLineEdit.setEnabled(False) if self.layerSelection.currentIndex() == 0: # visible layers layers = self.activeRasterLayers(0) elif self.layerSelection.currentIndex() == 3: # by selection string layers = self.activeRasterLayers(3) else: layers = self.activeRasterLayers(1) # All layers self.selectionTable.blockSignals(True) self.selectionTable.clearContents() self.selectionTable.setRowCount(len(layers)) self.selectionTable.horizontalHeader().resizeSection(0, 20) self.selectionTable.horizontalHeader().resizeSection(2, 20) j = 0 for layer in layers: item = QTableWidgetItem() item.setFlags(item.flags() | Qt.ItemIsUserCheckable) if self.layerSelection.currentIndex() != 2: item.setFlags(item.flags() & ~Qt.ItemIsEnabled) item.setCheckState(Qt.Checked) else: # manual selection if layer.id() in self.layersSelected: item.setCheckState(Qt.Checked) else: item.setCheckState(Qt.Unchecked) self.selectionTable.setItem(j, 0, item) item = QTableWidgetItem(layer.name()) item.setData(Qt.UserRole, layer.id()) self.selectionTable.setItem(j, 1, item) activeBands = self.activeBandsForRaster(layer) button = QToolButton() button.setIcon(QIcon(':/plugins/mutant/img/bands.jpg')) # button.setIconSize(QtCore.QSize(400, 400)) button.setPopupMode(QToolButton.InstantPopup) group = QActionGroup(button) group.setExclusive(False) group.triggered.connect(self.bandSelected) if self.bandSelection.currentIndex( ) == 2 and layer.bandCount() > 1: menu = QMenu() menu.installEventFilter(self) for iband in range(1, layer.bandCount() + 1): action = QAction(str(layer.bandName(iband)), group) action.setData([layer.id(), iband, j, False]) action.setCheckable(True) action.setChecked(iband in activeBands) menu.addAction(action) if layer.bandCount() > 1: action = QAction(str(self.tr("All")), group) action.setData([layer.id(), -1, j, True]) action.setCheckable(False) menu.addAction(action) action = QAction(str(self.tr("None")), group) action.setData([layer.id(), -1, j, False]) action.setCheckable(False) menu.addAction(action) button.setMenu(menu) else: button.setEnabled(False) self.selectionTable.setCellWidget(j, 2, button) item = QTableWidgetItem(str(activeBands)) item.setToolTip(str(activeBands)) self.selectionTable.setItem(j, 3, item) j += 1 self.selectionTable.blockSignals(False)
def buildfromauto(formconfig, base) -> QWidget: """ Build a auto form from the form config given. :param formconfig: The form config containing the information about the widgets to create. :param base: The base widget to create the new widgets in. :return: The base widget with the added widgets created inside the layout. """ widgetsconfig = copy.deepcopy(formconfig['widgets']) try: widgetsconfig = base.get_widgets(widgetsconfig) except AttributeError: pass newstyle = formconfig.get("newstyle", False) hassections = any(config['widget'] == "Section" for config in widgetsconfig) def make_layout(): """ Create the inner layout for the widget. For new style forms this is a vbox layout so everything is stacked on top of each other in a simple list. :return: """ if newstyle: return QVBoxLayout() else: layout = QFormLayout() layout.setFieldGrowthPolicy(QFormLayout.AllNonFixedFieldsGrow) return layout def make_tab(tabwidget, name): """ Create a table in the given tab widget. :param tabwidget: The tab widget to create the tab in. :param name: The name of the new tab to create. :return: The new widget inside the tab and the widgets inner layout. """ widget = QWidget() widget.setLayout(make_layout()) tabwidget.addTab(widget, name) return widget, widget.layout() if hassections: outwidget = QTabWidget(base) outlayout = None base.setLayout(QVBoxLayout()) base.layout().setContentsMargins(0, 0, 0, 0) base.layout().addWidget(outwidget) else: outwidget = base outlayout = make_layout() outwidget.setLayout(outlayout) # Add the geometry editor widget of that is set in the config. # This is a hidden option so isn't exposed in config manager yet if roam.config.settings.get("form_geom_edit", False): geomwidget = GeomWidget() geomwidget.setObjectName("__geomwidget") outlayout.addRow("Geometry", geomwidget) insection = False for config in widgetsconfig: widgettype = config['widget'] # Make the first tab if one isn't defined already and we have other sections in the config if not insection and hassections and not widgettype == "Section": name = formconfig['label'] tabwidget, outlayout = make_tab(outwidget, name) insection = True if widgettype == 'Section': # Add a spacer to the last widget if outlayout: spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) outlayout.addItem(QSpacerItem(10, 500)) outlayout.addWidget(spacer) name = config['name'] tabwidget, outlayout = make_tab(outwidget, name) insection = True continue field = config['field'] name = config.get('name', field) if not field: utils.warning("Field can't be null for {}".format(name)) utils.warning("Skipping widget") continue label = QLabel(name) label.setObjectName(field + "_label") labelwidget = QWidget() labelwidget.setLayout(QBoxLayout(QBoxLayout.LeftToRight)) labelwidget.layout().addWidget(label) labelwidget.layout().setContentsMargins(0, 0, 0, 0) widget = roam.editorwidgets.core.createwidget(widgettype, parent=base) widget.setObjectName(field) layoutwidget = QWidget() layoutwidget.setLayout(QBoxLayout(QBoxLayout.LeftToRight)) layoutwidget.layout().addWidget(widget) layoutwidget.layout().setContentsMargins(0, 0, 0, 10) if config.get('rememberlastvalue', False): savebutton = QToolButton() savebutton.setObjectName('{}_save'.format(field)) if newstyle: spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) labelwidget.layout().addWidget(spacer) labelwidget.layout().addWidget(savebutton) else: layoutwidget.layout().addWidget(savebutton) if newstyle: outlayout.addWidget(labelwidget) outlayout.addWidget(layoutwidget) else: outlayout.addRow(labelwidget, layoutwidget) spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) outlayout.addWidget(spacer) if not hassections: outlayout.addItem(QSpacerItem(10, 500)) return base
def __init__(self, geoservice, image_ba, parent=None, extent_renderer=None): QWidget.__init__(self, parent) self.extent_renderer = extent_renderer self.layout = QHBoxLayout(self) self.layout.setContentsMargins(5, 10, 5, 10) self.setLayout(self.layout) self.service_icon = QLabel(self) self.service_icon.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed) self.service_icon.resize(24, 24) qimg = QImage.fromData(image_ba) pixmap = QPixmap.fromImage(qimg) self.service_icon.setPixmap(pixmap) self.layout.addWidget(self.service_icon) self.service_desc_layout = QGridLayout(self) self.service_desc_layout.setSpacing(0) self.layout.addLayout(self.service_desc_layout) self.service_name = QLabel(self) self.service_name.setTextFormat(Qt.RichText) self.service_name.setWordWrap(True) self.service_name.setText(u" <strong> {} </strong>".format( geoservice.get('name', u""))) self.service_desc_layout.addWidget(self.service_name, 0, 0, 1, 3) self.service_type = QLabel(self) self.service_type.setTextFormat(Qt.RichText) self.service_type.setWordWrap(True) self.service_type.setText(geoservice.get('type', u"").upper() + " ") self.service_desc_layout.addWidget(self.service_type, 1, 0) self.service_deteils = QLabel(self) self.service_deteils.setTextFormat(Qt.RichText) self.service_deteils.setWordWrap(True) self.service_deteils.setOpenExternalLinks(True) self.service_deteils.setText(u"<a href=\"{0}\">{1}</a>, ".format( Client().geoservice_info_url(geoservice.get('id', u"")), self.tr('details'))) self.service_desc_layout.addWidget(self.service_deteils, 1, 1) self.service_report = QLabel(self) self.service_report.setTextFormat(Qt.RichText) self.service_report.setWordWrap(True) self.service_report.setOpenExternalLinks(True) self.service_report.setText(u"<a href=\"{0}\">{1}</a><div/>".format( Client().geoservice_report_url(geoservice.get('id', u"")), self.tr('report a problem'))) self.service_desc_layout.addWidget(self.service_report, 1, 2) self.service_desc_layout.setColumnStretch(2, 1) self.status_label = QLabel(self) self.status_label.setTextFormat(Qt.RichText) self.status_label.setText(u'\u2022') status = geoservice.get('cumulative_status', u'') if status == 'works': self.status_label.setStyleSheet("color: green; font-size: 30px") if status == 'failed': self.status_label.setStyleSheet("color: red; font-size: 30px") if status == 'problematic': self.status_label.setStyleSheet("color: yellow; font-size: 30px") self.layout.addWidget(self.status_label) self.addButton = QToolButton() self.addButton.setText(self.tr("Add")) self.addButton.clicked.connect(self.addToMap) self.layout.addWidget(self.addButton) self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Minimum) self.geoservice = geoservice self.image_ba = image_ba
def add_info_button(self): info_menu = QMenu() p_sec_act = add_menu_section_action('Planet', info_menu) p_com_act = QAction(QIcon(EXT_LINK), 'planet.com', info_menu) p_com_act.triggered[bool].connect( lambda: open_link_with_browser(PLANET_COM) ) info_menu.addAction(p_com_act) p_explorer_act = QAction(QIcon(EXT_LINK), 'Planet Explorer web app', info_menu) p_explorer_act.triggered[bool].connect( lambda: open_link_with_browser(PLANET_EXPLORER) ) info_menu.addAction(p_explorer_act) p_sat_act = QAction(QIcon(EXT_LINK), 'Satellite specs PDF', info_menu) p_sat_act.triggered[bool].connect( lambda: open_link_with_browser(SAT_SPECS_PDF) ) info_menu.addAction(p_sat_act) p_support_act = QAction(QIcon(EXT_LINK), 'Support Community', info_menu) p_support_act.triggered[bool].connect( lambda: open_link_with_browser(PLANET_SUPPORT_COMMUNITY) ) info_menu.addAction(p_support_act) p_whatsnew_act = QAction(QIcon(EXT_LINK), "What's new", info_menu) p_whatsnew_act.triggered[bool].connect( lambda: open_link_with_browser(PLANET_INTEGRATIONS) ) info_menu.addAction(p_whatsnew_act) p_sales_act = QAction(QIcon(EXT_LINK), "Sales", info_menu) p_sales_act.triggered[bool].connect( lambda: open_link_with_browser(PLANET_SALES) ) info_menu.addAction(p_sales_act) add_menu_section_action('Documentation', info_menu) terms_act = QAction('Terms', info_menu) terms_act.triggered[bool].connect(self.show_terms) info_menu.addAction(terms_act) btn = QToolButton() btn.setIcon(QIcon(os.path.join(plugin_path, "resources", "info.svg"),)) btn.setMenu(info_menu) btn.setPopupMode(QToolButton.MenuButtonPopup) # Also show menu on click, to keep disclosure triangle visible btn.clicked.connect(btn.showMenu) self.toolbar.addWidget(btn)
def initWidgets(self): # If there are advanced parameters — show corresponding groupbox for param in self.alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: self.grpAdvanced.show() break widget_context = QgsProcessingParameterWidgetContext() if iface is not None: widget_context.setMapCanvas(iface.mapCanvas()) # Create widgets and put them in layouts for param in self.alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue if param.isDestination(): continue else: wrapper = WidgetWrapperFactory.create_wrapper( param, self.parent) 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: wrapper.setWidgetContext(widget_context) widget = wrapper.createWrappedWidget( self.processing_context) wrapper.registerProcessingContextGenerator( self.context_generator) 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()) if isinstance(param, QgsProcessingParameterFeatureSource): layout = QHBoxLayout() layout.setSpacing(6) layout.setMargin(0) layout.addWidget(widget) button = QToolButton() icon = QIcon( os.path.join(pluginPath, 'images', 'iterate.png')) button.setIcon(icon) button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) button.setToolTip( self. tr('Iterate over this layer, creating a separate output for every feature in the layer' )) button.setCheckable(True) layout.addWidget(button) layout.setAlignment(button, Qt.AlignTop) self.iterateButtons[param.name()] = button button.toggled.connect(self.buttonToggled) widget = QWidget() widget.setLayout(layout) label = None if not is_python_wrapper: label = wrapper.createWrappedLabel() else: label = wrapper.label if label is not None: if param.flags( ) & QgsProcessingParameterDefinition.FlagAdvanced: self.layoutAdvanced.addWidget(label) else: self.layoutMain.insertWidget( self.layoutMain.count() - 2, label) elif is_python_wrapper: desc = param.description() if isinstance(param, QgsProcessingParameterExtent): desc += self.tr(' (xmin, xmax, ymin, ymax)') if isinstance(param, QgsProcessingParameterPoint): desc += self.tr(' (x, y)') if param.flags( ) & QgsProcessingParameterDefinition.FlagOptional: desc += self.tr(' [optional]') widget.setText(desc) if param.flags( ) & QgsProcessingParameterDefinition.FlagAdvanced: self.layoutAdvanced.addWidget(widget) else: self.layoutMain.insertWidget( self.layoutMain.count() - 2, widget) for output in self.alg.destinationParameterDefinitions(): if output.flags() & QgsProcessingParameterDefinition.FlagHidden: continue if self.in_place and param.name() in ('INPUT', 'OUTPUT'): continue label = QLabel(output.description()) widget = DestinationSelectionPanel(output, self.alg) self.layoutMain.insertWidget(self.layoutMain.count() - 1, label) self.layoutMain.insertWidget(self.layoutMain.count() - 1, widget) if isinstance(output, (QgsProcessingParameterRasterDestination, QgsProcessingParameterFeatureSink, QgsProcessingParameterVectorDestination)): check = QCheckBox() check.setText( QCoreApplication.translate( 'ParametersPanel', 'Open output file after running algorithm')) def skipOutputChanged(checkbox, skipped): checkbox.setEnabled(not skipped) if skipped: checkbox.setChecked(False) check.setChecked(not widget.outputIsSkipped()) check.setEnabled(not widget.outputIsSkipped()) widget.skipOutputChanged.connect( partial(skipOutputChanged, check)) self.layoutMain.insertWidget(self.layoutMain.count() - 1, check) self.checkBoxes[output.name()] = check widget.setToolTip(param.toolTip()) self.outputWidgets[output.name()] = widget for wrapper in list(self.wrappers.values()): wrapper.postInitialize(list(self.wrappers.values()))
def __init__(self, entity, parent=None, notification_bar=None, enable_list=True, can_filter=False, plugin=None): QWidget.__init__(self, parent) self.current_profile = current_profile() self._tbFKEntity = QTableView(self) self._tbFKEntity.setEditTriggers(QAbstractItemView.NoEditTriggers) self._tbFKEntity.setAlternatingRowColors(True) self._tbFKEntity.setSelectionBehavior(QAbstractItemView.SelectRows) self.plugin = plugin self._add_entity_btn = QToolButton(self) self._add_entity_btn.setToolTip( QApplication.translate("ForeignKeyMapper", "Add")) self._add_entity_btn.setIcon(GuiUtils.get_icon("add.png")) self._add_entity_btn.clicked.connect(self.onAddEntity) self._edit_entity_btn = QToolButton(self) self._edit_entity_btn.setVisible(False) self._edit_entity_btn.setToolTip( QApplication.translate("ForeignKeyMapper", "Edit")) self._edit_entity_btn.setIcon(GuiUtils.get_icon("edit.png")) self._filter_entity_btn = QToolButton(self) self._filter_entity_btn.setVisible(False) self._filter_entity_btn.setToolTip( QApplication.translate("ForeignKeyMapper", "Select by expression")) self._filter_entity_btn.setIcon(GuiUtils.get_icon("filter.png")) self._filter_entity_btn.clicked.connect(self.onFilterEntity) self._delete_entity_btn = QToolButton(self) self._delete_entity_btn.setToolTip( QApplication.translate("ForeignKeyMapper", "Remove")) self._delete_entity_btn.setIcon(GuiUtils.get_icon("remove.png")) self._delete_entity_btn.clicked.connect(self.onRemoveEntity) layout = QVBoxLayout(self) layout.setSpacing(4) layout.setMargin(5) self.grid_layout = QGridLayout() self.grid_layout.setHorizontalSpacing(5) self.grid_layout.addWidget(self._add_entity_btn, 0, 0, 1, 1) self.grid_layout.addWidget(self._filter_entity_btn, 0, 1, 1, 1) self.grid_layout.addWidget(self._edit_entity_btn, 0, 2, 1, 1) self.grid_layout.addWidget(self._delete_entity_btn, 0, 3, 1, 1) self.grid_layout.setColumnStretch(4, 5) layout.addLayout(self.grid_layout) layout.addWidget(self._tbFKEntity) self.social_tenure = self.current_profile.social_tenure self._tableModel = None self._notifBar = notification_bar self._headers = [] self._entity_attrs = [] self._cell_formatters = {} self._searchable_columns = OrderedDict() self._supportsLists = enable_list self._deleteOnRemove = False self._uniqueValueColIndices = OrderedDict() self.global_id = None self._deferred_objects = {} self._use_expression_builder = can_filter if self._use_expression_builder: self._filter_entity_btn.setVisible(True) self._edit_entity_btn.setVisible(False) self.set_entity(entity)
def initGui(self): self.azDigitizerTool = AzDigitizerTool(self.iface) self.lineDigitizerTool = LineDigitizerTool(self.iface) # Initialize the create shape menu items menu = QMenu() # Initialize Create Arc Wedge tool icon = QIcon(self.plugin_dir + '/images/arc.png') self.createArcAction = menu.addAction(icon, tr('Create arc wedge'), self.createArc) self.createArcAction.setObjectName('stCreateArcWedge') icon = QIcon(self.plugin_dir + '/images/donut.png') self.createDonutAction = menu.addAction(icon, tr('Create donut'), self.createDonut) self.createDonutAction.setObjectName('stCreateDonut') icon = QIcon(self.plugin_dir + '/images/ellipse.png') self.createEllipseAction = menu.addAction(icon, tr('Create ellipse'), self.createEllipse) self.createEllipseAction.setObjectName('stCreateEllipse') icon = QIcon(self.plugin_dir + '/images/rose.png') self.createEllipseRoseAction = menu.addAction( icon, tr('Create ellipse rose'), self.createEllipseRose) self.createEllipseRoseAction.setObjectName('stCreateEllipseRose') icon = QIcon(self.plugin_dir + '/images/epicycloid.png') self.createEpicycloidAction = menu.addAction(icon, tr('Create epicycloid'), self.createEpicycloid) self.createEpicycloidAction.setObjectName('stCreateEpicycloid') icon = QIcon(self.plugin_dir + '/images/heart.png') self.createHeartAction = menu.addAction(icon, tr('Create heart'), self.createHeart) self.createHeartAction.setObjectName('stCreateHeart') icon = QIcon(self.plugin_dir + '/images/hypocycloid.png') self.createHypocycloidAction = menu.addAction(icon, tr('Create hypocycloid'), self.createHypocycloid) self.createHypocycloidAction.setObjectName('stCreateHypocycloid') icon = QIcon(self.plugin_dir + '/images/line.png') self.createLOBAction = menu.addAction(icon, tr('Create line of bearing'), self.createLOB) self.createLOBAction.setObjectName('stCreateLineOfBearing') icon = QIcon(self.plugin_dir + '/images/pie.png') self.createPieAction = menu.addAction(icon, tr('Create pie wedge'), self.createPie) self.createPieAction.setObjectName('stCreatePie') icon = QIcon(self.plugin_dir + '/images/polyfoil.png') self.createPolyfoilAction = menu.addAction(icon, tr('Create polyfoil'), self.createPolyfoil) self.createPolyfoilAction.setObjectName('stCreatePolyfoil') icon = QIcon(self.plugin_dir + '/images/polygon.png') self.createPolygonAction = menu.addAction(icon, tr('Create polygon'), self.createPolygon) self.createPolygonAction.setObjectName('stCreatePolygon') icon = QIcon(self.plugin_dir + '/images/radialLines.png') self.createPolygonAction = menu.addAction(icon, tr('Create radial lines'), self.createRadialLines) self.createPolygonAction.setObjectName('stCreateRadialLines') icon = QIcon(self.plugin_dir + '/images/star.png') self.createStarAction = menu.addAction(icon, tr('Create star'), self.createStar) self.createStarAction.setObjectName('stCreateStar') # Add the shape creation tools to the menu icon = QIcon(self.plugin_dir + '/images/shapes.png') self.createShapesAction = QAction(icon, tr('Create shapes'), self.iface.mainWindow()) self.createShapesAction.setMenu(menu) self.iface.addPluginToVectorMenu('Shape Tools', self.createShapesAction) # Add the shape creation tools to the toolbar self.createShapeButton = QToolButton() self.createShapeButton.setMenu(menu) self.createShapeButton.setDefaultAction(self.createDonutAction) self.createShapeButton.setPopupMode(QToolButton.MenuButtonPopup) self.createShapeButton.triggered.connect(self.createShapeTriggered) self.createShapeToolbar = self.toolbar.addWidget( self.createShapeButton) # Initialize the XY to Line menu item icon = QIcon(self.plugin_dir + '/images/xyline.svg') self.xyLineAction = QAction(icon, tr('XY to line'), self.iface.mainWindow()) self.xyLineAction.setObjectName('stXYtoLine') self.xyLineAction.triggered.connect(self.xyLineTool) self.iface.addPluginToVectorMenu('Shape Tools', self.xyLineAction) self.toolbar.addAction(self.xyLineAction) # Initialize the Geodesic Densifier menu item icon = QIcon(self.plugin_dir + '/images/geodesicDensifier.svg') self.geodesicDensifyAction = QAction(icon, tr('Geodesic shape densifier'), self.iface.mainWindow()) self.geodesicDensifyAction.setObjectName('stGeodesicDensifier') self.geodesicDensifyAction.triggered.connect(self.geodesicDensifyTool) self.iface.addPluginToVectorMenu('Shape Tools', self.geodesicDensifyAction) self.toolbar.addAction(self.geodesicDensifyAction) # Initialize the Geodesic decimation menu items menu = QMenu() icon = QIcon(self.plugin_dir + '/images/geodesicLineDecimate.svg') self.lineDecimateAction = menu.addAction(icon, tr('Geodesic line decimate'), self.lineDecimateTool) self.lineDecimateAction.setObjectName('stGeodesicLineDecimate') icon = QIcon(self.plugin_dir + '/images/geodesicPointDecimate.svg') self.pointDecimateAction = menu.addAction( icon, tr('Geodesic point decimate'), self.pointDecimateTool) self.pointDecimateAction.setObjectName('stGeodesicPointDecimate') # Add the decimation tools to the menu icon = QIcon(self.plugin_dir + '/images/geodesicLineDecimate.svg') self.simplifyGeomAction = QAction( icon, tr('Geodesic geometry simplification'), self.iface.mainWindow()) self.simplifyGeomAction.setMenu(menu) self.iface.addPluginToVectorMenu('Shape Tools', self.simplifyGeomAction) # Add the shape creation tools to the toolbar self.simplifyButton = QToolButton() self.simplifyButton.setMenu(menu) self.simplifyButton.setDefaultAction(self.lineDecimateAction) self.simplifyButton.setPopupMode(QToolButton.MenuButtonPopup) self.simplifyButton.triggered.connect(self.simplifyTriggered) self.simplifyToolbar = self.toolbar.addWidget(self.simplifyButton) # Initialize the Geodesic line break menu item icon = QIcon(self.plugin_dir + '/images/idlbreak.svg') self.geodesicLineBreakAction = QAction( icon, tr('Geodesic line break at -180,180'), self.iface.mainWindow()) self.geodesicLineBreakAction.setObjectName('stGeodesicLineBreak') self.geodesicLineBreakAction.triggered.connect( self.geodesicLineBreakTool) self.iface.addPluginToVectorMenu('Shape Tools', self.geodesicLineBreakAction) self.toolbar.addAction(self.geodesicLineBreakAction) # Initialize Geodesic Measure Tool self.geodesicMeasureTool = GeodesicMeasureTool(self.iface, self.iface.mainWindow()) icon = QIcon(self.plugin_dir + '/images/measure.svg') self.measureAction = QAction(icon, tr('Geodesic measure tool'), self.iface.mainWindow()) self.measureAction.setObjectName('stGeodesicMeasureTool') self.measureAction.triggered.connect(self.measureTool) self.measureAction.setCheckable(True) self.iface.addPluginToVectorMenu('Shape Tools', self.measureAction) self.toolbar.addAction(self.measureAction) # Initialize Geodesic Measurement layer icon = QIcon(self.plugin_dir + '/images/measureLine.svg') self.measureLayerAction = QAction(icon, tr('Geodesic measurement layer'), self.iface.mainWindow()) self.measureLayerAction.setObjectName('stGeodesicLineBreak') self.measureLayerAction.triggered.connect(self.measureLayerTool) self.iface.addPluginToVectorMenu('Shape Tools', self.measureLayerAction) self.toolbar.addAction(self.measureLayerAction) menu = QMenu() # Initialize Geodesic transformation tool icon = QIcon(self.plugin_dir + '/images/transformShape.svg') self.transformationsAction = menu.addAction( icon, tr('Geodesic transformations'), self.transformTool) self.transformationsAction.setObjectName('stGeodesicTransformations') icon = QIcon(self.plugin_dir + '/images/flip.svg') self.flipRotateAction = menu.addAction(icon, tr('Geodesic flip and rotate'), self.flipRotateTool) self.flipRotateAction.setObjectName('stGeodesicFlipRotate') icon = QIcon(self.plugin_dir + '/images/flipHorizontal.svg') self.flipHorizontalAction = menu.addAction(icon, tr('Flip horizontal'), self.flipHorizontalTool) self.flipHorizontalAction.setObjectName('stGeodesicFlipHorizontal') self.flipHorizontalAction.setEnabled(False) icon = QIcon(self.plugin_dir + '/images/flipVertical.svg') self.flipVerticalAction = menu.addAction(icon, tr('Flip vertical'), self.flipVerticalTool) self.flipVerticalAction.setObjectName('stGeodesicFlipVertical') self.flipVerticalAction.setEnabled(False) icon = QIcon(self.plugin_dir + '/images/rotate180.svg') self.rotate180Action = menu.addAction(icon, tr('Rotate 180\xb0'), self.rotate180Tool) self.rotate180Action.setObjectName('stGeodesicRotate180') self.rotate180Action.setEnabled(False) icon = QIcon(self.plugin_dir + '/images/rotatecw.svg') self.rotate90CWAction = menu.addAction(icon, tr('Rotate 90\xb0 CW'), self.rotate90CWTool) self.rotate90CWAction.setObjectName('stGeodesicRotate90CW') self.rotate90CWAction.setEnabled(False) icon = QIcon(self.plugin_dir + '/images/rotateccw.svg') self.rotate90CCWAction = menu.addAction(icon, tr('Rotate 90\xb0 CCW'), self.rotate90CCWTool) self.rotate90CCWAction.setObjectName('stGeodesicRotate90CCW') self.rotate90CCWAction.setEnabled(False) self.transformsAction = QAction(icon, tr('Geodesic transforms'), self.iface.mainWindow()) self.transformsAction.setMenu(menu) self.iface.addPluginToVectorMenu('Shape Tools', self.transformsAction) self.transformationButton = QToolButton() self.transformationButton.setMenu(menu) self.transformationButton.setDefaultAction(self.transformationsAction) self.transformationButton.setPopupMode(QToolButton.MenuButtonPopup) self.transformationButton.triggered.connect(self.toolButtonTriggered) self.tranformToolbar = self.toolbar.addWidget( self.transformationButton) # Initialize the Azimuth Distance Digitize function icon = QIcon(self.plugin_dir + '/images/dazdigitize.svg') self.digitizeAction = QAction(icon, tr('Azimuth distance digitizer'), self.iface.mainWindow()) self.digitizeAction.setObjectName('stAzDistanceDigitizer') self.digitizeAction.triggered.connect(self.setShowAzDigitizerTool) self.digitizeAction.setCheckable(True) self.digitizeAction.setEnabled(False) self.iface.addPluginToVectorMenu(u'Shape Tools', self.digitizeAction) self.toolbar.addAction(self.digitizeAction) # Initialize the multi point azimuth Digitize function icon = QIcon(self.plugin_dir + '/images/linedigitize.svg') self.lineDigitizeAction = QAction( icon, tr('Azimuth distance sequence digitizer'), self.iface.mainWindow()) self.lineDigitizeAction.setObjectName('stLineDigitizer') self.lineDigitizeAction.triggered.connect(self.setShowLineDigitizeTool) self.lineDigitizeAction.setCheckable(True) self.lineDigitizeAction.setEnabled(False) self.iface.addPluginToVectorMenu(u'Shape Tools', self.lineDigitizeAction) self.toolbar.addAction(self.lineDigitizeAction) # Settings icon = QIcon(':/images/themes/default/mActionOptions.svg') self.settingsAction = QAction(icon, tr('Settings'), self.iface.mainWindow()) self.settingsAction.setObjectName('shapeToolsSettings') self.settingsAction.triggered.connect(self.settings) self.iface.addPluginToVectorMenu('Shape Tools', self.settingsAction) # Help icon = QIcon(self.plugin_dir + '/images/help.svg') self.helpAction = QAction(icon, tr('Shape Tools help'), self.iface.mainWindow()) self.helpAction.setObjectName('shapeToolsHelp') self.helpAction.triggered.connect(self.help) self.iface.addPluginToVectorMenu('Shape Tools', self.helpAction) self.iface.currentLayerChanged.connect(self.currentLayerChanged) self.canvas.mapToolSet.connect(self.unsetTool) self.enableTools() # Add the processing provider QgsApplication.processingRegistry().addProvider(self.provider)
def __init__(self, parent=None): super(MapWidget, self).__init__(parent) self.setupUi(self) self.snapping = True icon = roam_style.iconsize() self.projecttoolbar.setIconSize(QSize(icon, icon)) self.defaultextent = None self.current_form = None self.last_form = None self.layerbuttons = [] self.editfeaturestack = [] self.lastgpsposition = None self.project = None self.gps = None self.gpslogging = None self.selectionbands = defaultdict(partial(QgsRubberBand, self.canvas)) self.bridge = QgsLayerTreeMapCanvasBridge( QgsProject.instance().layerTreeRoot(), self.canvas) self.bridge.setAutoSetupOnFirstLayer(False) self.canvas.setCanvasColor(Qt.white) self.canvas.enableAntiAliasing(True) self.snappingutils = SnappingUtils(self.canvas, self) self.canvas.setSnappingUtils(self.snappingutils) threadcount = QThread.idealThreadCount() threadcount = 2 if threadcount > 2 else 1 QgsApplication.setMaxThreads(threadcount) self.canvas.setParallelRenderingEnabled(True) self.canvas.setFrameStyle(QFrame.NoFrame) self.editgroup = QActionGroup(self) self.editgroup.setExclusive(True) self.editgroup.addAction(self.actionPan) self.editgroup.addAction(self.actionZoom_In) self.editgroup.addAction(self.actionZoom_Out) self.editgroup.addAction(self.actionInfo) self.actionGPS = GPSAction(self.canvas, self) self.projecttoolbar.addAction(self.actionGPS) if roam.config.settings.get('north_arrow', False): self.northarrow = NorthArrow(":/icons/north", self.canvas) self.northarrow.setPos(10, 10) self.canvas.scene().addItem(self.northarrow) smallmode = roam.config.settings.get("smallmode", False) self.projecttoolbar.setSmallMode(smallmode) self.projecttoolbar.setContextMenuPolicy(Qt.CustomContextMenu) gpsspacewidget = QWidget() gpsspacewidget.setMinimumWidth(30) gpsspacewidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.topspaceraction = self.projecttoolbar.insertWidget( self.actionGPS, gpsspacewidget) self.dataentryselection = QAction(self.projecttoolbar) self.dataentryaction = self.projecttoolbar.insertAction( self.topspaceraction, self.dataentryselection) self.dataentryselection.triggered.connect(self.select_data_entry) self.gpsMarker = GPSMarker(self.canvas) self.gpsMarker.hide() self.currentfeatureband = CurrentSelection(self.canvas) self.currentfeatureband.setIconSize(30) self.currentfeatureband.setWidth(10) self.currentfeatureband.setColor(QColor(88, 64, 173, 50)) self.currentfeatureband.setOutlineColour(QColor(88, 64, 173)) self.gpsband = QgsRubberBand(self.canvas) self.gpsband.setColor(QColor(165, 111, 212, 75)) self.gpsband.setWidth(5) RoamEvents.refresh_map.connect(self.refresh_map) RoamEvents.editgeometry.connect(self.queue_feature_for_edit) RoamEvents.selectioncleared.connect(self.clear_selection) RoamEvents.selectionchanged.connect(self.highlight_selection) RoamEvents.openfeatureform.connect(self.feature_form_loaded) RoamEvents.sync_complete.connect(self.refresh_map) RoamEvents.snappingChanged.connect(self.snapping_changed) self.snappingbutton = QToolButton() self.snappingbutton.setText("Snapping: On") self.snappingbutton.setAutoRaise(True) self.snappingbutton.pressed.connect(self.toggle_snapping) spacer = QWidget() spacer2 = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) spacer2.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) self.scalewidget = QgsScaleComboBox() self.scalebutton = QToolButton() self.scalebutton.setAutoRaise(True) self.scalebutton.setMaximumHeight(self.statusbar.height()) self.scalebutton.pressed.connect(self.selectscale) self.scalebutton.setText("Scale") self.scalelist = BigList(parent=self.canvas, centeronparent=True, showsave=False) self.scalelist.hide() self.scalelist.setlabel("Map Scale") self.scalelist.setmodel(self.scalewidget.model()) self.scalelist.closewidget.connect(self.scalelist.close) self.scalelist.itemselected.connect(self.update_scale_from_item) self.scalelist.itemselected.connect(self.scalelist.close) self.positionlabel = QLabel('') self.gpslabel = QLabel("GPS: Not active") self.gpslabelposition = QLabel("") self.gpslabelaveraging = QLabel('') # averaging self.statusbar.addWidget(self.snappingbutton) self.statusbar.addWidget(spacer2) self.statusbar.addWidget(self.gpslabel) self.statusbar.addWidget(self.gpslabelposition) self.statusbar.addWidget(self.gpslabelaveraging) # averaging self.statusbar.addPermanentWidget(self.scalebutton) self.canvas.extentsChanged.connect(self.update_status_label) self.canvas.scaleChanged.connect(self.update_status_label) self.connectButtons() scalebar_enabled = roam.config.settings.get('scale_bar', False) self.scalebar_enabled = False if scalebar_enabled: roam.utils.warning( "Unsupported feature: Scale bar support not ported to QGIS 3 API yet." ) RoamEvents.raisemessage( "Unsupported feature", "Scale bar support not ported to QGIS 3 API yet", level=RoamEvents.CRITICAL) self.scalebar_enabled = False
def __init__(self, model=None): super().__init__(None) self.setAttribute(Qt.WA_DeleteOnClose) self.setupUi(self) self._variables_scope = None # LOTS of bug reports when we include the dock creation in the UI file # see e.g. #16428, #19068 # So just roll it all by hand......! self.propertiesDock = QgsDockWidget(self) self.propertiesDock.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) self.propertiesDock.setObjectName("propertiesDock") propertiesDockContents = QWidget() self.verticalDockLayout_1 = QVBoxLayout(propertiesDockContents) self.verticalDockLayout_1.setContentsMargins(0, 0, 0, 0) self.verticalDockLayout_1.setSpacing(0) self.scrollArea_1 = QgsScrollArea(propertiesDockContents) sizePolicy = QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.scrollArea_1.sizePolicy().hasHeightForWidth()) self.scrollArea_1.setSizePolicy(sizePolicy) self.scrollArea_1.setFocusPolicy(Qt.WheelFocus) self.scrollArea_1.setFrameShape(QFrame.NoFrame) self.scrollArea_1.setFrameShadow(QFrame.Plain) self.scrollArea_1.setWidgetResizable(True) self.scrollAreaWidgetContents_1 = QWidget() self.gridLayout = QGridLayout(self.scrollAreaWidgetContents_1) self.gridLayout.setContentsMargins(6, 6, 6, 6) self.gridLayout.setSpacing(4) self.label_1 = QLabel(self.scrollAreaWidgetContents_1) self.gridLayout.addWidget(self.label_1, 0, 0, 1, 1) self.textName = QLineEdit(self.scrollAreaWidgetContents_1) self.gridLayout.addWidget(self.textName, 0, 1, 1, 1) self.label_2 = QLabel(self.scrollAreaWidgetContents_1) self.gridLayout.addWidget(self.label_2, 1, 0, 1, 1) self.textGroup = QLineEdit(self.scrollAreaWidgetContents_1) self.gridLayout.addWidget(self.textGroup, 1, 1, 1, 1) self.label_1.setText(self.tr("Name")) self.textName.setToolTip(self.tr("Enter model name here")) self.label_2.setText(self.tr("Group")) self.textGroup.setToolTip(self.tr("Enter group name here")) self.scrollArea_1.setWidget(self.scrollAreaWidgetContents_1) self.verticalDockLayout_1.addWidget(self.scrollArea_1) self.propertiesDock.setWidget(propertiesDockContents) self.propertiesDock.setWindowTitle(self.tr("Model Properties")) self.inputsDock = QgsDockWidget(self) self.inputsDock.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) self.inputsDock.setObjectName("inputsDock") self.inputsDockContents = QWidget() self.verticalLayout_3 = QVBoxLayout(self.inputsDockContents) self.verticalLayout_3.setContentsMargins(0, 0, 0, 0) self.scrollArea_2 = QgsScrollArea(self.inputsDockContents) sizePolicy.setHeightForWidth( self.scrollArea_2.sizePolicy().hasHeightForWidth()) self.scrollArea_2.setSizePolicy(sizePolicy) self.scrollArea_2.setFocusPolicy(Qt.WheelFocus) self.scrollArea_2.setFrameShape(QFrame.NoFrame) self.scrollArea_2.setFrameShadow(QFrame.Plain) self.scrollArea_2.setWidgetResizable(True) self.scrollAreaWidgetContents_2 = QWidget() self.verticalLayout = QVBoxLayout(self.scrollAreaWidgetContents_2) self.verticalLayout.setContentsMargins(0, 0, 0, 0) self.verticalLayout.setSpacing(0) self.inputsTree = QTreeWidget(self.scrollAreaWidgetContents_2) self.inputsTree.setAlternatingRowColors(True) self.inputsTree.header().setVisible(False) self.verticalLayout.addWidget(self.inputsTree) self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2) self.verticalLayout_3.addWidget(self.scrollArea_2) self.inputsDock.setWidget(self.inputsDockContents) self.addDockWidget(Qt.DockWidgetArea(1), self.inputsDock) self.inputsDock.setWindowTitle(self.tr("Inputs")) self.algorithmsDock = QgsDockWidget(self) self.algorithmsDock.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) self.algorithmsDock.setObjectName("algorithmsDock") self.algorithmsDockContents = QWidget() self.verticalLayout_4 = QVBoxLayout(self.algorithmsDockContents) self.verticalLayout_4.setContentsMargins(0, 0, 0, 0) self.scrollArea_3 = QgsScrollArea(self.algorithmsDockContents) sizePolicy.setHeightForWidth( self.scrollArea_3.sizePolicy().hasHeightForWidth()) self.scrollArea_3.setSizePolicy(sizePolicy) self.scrollArea_3.setFocusPolicy(Qt.WheelFocus) self.scrollArea_3.setFrameShape(QFrame.NoFrame) self.scrollArea_3.setFrameShadow(QFrame.Plain) self.scrollArea_3.setWidgetResizable(True) self.scrollAreaWidgetContents_3 = QWidget() self.verticalLayout_2 = QVBoxLayout(self.scrollAreaWidgetContents_3) self.verticalLayout_2.setContentsMargins(0, 0, 0, 0) self.verticalLayout_2.setSpacing(4) self.searchBox = QgsFilterLineEdit(self.scrollAreaWidgetContents_3) self.verticalLayout_2.addWidget(self.searchBox) self.algorithmTree = QgsProcessingToolboxTreeView( None, QgsApplication.processingRegistry()) self.algorithmTree.setAlternatingRowColors(True) self.algorithmTree.header().setVisible(False) self.verticalLayout_2.addWidget(self.algorithmTree) self.scrollArea_3.setWidget(self.scrollAreaWidgetContents_3) self.verticalLayout_4.addWidget(self.scrollArea_3) self.algorithmsDock.setWidget(self.algorithmsDockContents) self.addDockWidget(Qt.DockWidgetArea(1), self.algorithmsDock) self.algorithmsDock.setWindowTitle(self.tr("Algorithms")) self.searchBox.setToolTip( self.tr("Enter algorithm name to filter list")) self.searchBox.setShowSearchIcon(True) self.variables_dock = QgsDockWidget(self) self.variables_dock.setFeatures(QDockWidget.DockWidgetFloatable | QDockWidget.DockWidgetMovable) self.variables_dock.setObjectName("variablesDock") self.variables_dock_contents = QWidget() vl_v = QVBoxLayout() vl_v.setContentsMargins(0, 0, 0, 0) self.variables_editor = QgsVariableEditorWidget() vl_v.addWidget(self.variables_editor) self.variables_dock_contents.setLayout(vl_v) self.variables_dock.setWidget(self.variables_dock_contents) self.addDockWidget(Qt.DockWidgetArea(1), self.variables_dock) self.variables_dock.setWindowTitle(self.tr("Variables")) self.addDockWidget(Qt.DockWidgetArea(1), self.propertiesDock) self.tabifyDockWidget(self.propertiesDock, self.variables_dock) self.variables_editor.scopeChanged.connect(self.variables_changed) self.bar = QgsMessageBar() self.bar.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed) self.centralWidget().layout().insertWidget(0, self.bar) try: self.setDockOptions(self.dockOptions() | QMainWindow.GroupedDragging) except: pass if iface is not None: self.mToolbar.setIconSize(iface.iconSize()) self.setStyleSheet(iface.mainWindow().styleSheet()) self.toolbutton_export_to_script = QToolButton() self.toolbutton_export_to_script.setPopupMode(QToolButton.InstantPopup) self.export_to_script_algorithm_action = QAction( QCoreApplication.translate('ModelerDialog', 'Export as Script Algorithm…')) self.toolbutton_export_to_script.addActions( [self.export_to_script_algorithm_action]) self.mToolbar.insertWidget(self.mActionExportImage, self.toolbutton_export_to_script) self.export_to_script_algorithm_action.triggered.connect( self.export_as_script_algorithm) self.mActionOpen.setIcon( QgsApplication.getThemeIcon('/mActionFileOpen.svg')) self.mActionSave.setIcon( QgsApplication.getThemeIcon('/mActionFileSave.svg')) self.mActionSaveAs.setIcon( QgsApplication.getThemeIcon('/mActionFileSaveAs.svg')) self.mActionSaveInProject.setIcon( QgsApplication.getThemeIcon('/mAddToProject.svg')) self.mActionZoomActual.setIcon( QgsApplication.getThemeIcon('/mActionZoomActual.svg')) self.mActionZoomIn.setIcon( QgsApplication.getThemeIcon('/mActionZoomIn.svg')) self.mActionZoomOut.setIcon( QgsApplication.getThemeIcon('/mActionZoomOut.svg')) self.mActionExportImage.setIcon( QgsApplication.getThemeIcon('/mActionSaveMapAsImage.svg')) self.mActionZoomToItems.setIcon( QgsApplication.getThemeIcon('/mActionZoomFullExtent.svg')) self.mActionExportPdf.setIcon( QgsApplication.getThemeIcon('/mActionSaveAsPDF.svg')) self.mActionExportSvg.setIcon( QgsApplication.getThemeIcon('/mActionSaveAsSVG.svg')) self.toolbutton_export_to_script.setIcon( QgsApplication.getThemeIcon('/mActionSaveAsPython.svg')) self.mActionEditHelp.setIcon( QgsApplication.getThemeIcon('/mActionEditHelpContent.svg')) self.mActionRun.setIcon( QgsApplication.getThemeIcon('/mActionStart.svg')) self.addDockWidget(Qt.LeftDockWidgetArea, self.propertiesDock) self.addDockWidget(Qt.LeftDockWidgetArea, self.inputsDock) self.addDockWidget(Qt.LeftDockWidgetArea, self.algorithmsDock) self.tabifyDockWidget(self.inputsDock, self.algorithmsDock) self.inputsDock.raise_() self.setWindowFlags(Qt.WindowMinimizeButtonHint | Qt.WindowMaximizeButtonHint | Qt.WindowCloseButtonHint) settings = QgsSettings() self.restoreState( settings.value("/Processing/stateModeler", QByteArray())) self.restoreGeometry( settings.value("/Processing/geometryModeler", QByteArray())) self.scene = ModelerScene(self, dialog=self) self.scene.setSceneRect( QRectF(0, 0, self.CANVAS_SIZE, self.CANVAS_SIZE)) self.view.setScene(self.scene) self.view.setAcceptDrops(True) self.view.ensureVisible(0, 0, 10, 10) self.view.scale(QgsApplication.desktop().logicalDpiX() / 96, QgsApplication.desktop().logicalDpiX() / 96) def _dragEnterEvent(event): if event.mimeData().hasText() or event.mimeData().hasFormat( 'application/x-vnd.qgis.qgis.algorithmid'): event.acceptProposedAction() else: event.ignore() def _dropEvent(event): def alg_dropped(algorithm_id, pos): alg = QgsApplication.processingRegistry().createAlgorithmById( algorithm_id) if alg is not None: self._addAlgorithm(alg, pos) else: assert False, algorithm_id def input_dropped(id, pos): if id in [ param.id() for param in QgsApplication.instance(). processingRegistry().parameterTypes() ]: self.addInputOfType(itemId, pos) if event.mimeData().hasFormat( 'application/x-vnd.qgis.qgis.algorithmid'): data = event.mimeData().data( 'application/x-vnd.qgis.qgis.algorithmid') stream = QDataStream(data, QIODevice.ReadOnly) algorithm_id = stream.readQString() QTimer.singleShot( 0, lambda id=algorithm_id, pos=self.view.mapToScene(event.pos( )): alg_dropped(id, pos)) event.accept() elif event.mimeData().hasText(): itemId = event.mimeData().text() QTimer.singleShot(0, lambda id=itemId, pos=self.view.mapToScene( event.pos()): input_dropped(id, pos)) event.accept() else: event.ignore() def _dragMoveEvent(event): if event.mimeData().hasText() or event.mimeData().hasFormat( 'application/x-vnd.qgis.qgis.algorithmid'): event.accept() else: event.ignore() def _wheelEvent(event): self.view.setTransformationAnchor(QGraphicsView.AnchorUnderMouse) settings = QgsSettings() factor = settings.value('/qgis/zoom_favor', 2.0) # "Normal" mouse has an angle delta of 120, precision mouses provide data # faster, in smaller steps factor = 1.0 + (factor - 1.0) / 120.0 * abs(event.angleDelta().y()) if (event.modifiers() == Qt.ControlModifier): factor = 1.0 + (factor - 1.0) / 20.0 if event.angleDelta().y() < 0: factor = 1 / factor self.view.scale(factor, factor) def _enterEvent(e): QGraphicsView.enterEvent(self.view, e) self.view.viewport().setCursor(Qt.ArrowCursor) def _mouseReleaseEvent(e): QGraphicsView.mouseReleaseEvent(self.view, e) self.view.viewport().setCursor(Qt.ArrowCursor) def _mousePressEvent(e): if e.button() == Qt.MidButton: self.previousMousePos = e.pos() else: QGraphicsView.mousePressEvent(self.view, e) def _mouseMoveEvent(e): if e.buttons() == Qt.MidButton: offset = self.previousMousePos - e.pos() self.previousMousePos = e.pos() self.view.verticalScrollBar().setValue( self.view.verticalScrollBar().value() + offset.y()) self.view.horizontalScrollBar().setValue( self.view.horizontalScrollBar().value() + offset.x()) else: QGraphicsView.mouseMoveEvent(self.view, e) self.view.setDragMode(QGraphicsView.ScrollHandDrag) self.view.dragEnterEvent = _dragEnterEvent self.view.dropEvent = _dropEvent self.view.dragMoveEvent = _dragMoveEvent self.view.wheelEvent = _wheelEvent self.view.enterEvent = _enterEvent self.view.mousePressEvent = _mousePressEvent self.view.mouseMoveEvent = _mouseMoveEvent def _mimeDataInput(items): mimeData = QMimeData() text = items[0].data(0, Qt.UserRole) mimeData.setText(text) return mimeData self.inputsTree.mimeData = _mimeDataInput self.inputsTree.setDragDropMode(QTreeWidget.DragOnly) self.inputsTree.setDropIndicatorShown(True) self.algorithms_model = ModelerToolboxModel( self, QgsApplication.processingRegistry()) self.algorithmTree.setToolboxProxyModel(self.algorithms_model) self.algorithmTree.setDragDropMode(QTreeWidget.DragOnly) self.algorithmTree.setDropIndicatorShown(True) filters = QgsProcessingToolboxProxyModel.Filters( QgsProcessingToolboxProxyModel.FilterModeler) if ProcessingConfig.getSetting( ProcessingConfig.SHOW_ALGORITHMS_KNOWN_ISSUES): filters |= QgsProcessingToolboxProxyModel.FilterShowKnownIssues self.algorithmTree.setFilters(filters) if hasattr(self.searchBox, 'setPlaceholderText'): self.searchBox.setPlaceholderText( QCoreApplication.translate('ModelerDialog', 'Search…')) if hasattr(self.textName, 'setPlaceholderText'): self.textName.setPlaceholderText(self.tr('Enter model name here')) if hasattr(self.textGroup, 'setPlaceholderText'): self.textGroup.setPlaceholderText(self.tr('Enter group name here')) # Connect signals and slots self.inputsTree.doubleClicked.connect(self.addInput) self.searchBox.textChanged.connect(self.algorithmTree.setFilterString) self.algorithmTree.doubleClicked.connect(self.addAlgorithm) # Ctrl+= should also trigger a zoom in action ctrlEquals = QShortcut(QKeySequence("Ctrl+="), self) ctrlEquals.activated.connect(self.zoomIn) self.mActionOpen.triggered.connect(self.openModel) self.mActionSave.triggered.connect(self.save) self.mActionSaveAs.triggered.connect(self.saveAs) self.mActionSaveInProject.triggered.connect(self.saveInProject) self.mActionZoomIn.triggered.connect(self.zoomIn) self.mActionZoomOut.triggered.connect(self.zoomOut) self.mActionZoomActual.triggered.connect(self.zoomActual) self.mActionZoomToItems.triggered.connect(self.zoomToItems) self.mActionExportImage.triggered.connect(self.exportAsImage) self.mActionExportPdf.triggered.connect(self.exportAsPdf) self.mActionExportSvg.triggered.connect(self.exportAsSvg) #self.mActionExportPython.triggered.connect(self.exportAsPython) self.mActionEditHelp.triggered.connect(self.editHelp) self.mActionRun.triggered.connect(self.runModel) if model is not None: self.model = model.create() self.model.setSourceFilePath(model.sourceFilePath()) self.textGroup.setText(self.model.group()) self.textName.setText(self.model.displayName()) self.repaintModel() else: self.model = QgsProcessingModelAlgorithm() self.model.setProvider( QgsApplication.processingRegistry().providerById('model')) self.update_variables_gui() self.fillInputsTree() self.view.centerOn(0, 0) self.help = None self.hasChanged = False
def __createToolbarsAndConnect(self): actionGroup = QActionGroup(self) actionGroup.addAction(self.actionImport) actionGroup.addAction(self.actionVyhledavani) actionGroup.addAction(self.actionZpracujZmeny) # QSignalMapper self.signalMapper = QtCore.QSignalMapper(self) self.actionImport.triggered.connect(self.signalMapper.map) self.actionVyhledavani.triggered.connect(self.signalMapper.map) self.actionZpracujZmeny.triggered.connect(self.signalMapper.map) # setMapping on each button to the QStackedWidget index we'd like to # switch to self.signalMapper.setMapping(self.actionImport, 0) self.signalMapper.setMapping(self.actionVyhledavani, 2) self.signalMapper.setMapping(self.actionZpracujZmeny, 1) # connect mapper to stackedWidget self.signalMapper.mapped.connect(self.stackedWidget.setCurrentIndex) self.vfkBrowser.switchToPanelImport.connect(self.switchToImport) self.vfkBrowser.switchToPanelSearch.connect(self.switchToSearch) self.vfkBrowser.switchToPanelChanges.connect(self.switchToChanges) # Browser toolbar # --------------- self.__mBrowserToolbar = QToolBar(self) self.actionBack.triggered.connect(self.vfkBrowser.goBack) self.actionForward.triggered.connect(self.vfkBrowser.goForth) self.actionSelectBudInMap.triggered.connect(self.selectBudInMap) self.actionSelectParInMap.triggered.connect(self.selectParInMap) self.actionCuzkPage.triggered.connect(self.showOnCuzk) self.actionExportLatex.triggered.connect(self.latexExport) self.actionExportHtml.triggered.connect(self.htmlExport) self.actionShowInfoaboutSelection.toggled.connect( self.setSelectionChangedConnected) self.actionShowHelpPage.triggered.connect(self.vfkBrowser.showHelpPage) self.loadVfkButton.clicked.connect(self.loadVfkButton_clicked) self.__browseButtons['browseButton_1'] = self.browseButton self.__browseButtons['browseButton_1'].clicked.connect( lambda: self.browseButton_clicked( int('{}'.format(len(self.__vfkLineEdits))))) self.__vfkLineEdits['vfkLineEdit_1'] = self.vfkFileLineEdit bt = QToolButton(self.__mBrowserToolbar) bt.setPopupMode(QToolButton.InstantPopup) bt.setText("Export ") menu = QMenu(bt) menu.addAction(self.actionExportLatex) menu.addAction(self.actionExportHtml) bt.setMenu(menu) # add actions to toolbar icons self.__mBrowserToolbar.addAction(self.actionImport) self.__mBrowserToolbar.addAction(self.actionVyhledavani) self.__mBrowserToolbar.addAction(self.actionZpracujZmeny) self.__mBrowserToolbar.addSeparator() self.__mBrowserToolbar.addAction(self.actionBack) self.__mBrowserToolbar.addAction(self.actionForward) self.__mBrowserToolbar.addAction(self.actionSelectParInMap) self.__mBrowserToolbar.addAction(self.actionSelectBudInMap) self.__mBrowserToolbar.addAction(self.actionCuzkPage) self.__mBrowserToolbar.addSeparator() self.__mBrowserToolbar.addAction(self.actionShowInfoaboutSelection) self.__mBrowserToolbar.addSeparator() self.__mBrowserToolbar.addWidget(bt) self.__mBrowserToolbar.addSeparator() self.__mBrowserToolbar.addAction(self.actionShowHelpPage) self.rightWidgetLayout.insertWidget(0, self.__mBrowserToolbar) # connect signals from vfkbrowser when changing history self.vfkBrowser.currentParIdsChanged.connect( self.actionSelectParInMap.setEnabled) self.vfkBrowser.currentBudIdsChanged.connect( self.actionSelectBudInMap.setEnabled) self.vfkBrowser.historyBefore.connect(self.actionBack.setEnabled) self.vfkBrowser.historyAfter.connect(self.actionForward.setEnabled) self.vfkBrowser.definitionPointAvailable.connect( self.actionCuzkPage.setEnabled) # add toolTips self.pb_nextFile.setToolTip(u'Přidej další soubor VFK') self.parCheckBox.setToolTip(u'Načti vrstvu parcel') self.budCheckBox.setToolTip(u'Načti vrstvu budov') # add new VFK file self.pb_nextFile.clicked.connect(self.__addRowToGridLayout) # widget apply changes self.pb_mainDb.clicked.connect(lambda: self.browseDb_clicked('mainDb')) self.pb_amendmentDb.clicked.connect( lambda: self.browseDb_clicked('amendmentDb')) self.pb_exportDb.clicked.connect( lambda: self.browseDb_clicked('exportDb')) self.pb_applyChanges.clicked.connect(self.applyChanges) self.pb_applyChanges.setEnabled(False) self.changes_instance.maxRangeProgressBar.connect( self.__setRangeProgressBarChanges) self.changes_instance.updateStatus.connect( self.__updateProgressBarChanges) self.changes_instance.finishedStatus.connect(self.__changesApplied) self.changes_instance.preprocessingDatabase.connect( self.__changesPreprocessingDatabase) # connect radio boxes self.rb_file.clicked.connect(self.radioButtonValue) self.rb_directory.clicked.connect(self.radioButtonValue)
def __init__(self, alg): super(AlgorithmDialogBase, self).__init__(iface.mainWindow() if iface else None) self.setupUi(self) # don't collapse parameters panel self.splitter.setCollapsible(0, False) # add collapse button to splitter splitterHandle = self.splitter.handle(1) handleLayout = QVBoxLayout() handleLayout.setContentsMargins(0, 0, 0, 0) self.btnCollapse = QToolButton(splitterHandle) self.btnCollapse.setAutoRaise(True) self.btnCollapse.setFixedSize(12, 12) self.btnCollapse.setCursor(Qt.ArrowCursor) handleLayout.addWidget(self.btnCollapse) handleLayout.addStretch() splitterHandle.setLayout(handleLayout) self.settings = QgsSettings() self.splitter.restoreState( self.settings.value("/Processing/dialogBaseSplitter", QByteArray())) self.restoreGeometry( self.settings.value("/Processing/dialogBase", QByteArray())) self.splitterState = self.splitter.saveState() self.splitterChanged(0, 0) self.executed = False self.mainWidget = None self.alg = alg self.setWindowTitle(self.alg.displayName()) self.buttonBox.rejected.connect(self.reject) self.buttonBox.accepted.connect(self.accept) # Rename OK button to Run self.btnRun = self.buttonBox.button(QDialogButtonBox.Ok) self.btnRun.setText(self.tr('Run')) self.buttonCancel.setEnabled(False) self.btnClose = self.buttonBox.button(QDialogButtonBox.Close) self.buttonBox.helpRequested.connect(self.openHelp) self.btnCollapse.clicked.connect(self.toggleCollapsed) self.splitter.splitterMoved.connect(self.splitterChanged) # desktop = QDesktopWidget() # if desktop.physicalDpiX() > 96: # self.txtHelp.setZoomFactor(desktop.physicalDpiX() / 96) algHelp = self.formatHelp(self.alg) if algHelp is None: self.textShortHelp.hide() else: self.textShortHelp.document().setDefaultStyleSheet( '''.summary { margin-left: 10px; margin-right: 10px; } h2 { color: #555555; padding-bottom: 15px; } a { text-decoration: none; color: #3498db; font-weight: bold; } p { color: #666666; } b { color: #333333; } dl dd { margin-bottom: 5px; }''' ) self.textShortHelp.setHtml(algHelp) def linkClicked(url): webbrowser.open(url.toString()) self.textShortHelp.anchorClicked.connect(linkClicked) self.showDebug = ProcessingConfig.getSetting( ProcessingConfig.SHOW_DEBUG_IN_DIALOG)
def initGui(self): readTrackedLayers() QgsMapLayerRegistry.instance().layerWasAdded.connect(trackLayer) QgsMapLayerRegistry.instance().layerRemoved.connect(layerRemoved) icon = QIcon(os.path.dirname(__file__) + "/ui/resources/geogig.png") self.explorerAction = navigatorInstance.toggleViewAction() self.explorerAction.setIcon(icon) self.explorerAction.setText("GeoGig Navigator") icon = QIcon(os.path.dirname(__file__) + "/ui/resources/config.png") self.configAction = QAction(icon, "GeoGig Settings", self.iface.mainWindow()) self.configAction.triggered.connect(self.openSettings) icon = QIcon(os.path.dirname(__file__) + "/ui/resources/identify.png") self.toolAction = QAction(icon, "GeoGig Feature Info Tool", self.iface.mainWindow()) self.toolAction.setCheckable(True) self.toolAction.triggered.connect(self.setTool) helpIcon = QgsApplication.getThemeIcon('/mActionHelpAPI.png') self.helpAction = QAction(helpIcon, "GeoGig Plugin Help", self.iface.mainWindow()) self.helpAction.setObjectName("GeoGigHelp") self.helpAction.triggered.connect( lambda: webbrowser.open_new("file://" + os.path.join( os.path.dirname(__file__), "docs", "html", "index.html"))) self.menu = QMenu(self.iface.mainWindow()) self.menu.setTitle("GeoGig") self.menu.addAction(self.explorerAction) self.menu.addAction(self.toolAction) self.menu.addAction(self.configAction) self.menu.addAction(self.helpAction) bar = self.iface.layerToolBar() self.toolButton = QToolButton() self.toolButton.setMenu(self.menu) self.toolButton.setPopupMode(QToolButton.MenuButtonPopup) self.toolButton.setDefaultAction(self.explorerAction) useMainMenu = config.getConfigValue(config.GENERAL, config.USE_MAIN_MENUBAR) bar.addWidget(self.toolButton) if useMainMenu: menuBar = self.iface.mainWindow().menuBar() menuBar.insertMenu( self.iface.firstRightStandardMenu().menuAction(), self.menu) else: self.iface.addPluginToMenu(u"&GeoGig", self.explorerAction) self.iface.addPluginToMenu(u"&GeoGig", self.configAction) self.iface.addPluginToMenu(u"&GeoGig", self.toolAction) self.mapTool = MapToolGeoGigInfo(self.iface.mapCanvas()) #This crashes QGIS, so we comment it out until finding a solution #self.mapTool.setAction(self.toolAction) self.iface.addDockWidget(Qt.RightDockWidgetArea, navigatorInstance) try: from lessons import addLessonsFolder folder = os.path.join(os.path.dirname(__file__), "_lessons") addLessonsFolder(folder, "geogig") except Exception as e: pass
def createWidget(self): if self.dialogType == DIALOG_STANDARD: widget = QWidget() layout = QHBoxLayout() layout.setMargin(0) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(2) self.combo = QgsMapLayerComboBox() layout.addWidget(self.combo) btn = QToolButton() btn.setText('...') btn.setToolTip(self.tr("Select file")) btn.clicked.connect(self.selectFile) layout.addWidget(btn) widget.setLayout(layout) filters = QgsMapLayerProxyModel.Filters() if self.param.datatype == [-1] or -1 in self.param.datatype: filters = QgsMapLayerProxyModel.HasGeometry if QgsWkbTypes.PointGeometry in self.param.datatype: filters |= QgsMapLayerProxyModel.PointLayer if QgsWkbTypes.LineGeometry in self.param.datatype: filters |= QgsMapLayerProxyModel.LineLayer if QgsWkbTypes.PolygonGeometry in self.param.datatype: filters |= QgsMapLayerProxyModel.PolygonLayer try: if iface.activeLayer().type() == QgsMapLayer.VectorLayer: self.combo.setLayer(iface.activeLayer()) except: pass if self.param.optional: self.combo.setAllowEmptyLayer(True) if ProcessingConfig.getSetting(ProcessingConfig.SHOW_CRS_DEF): self.combo.setShowCrs(True) self.combo.setFilters(filters) self.combo.setExcludedProviders(['grass']) self.combo.currentIndexChanged.connect( lambda: self.widgetValueHasChanged.emit(self)) self.combo.currentTextChanged.connect( lambda: self.widgetValueHasChanged.emit(self)) return widget elif self.dialogType == DIALOG_BATCH: widget = BatchInputSelectionPanel(self.param, self.row, self.col, self.dialog) widget.valueChanged.connect( lambda: self.widgetValueHasChanged.emit(self)) return widget else: self.combo = QComboBox() layers = self.dialog.getAvailableValuesOfType( ParameterVector, OutputVector) self.combo.setEditable(True) for layer in layers: self.combo.addItem(self.dialog.resolveValueDescription(layer), layer) if self.param.optional: self.combo.setEditText("") widget = QWidget() layout = QHBoxLayout() layout.setMargin(0) layout.setContentsMargins(0, 0, 0, 0) layout.setSpacing(2) layout.addWidget(self.combo) btn = QToolButton() btn.setText('...') btn.setToolTip(self.tr("Select file")) btn.clicked.connect(self.selectFile) layout.addWidget(btn) widget.setLayout(layout) return widget
def initWidgets(self): # Heavy overload # If there are advanced parameters — show corresponding groupbox for param in self.alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: self.grpAdvanced.show() break #widget_context = QgsProcessingParameterWidgetContext() #if iface is not None: # widget_context.setMapCanvas(iface.mapCanvas()) # Create widgets and put them in layouts for param in self.alg.parameterDefinitions(): if param.flags() & QgsProcessingParameterDefinition.FlagHidden: continue print('initWidgets - param.name(): {}'.format(param.name())) if param.isDestination(): # and param.name() != 'OUTPUT_ASC': continue else: wrapper = WidgetWrapperFactory.create_wrapper(param, self.parent) self.wrappers[param.name()] = wrapper #widget = wrapper.widget # 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: from qgis.gui import (QgsProcessingContextGenerator, QgsProcessingParameterWidgetContext) widget_context = QgsProcessingParameterWidgetContext() if iface is not None: widget_context.setMapCanvas(iface.mapCanvas()) wrapper.setWidgetContext(widget_context) widget = wrapper.createWrappedWidget(self.processing_context) wrapper.registerProcessingContextGenerator(self.context_generator) 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()) if isinstance(param, QgsProcessingParameterFeatureSource): layout = QHBoxLayout() layout.setSpacing(6) layout.setMargin(0) layout.addWidget(widget) button = QToolButton() icon = QIcon(os.path.join(pluginPath, 'images', 'iterate.png')) button.setIcon(icon) button.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding) button.setToolTip(self.tr('Iterate over this layer, creating a separate output for every feature in the layer')) button.setCheckable(True) layout.addWidget(button) layout.setAlignment(button, Qt.AlignTop) self.iterateButtons[param.name()] = button button.toggled.connect(self.buttonToggled) widget = QWidget() widget.setLayout(layout) label = None if not is_python_wrapper: label = wrapper.createWrappedLabel() else: label = wrapper.label if label is not None: if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: self.layoutAdvanced.addWidget(label) else: self.layoutMain.insertWidget( self.layoutMain.count() - 2, label) elif is_python_wrapper: desc = param.description() if isinstance(param, QgsProcessingParameterExtent): desc += self.tr(' (xmin, xmax, ymin, ymax)') if isinstance(param, QgsProcessingParameterPoint): desc += self.tr(' (x, y)') if param.flags() & QgsProcessingParameterDefinition.FlagOptional: desc += self.tr(' [optional]') widget.setText(desc) if param.flags() & QgsProcessingParameterDefinition.FlagAdvanced: self.layoutAdvanced.addWidget(widget) else: self.layoutMain.insertWidget( self.layoutMain.count() - 2, widget) for output in self.alg.destinationParameterDefinitions(): if output.flags() & QgsProcessingParameterDefinition.FlagHidden: continue #if self.in_place and param.name() in ('INPUT', 'OUTPUT'): # continue label = QLabel(output.description()) #print('initWidgets 2 - param.name(): {}'.format(param.name())) widget = DestinationSelectionPanel(output, self.alg) # TODO, overload self.layoutMain.insertWidget(self.layoutMain.count() - 1, label) self.layoutMain.insertWidget(self.layoutMain.count() - 1, widget) if isinstance(output, (QgsProcessingParameterRasterDestination, QgsProcessingParameterFeatureSink, QgsProcessingParameterVectorDestination # alk: checkboxes for Chloe handling ,ChloeCSVParameterFileDestination, ChloeASCParameterFileDestination, ChloeParameterFolderDestination) ): check = QCheckBox() check.setText(QCoreApplication.translate('ParametersPanel', 'Open output file(s) after running algorithm')) def skipOutputChanged(checkbox, skipped): checkbox.setEnabled(not skipped) if skipped: checkbox.setChecked(False) check.setChecked(not widget.outputIsSkipped()) check.setEnabled(not widget.outputIsSkipped()) widget.skipOutputChanged.connect(partial(skipOutputChanged, check)) self.layoutMain.insertWidget(self.layoutMain.count() - 1, check) self.checkBoxes[output.name()] = check # initial state if hasattr(output,'addToMapDefaultState'): check.setChecked(output.addToMapDefaultState) widget.setToolTip(param.toolTip()) self.outputWidgets[output.name()] = widget for wrapper in list(self.wrappers.values()): wrapper.postInitialize(list(self.wrappers.values())) # # alk: checkboxes for Chloe handling # for output in self.alg.destinationParameterDefinitions(): # if output.flags() & QgsProcessingParameterDefinition.FlagHidden: # continue # if isinstance(output, (ChloeCSVParameterFileDestination)) or isinstance(output, (ChloeASCParameterFileDestination)): # check = QCheckBox() # check.setText(QCoreApplication.translate('ParametersPanel', 'Open output file(s) after running algorithm')) # def skipOutputChanged(checkbox, skipped): # checkbox.setEnabled(not skipped) # if skipped: # checkbox.setChecked(False) # check.setChecked(not widget.outputIsSkipped()) # check.setEnabled(not widget.outputIsSkipped()) # widget.skipOutputChanged.connect(partial(skipOutputChanged, check)) # print(str(self.layoutMain)+1) # self.layoutMain.insertWidget(self.layoutMain.count() - 1, check) # self.checkBoxes[output.name()] = check # # connecting alg outputLoading info with checkbox state # self.alg.outputLoading[output.name()] = check.isChecked() # def updateOutputLoadingState(alg, outputName, checkbox, state): # self.alg.outputLoading[outputName] = checkbox.isChecked() # print( outputName + " " + str(checkbox.isChecked()) + " " + str(self.alg.outputLoading) + " " + str(self.alg)) # #print(str(self.alg.parameters)) # check.stateChanged.connect(partial(updateOutputLoadingState, self, output.name(), check)) # alk: addition of wrapper special config handling # for dependancy between wrapper, i.e. changing the value # of a FileSelectionPanel entails the update of another widget for k in self.wrappers: w = self.wrappers[k] if hasattr(w,'getParentWidgetConfig'): print(str(w) + " " + "getParentWidgetConfig") config = w.getParentWidgetConfig() if config != None: p = self.wrappers[config['paramName']] m = getattr(w, config['refreshMethod']) if m!=None: print(str(p) + " " + str(p.widget)) # todo generalize valueChanged handling # to any type of widget componant if isinstance(p.widget, FileSelectionPanel): p.widget.leText.textChanged.connect(m) elif isinstance(p, RasterWidgetWrapper): try: p.combo.valueChanged.connect(m) # QGIS 3.8 version except: p.combo.currentIndexChanged.connect(m) # QGIS LTR 3.4