class Spanners(tool.Tool): """Dynamics tool in the quick insert panel toolbox.""" def __init__(self, panel): super(Spanners, self).__init__(panel) self.removemenu = QToolButton(self, autoRaise=True, popupMode=QToolButton.InstantPopup, icon=icons.get('edit-clear')) mainwindow = panel.parent().mainwindow() mainwindow.selectionStateChanged.connect(self.removemenu.setEnabled) self.removemenu.setEnabled(mainwindow.hasSelection()) ac = documentactions.DocumentActions.instance( mainwindow).actionCollection self.removemenu.addAction(ac.tools_quick_remove_slurs) layout = QHBoxLayout() layout.addWidget(self.removemenu) layout.addStretch(1) self.layout().addLayout(layout) self.layout().addWidget(ArpeggioGroup(self)) self.layout().addWidget(GlissandoGroup(self)) self.layout().addWidget(SpannerGroup(self)) self.layout().addWidget(GraceGroup(self)) self.layout().addStretch(1) def icon(self): """Should return an icon for our tab.""" return symbols.icon("spanner_phrasingslur") def title(self): """Should return a title for our tab.""" return _("Spanners") def tooltip(self): """Returns a tooltip""" return _("Slurs, spanners, etcetera.")
class Spanners(tool.Tool): """Dynamics tool in the quick insert panel toolbox.""" def __init__(self, panel): super(Spanners, self).__init__(panel) self.removemenu = QToolButton(self, autoRaise=True, popupMode=QToolButton.InstantPopup, icon=icons.get('edit-clear')) mainwindow = panel.parent().mainwindow() mainwindow.selectionStateChanged.connect(self.removemenu.setEnabled) self.removemenu.setEnabled(mainwindow.hasSelection()) ac = documentactions.DocumentActions.instance(mainwindow).actionCollection self.removemenu.addAction(ac.tools_quick_remove_slurs) layout = QHBoxLayout() layout.addWidget(self.removemenu) layout.addStretch(1) self.layout().addLayout(layout) self.layout().addWidget(ArpeggioGroup(self)) self.layout().addWidget(GlissandoGroup(self)) self.layout().addWidget(SpannerGroup(self)) self.layout().addWidget(GraceGroup(self)) self.layout().addStretch(1) def icon(self): """Should return an icon for our tab.""" return symbols.icon("spanner_phrasingslur") def title(self): """Should return a title for our tab.""" return _("Spanners") def tooltip(self): """Returns a tooltip""" return _("Slurs, spanners, etcetera.")
class Articulations(tool.Tool): """Articulations tool in the quick insert panel toolbox. """ def __init__(self, panel): super(Articulations, self).__init__(panel) self.shorthands = QCheckBox(self) self.shorthands.setChecked(True) self.removemenu = QToolButton(self, autoRaise=True, popupMode=QToolButton.InstantPopup, icon=icons.get('edit-clear')) mainwindow = panel.parent().mainwindow() mainwindow.selectionStateChanged.connect(self.removemenu.setEnabled) self.removemenu.setEnabled(mainwindow.hasSelection()) ac = documentactions.DocumentActions.instance( mainwindow).actionCollection self.removemenu.addAction(ac.tools_quick_remove_articulations) self.removemenu.addAction(ac.tools_quick_remove_ornaments) self.removemenu.addAction(ac.tools_quick_remove_instrument_scripts) layout = QHBoxLayout() layout.addWidget(self.shorthands) layout.addWidget(self.removemenu) layout.addStretch(1) self.layout().addLayout(layout) for cls in ( ArticulationsGroup, OrnamentsGroup, SignsGroup, OtherGroup, ): self.layout().addWidget(cls(self)) self.layout().addStretch(1) app.translateUI(self) def translateUI(self): self.shorthands.setText(_("Allow shorthands")) self.shorthands.setToolTip( _("Use short notation for some articulations like staccato.")) self.removemenu.setToolTip(_("Remove articulations etc.")) def icon(self): """Should return an icon for our tab.""" return symbols.icon("articulation_prall") def title(self): """Should return a title for our tab.""" return _("Articulations") def tooltip(self): """Returns a tooltip""" return _("Different kinds of articulations and other signs.")
class Articulations(tool.Tool): """Articulations tool in the quick insert panel toolbox. """ def __init__(self, panel): super(Articulations, self).__init__(panel) self.shorthands = QCheckBox(self) self.shorthands.setChecked(True) self.removemenu = QToolButton(self, autoRaise=True, popupMode=QToolButton.InstantPopup, icon=icons.get('edit-clear')) mainwindow = panel.parent().mainwindow() mainwindow.selectionStateChanged.connect(self.removemenu.setEnabled) self.removemenu.setEnabled(mainwindow.hasSelection()) ac = documentactions.DocumentActions.instance(mainwindow).actionCollection self.removemenu.addAction(ac.tools_quick_remove_articulations) self.removemenu.addAction(ac.tools_quick_remove_ornaments) self.removemenu.addAction(ac.tools_quick_remove_instrument_scripts) layout = QHBoxLayout() layout.addWidget(self.shorthands) layout.addWidget(self.removemenu) layout.addStretch(1) self.layout().addLayout(layout) for cls in ( ArticulationsGroup, OrnamentsGroup, SignsGroup, OtherGroup, ): self.layout().addWidget(cls(self)) self.layout().addStretch(1) app.translateUI(self) def translateUI(self): self.shorthands.setText(_("Allow shorthands")) self.shorthands.setToolTip(_( "Use short notation for some articulations like staccato.")) self.removemenu.setToolTip(_( "Remove articulations etc.")) def icon(self): """Should return an icon for our tab.""" return symbols.icon("articulation_prall") def title(self): """Should return a title for our tab.""" return _("Articulations") def tooltip(self): """Returns a tooltip""" return _("Different kinds of articulations and other signs.")
class EjdexplInt: def __init__(self, iface): self.iface = iface self.plugin_dir = os.path.dirname(__file__) self.searchobj = None self.readconfig() self.updateconfig() self.srsitem = CanvasItems(self.iface.mapCanvas(),self.config['search_color'],self.config['search_style'],self.config['search_width'],self.config['search_icon'],self.config['search_size']) self.db = QSqlDatabase.addDatabase('QODBC') self.db.setDatabaseName(self.config['connection']) locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join(self.plugin_dir,'i18n','EjdexplInt_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) def tr(self, message): return QCoreApplication.translate('EjdexplInt', message) def initGui(self): self.action = QAction(QIcon(":/plugins/EjdexplInt/icons/icon.png"),self.tr(u'Activate EjdExplorer tool'),self.iface.mainWindow()) self.action.setWhatsThis(u"Activate EjdExplorer tool") self.action.triggered.connect(self.run) self.tbmenu = QMenu() self.ag1 = QActionGroup(self.tbmenu,exclusive=True) self.acPol = self.ag1.addAction(QAction(QIcon(':/plugins/EjdexplInt/icons/Icons8-Ios7-Maps-Polygon.ico'),self.tr(u'Draw polygon'),self.tbmenu,checkable=True)) self.acLin = self.ag1.addAction(QAction(QIcon(':/plugins/EjdexplInt/icons/Icons8-Ios7-Maps-Polyline.ico'),self.tr(u'Draw line'),self.tbmenu,checkable=True)) self.acPnt = self.ag1.addAction(QAction(QIcon(':/plugins/EjdexplInt/icons/Icons8-Ios7-Maps-Geo-Fence.ico'),self.tr(u'Draw point'),self.tbmenu,checkable=True)) self.acAlay = self.ag1.addAction(QAction(QIcon(':/plugins/EjdexplInt/icons/Icons8-Ios7-Maps-Layers.ico'),self.tr(u'Active selection'),self.tbmenu,checkable=True)) self.acPobj = self.ag1.addAction(QAction(QIcon(':/plugins/EjdexplInt/icons/Icons8-Ios7-Maps-Quest.ico'),self.tr(u'Previous object'),self.tbmenu,checkable=True)) self.tbmenu.addActions(self.ag1.actions()); self.acPol.setChecked(self.config['searchtool']==u'polygon') self.acLin.setChecked(self.config['searchtool']==u'line') self.acPnt.setChecked(self.config['searchtool']==u'point') self.acAlay.setChecked(self.config['searchtool']==u'selection') self.acPobj.setChecked(self.config['searchtool']==u'search') self.tbmenu.addSeparator() self.ag2 = QActionGroup(self.tbmenu,exclusive=True) self.acSingle = self.ag2.addAction(QAction(self.tr(u'Use single mode'),self.tbmenu,checkable=True)) self.acBulk = self.ag2.addAction(QAction(self.tr(u'Use bulk mode'),self.tbmenu,checkable=True)) self.acMerge = self.ag2.addAction(QAction(self.tr(u'Use merge mode'),self.tbmenu,checkable=True)) self.tbmenu.addActions(self.ag2.actions()); self.acSingle.setChecked(self.config['tabchoice']==u'single') self.acBulk.setChecked(self.config['tabchoice']==u'bulk') self.acMerge.setChecked(self.config['tabchoice']==u'merge') if self.config['old_behavior'] == 0: self.tbmenu.addSeparator() self.acClear = QAction(self.tr(u'Clear'),self.tbmenu,checkable=False) self.acClear.triggered.connect(self.clearSearch) self.tbmenu.addAction(self.acClear) self.toolButton = QToolButton() self.toolButton.addAction(self.action) self.toolButton.setDefaultAction(self.action) self.toolButton.setMenu(self.tbmenu) self.toolButton.setPopupMode(QToolButton.MenuButtonPopup) self.iface.addToolBarWidget(self.toolButton) self.iface.addPluginToMenu(self.tr(u'Activate EjdExplorer tool'), self.action) self.ag1.triggered.connect(self.drawChanged) def drawChanged(self, action): if action.isChecked(): self.run() def clearSearch(self): if self.config['old_behavior'] == 0: self.srsitem.clearMarkerGeom() def unload(self): self.iface.removePluginMenu(self.tr(u'Activate EjdExplorer tool'), self.action) self.iface.removeToolBarIcon(self.action) del self.tbmenu # No parent del self.toolButton # No parent def run(self): geoms = None canvas = self.iface.mapCanvas() if self.config['old_behavior'] == 0: self.srsitem.clearMarkerGeom() if self.acPol.isChecked(): # polygon tool = CaptureTool(canvas, self.geometryAdded, CaptureTool.CAPTURE_POLYGON) canvas.setMapTool(tool) elif self.acLin.isChecked(): # line tool = CaptureTool(canvas, self.geometryAdded, CaptureTool.CAPTURE_LINE) canvas.setMapTool(tool) elif self.acPnt.isChecked(): # point tool = AddPointTool(canvas, self.geometryAdded) canvas.setMapTool(tool) elif self.acAlay.isChecked(): # active layer selection layer = self.iface.activeLayer() if (layer) and (layer.type() == QgsMapLayer.VectorLayer): selection = layer.selectedFeatures() if (selection): for f in selection: if geoms == None: geoms = f.geometry() else: geoms = geoms.combine( f.geometry() ) if (geoms != None): self.geometryAdded(geoms) else: self.iface.messageBar().pushMessage(self.tr(u'EjdExplorer - Object definition'), self.tr(u'No object found'), QgsMessageBar.CRITICAL, 6) elif self.acPobj.isChecked(): # existing object geoms = self.searchobj if (geoms != None): self.geometryAdded(geoms) else: self.iface.messageBar().pushMessage(self.tr(u'EjdExplorer - Object definition'), self.tr(u'No existing object found'), QgsMessageBar.CRITICAL, 6) self.acPol.setChecked(True) else: self.iface.messageBar().pushMessage(self.tr(u'EjdExplorer - Object definition'), self.tr(u'Uknown search tool'), QgsMessageBar.CRITICAL, 6) def cnvobj2wkt (self,gobj,epsg_in,epsg_out, buffer_pol, buffer_lin): # Buffer around search object; negative for polygon or positive for points and lines if gobj.type() == 2: # Polygon gobj = gobj.buffer(buffer_pol,8) else: # Line or Point gobj = gobj.buffer(buffer_lin,8) crsSrc = QgsCoordinateReferenceSystem(int(epsg_in)) crsDest = QgsCoordinateReferenceSystem(int(epsg_out)) xform = QgsCoordinateTransform(crsSrc, crsDest) i = gobj.transform(xform) return gobj.exportToWkt() def geometryAdded(self, geom): self.iface.messageBar().pushMessage(self.tr(u'EjdExplorer - Start EjdExplorer'), self.tr(u'Starting EjdExplorer program, takes a few seconds..'), QgsMessageBar.INFO, 6) self.searchobj = geom if self.config['old_behavior'] == 0: self.srsitem.setMarkerGeom(geom) epsg_in = self.iface.mapCanvas().mapRenderer().destinationCrs().authid().replace('EPSG:','') geom_txt = self.cnvobj2wkt (geom,epsg_in,self.config['epsg'],self.config['buffer_pol'],self.config['buffer_lin']) txt1, txt2 = self.getlists (geom_txt) mode = u'single' if self.acBulk.isChecked(): mode = u'bulk' if self.acMerge.isChecked(): mode = u'merge' # NB! parameters dosn't work as expected, LIFA contacted (and admit to an error in their program) txt = u'start ' + self.config['command'] + u' "' + self.config['parameter'].format(mode, txt1,txt2) + u'"' txt = txt.encode('latin-1') if len(txt) <= 8190: # max length of command-line parameter os.system ( txt) else: self.iface.messageBar().pushMessage(self.tr(u'EjdExplorer - Start EjdExplorer'), self.tr(u'To many entities selected; try with a smaller search object'), QgsMessageBar.CRITICAL, 6) self.iface.actionPan().trigger() def msgbox (self,txt1): cb = QApplication.clipboard() cb.setText(txt1) msgBox = QMessageBox() msgBox.setText(txt1) msgBox.exec_() def getlists(self, wkt): ejrlrv = [] matrnr = [] if (self.db.open()==True): query = QSqlQuery (self.config['sqlquery'].format(wkt,self.config['epsg'])) while (query.next()): ejrlrv.append(query.value(0)) matrnr.append(query.value(1)) else: self.iface.messageBar().pushMessage(self.tr(u'EjdExplorer - Database Error'), db.lastError().text(), QgsMessageBar.INFO, 6) return u','.join(ejrlrv), u','.join(matrnr) def readconfig(self): s = QSettings() k = __package__ self.config = { 'epsg': unicode(s.value(k + "/epsg" , "25832", type=str)), 'buffer_pol': s.value(k + "/buffer_pol" , -0.1, type=float), 'buffer_lin': s.value(k + "/buffer_lin" , 0.1, type=float), 'searchtool': unicode(s.value(k + "/searchtool" , "point", type=str)).lower(), 'tabchoice': unicode(s.value(k + "/tabchoice" , "single", type=str)).lower(), 'sqlquery': unicode(s.value(k + "/sqlquery" , "select LTRIM(RTRIM(CONVERT(varchar(10), [landsejerlavskode]))) as ejrlvnr, LTRIM(RTRIM([matrikelnummer])) as matrnr from [dbo].[Jordstykke] where geometry::STGeomFromText('{0}',{1}).STIntersects([geometri])=1", type=str)), 'connection': unicode(s.value(k + "/connection" , "Driver={SQL Server};Server=f-sql12;Database=LOIS;Trusted_Connection=Yes;", type=str)), 'command': unicode(s.value(k + "/command" , 'C:/"Program Files (x86)"/LIFA/EjdExplorer/LIFA.EjdExplorer.GUI.exe', type=str)), 'parameter': unicode(s.value(k + "/parameter" , 'ejdexpl://?mode={0}&CadastralDistrictIdentifier={1}&RealPropertyKey={2}', type=str)), 'search_color': str(s.value(k + "/search_color", "#FF0000", type=str)), 'search_width': s.value(k + "/search_width", 4, type=int), 'search_style': s.value(k + "/search_style", 1, type=int), 'search_icon': s.value(k + "/search_icon", QgsVertexMarker.ICON_CROSS, type=int), 'search_size': s.value(k + "/search_size", 30, type=int), 'old_behavior': s.value(k + "/old_behavior", 0, type=int) } self.srsitem = CanvasItems(self.iface.mapCanvas(),self.config['search_color'],self.config['search_style'],self.config['search_width'],self.config['search_icon'],self.config['search_size']) def updateconfig(self): s = QSettings() k = __package__ s.setValue(k + "/epsg", self.config['epsg']) s.setValue(k + "/buffer_pol", self.config['buffer_pol']) s.setValue(k + "/buffer_lin", self.config['buffer_lin']) s.setValue(k + "/searchtool", self.config['searchtool']) s.setValue(k + "/tabchoice", self.config['tabchoice']) s.setValue(k + "/sqlquery", self.config['sqlquery']) s.setValue(k + "/connection", self.config['connection']) s.setValue(k + "/command", self.config['command']) s.setValue(k + "/parameter", self.config['parameter']) s.setValue(k + "/search_color", self.config['search_color']) s.setValue(k + "/search_style", self.config['search_style']) s.setValue(k + "/search_width", self.config['search_width']) s.setValue(k + "/search_icon", self.config['search_icon']) s.setValue(k + "/search_size", self.config['search_size']) s.setValue(k + "/old_behavior", self.config['old_behavior']) s.sync
class ToolBar(QToolBar): """A tool bar.""" def __init__(self, parentWidget, dockWidgetName, iface, pluginDir): """Constructor. Args: parentWidget (QToolBar): A reference to the parent widget. dockWidgetName (str): A name of the dock widget. iface (QgisInterface): A reference to the QgisInterface. pluginDir (QDir): A plugin directory. """ self.dW = parentWidget self.dWName = dockWidgetName self.iface = iface self.pluginDir = pluginDir super(ToolBar, self).__init__(self.dW) self._setup_self() def _setup_self(self): """Sets up self.""" self.setObjectName(u'toolbar') self._build_widgets() def _build_widgets(self): """Builds own widgets.""" self.iface.initializationCompleted.connect(self._set_icon_size) iconsDir = QDir(self.pluginDir.path() + u'/data/icons') self.openTabActionGroup = QActionGroup(self) self.loadVfkAction = QAction(self) self.loadVfkAction.setObjectName(u'loadVfkAction') self.loadVfkAction.setToolTip(u'Načtení VFK souboru') self.loadVfkAction.setCheckable(True) loadVfkIcon = QIcon() loadVfkIcon.addPixmap(QPixmap(iconsDir.filePath(u'loadvfk.png'))) self.loadVfkAction.setIcon(loadVfkIcon) self.openTabActionGroup.addAction(self.loadVfkAction) self.addAction(self.loadVfkAction) self.loadVfkAction.trigger() self.editAction = QAction(self) self.editAction.setObjectName(u'editAction') self.editAction.setToolTip(u'Editace') self.editAction.setCheckable(True) editIcon = QIcon() editIcon.addPixmap(QPixmap(iconsDir.filePath(u'edit.png'))) self.editAction.setIcon(editIcon) self.openTabActionGroup.addAction(self.editAction) self.addAction(self.editAction) self.checkAnalysisAction = QAction(self) self.checkAnalysisAction.setObjectName(u'checkAnalysisAction') self.checkAnalysisAction.setToolTip(u'Kontroly a analýzy') self.checkAnalysisAction.setCheckable(True) checkIcon = QIcon() checkIcon.addPixmap(QPixmap(iconsDir.filePath(u'checkanalysis.png'))) self.checkAnalysisAction.setIcon(checkIcon) self.openTabActionGroup.addAction(self.checkAnalysisAction) self.addAction(self.checkAnalysisAction) self.addSeparator() self.zoomFullExtentAction = self.iface.actionZoomFullExtent() self.addAction(self.zoomFullExtentAction) self.zoomToSelectedAction = self.iface.actionZoomToSelected() self.addAction(self.zoomToSelectedAction) self.selectToolButton = QToolButton(self) self.selectToolButton.setObjectName(u'selectToolButton') self.selectToolButton.setPopupMode(1) self.selectRectangleAction = self.iface.actionSelectRectangle() self.selectToolButton.addAction(self.selectRectangleAction) self.selectPolygonAction = self.iface.actionSelectPolygon() self.selectToolButton.addAction(self.selectPolygonAction) self.selectFreehandAction = self.iface.actionSelectFreehand() self.selectToolButton.addAction(self.selectFreehandAction) self.selectRadiusAction = self.iface.actionSelectRadius() self.selectToolButton.addAction(self.selectRadiusAction) for action in self.iface.attributesToolBar().actions(): if action.objectName() == 'ActionSelect': self.qgisSelectToolButton = action.defaultWidget() break self.qgisSelectToolButton.toggled.connect( self._set_default_action_selectToolButton) self._set_default_action_selectToolButton() self.addWidget(self.selectToolButton) self.selectionToolButton = QToolButton(self) self.selectionToolButton.setObjectName(u'selectionToolButton') self.selectionToolButton.setPopupMode(1) for action in self.iface.attributesToolBar().actions(): if action.objectName() == 'ActionSelection': self.qgisSelectionToolButton = action.defaultWidget() break self.selectionToolButton.addActions( self.qgisSelectionToolButton.actions()) self.selectionToolButton.setDefaultAction( self.qgisSelectionToolButton.defaultAction()) self.addWidget(self.selectionToolButton) for action in self.iface.attributesToolBar().actions(): if action.objectName() == 'mActionDeselectAll': self.deselectAllAction = action break self.addAction(self.deselectAllAction) self.openTableAction = self.iface.actionOpenTable() self.addAction(self.openTableAction) def _set_icon_size(self): """Sets icon size according to the current QGIS settings.""" self.setIconSize(self.iface.mainWindow().iconSize()) def _set_default_action_selectToolButton(self): """Sets selectToolButton's default action.""" self.selectToolButton.setDefaultAction( self.qgisSelectToolButton.defaultAction())
class FeatureSelectorWidget(QWidget): featureIdentified = pyqtSignal(QgsFeature) def __init__(self, parent): QWidget.__init__(self, parent) editLayout = QHBoxLayout() editLayout.setContentsMargins(0, 0, 0, 0) editLayout.setSpacing(2) self.setLayout(editLayout) self.lineEdit = QLineEdit(self) self.lineEdit.setReadOnly(True) editLayout.addWidget(self.lineEdit) self.highlightFeatureButton = QToolButton(self) self.highlightFeatureButton.setPopupMode(QToolButton.MenuButtonPopup) self.highlightFeatureAction = QAction(QgsApplication.getThemeIcon("/mActionHighlightFeature.svg"), "Highlight feature", self) self.scaleHighlightFeatureAction = QAction(QgsApplication.getThemeIcon("/mActionScaleHighlightFeature.svg"), "Scale and highlight feature", self) self.panHighlightFeatureAction = QAction(QgsApplication.getThemeIcon("/mActionPanHighlightFeature.svg"), "Pan and highlight feature", self) self.highlightFeatureButton.addAction(self.highlightFeatureAction) self.highlightFeatureButton.addAction(self.scaleHighlightFeatureAction) self.highlightFeatureButton.addAction(self.panHighlightFeatureAction) self.highlightFeatureButton.setDefaultAction(self.highlightFeatureAction) editLayout.addWidget(self.highlightFeatureButton) self.mapIdentificationButton = QToolButton(self) self.mapIdentificationButton.setIcon(QgsApplication.getThemeIcon("/mActionMapIdentification.svg")) self.mapIdentificationButton.setText("Select on map") self.mapIdentificationButton.setCheckable(True) editLayout.addWidget(self.mapIdentificationButton) self.mapIdentificationButton.clicked.connect(self.mapIdentification) self.highlightFeatureButton.triggered.connect(self.highlightActionTriggered) self.layer = None self.mapTool = None self.canvas = None self.windowWidget = None self.highlight = None self.feature = QgsFeature() def setCanvas(self, mapCanvas): self.mapTool = QgsMapToolIdentifyFeature(mapCanvas) self.mapTool.setButton(self.mapIdentificationButton) self.canvas = mapCanvas def setLayer(self, layer): self.layer = layer def setFeature(self, feature, canvasExtent = CanvasExtent.Fixed): self.lineEdit.clear() self.feature = feature if not self.feature.isValid() or self.layer is None: return featureTitle = feature.attribute(self.layer.displayField()) if featureTitle == '': featureTitle = feature.id() self.lineEdit.setText(str(featureTitle)) self.highlightFeature(canvasExtent) def clear(self): self.feature = QgsFeature() self.lineEdit.clear() def mapIdentification(self): if self.layer is None or self.mapTool is None or self.canvas is None: return self.mapTool.setLayer(self.layer) self.canvas.setMapTool(self.mapTool) self.windowWidget = QWidget.window(self) self.canvas.window().raise_() self.canvas.activateWindow() self.canvas.setFocus() self.mapTool.featureIdentified.connect(self.mapToolFeatureIdentified) self.mapTool.deactivated.connect(self.mapToolDeactivated) def mapToolFeatureIdentified(self, feature): feature = QgsFeature(feature) self.featureIdentified.emit(feature) self.unsetMapTool() self.setFeature(feature) def mapToolDeactivated(self): if self.windowWidget is not None: self.windowWidget.raise_() self.windowWidget.activateWindow() def highlightFeature(self, canvasExtent = CanvasExtent.Fixed): if self.canvas is None or not self.feature.isValid(): return geom = self.feature.geometry() if geom is None: return if canvasExtent == CanvasExtent.Scale: featBBox = geom.boundingBox() featBBox = self.canvas.mapSettings().layerToMapCoordinates(self.layer, featBBox) extent = self.canvas.extent() if not extent.contains(featBBox): extent.combineExtentWith(featBBox) extent.scale(1.1) self.canvas.setExtent(extent) self.canvas.refresh() elif canvasExtent == CanvasExtent.Pan: centroid = geom.centroid() center = centroid.asPoint() center = self.canvas.mapSettings().layerToMapCoordinates(self.layer, center) self.canvas.zoomByFactor(1.0, center) # refresh is done in this method # highlight self.delete_highlight() self.highlight = QgsHighlight(self.canvas, geom, self.layer) settings = QSettings() color = QColor(settings.value("/Map/highlight/color", QGis.DEFAULT_HIGHLIGHT_COLOR.name())) alpha = int(settings.value("/Map/highlight/colorAlpha", QGis.DEFAULT_HIGHLIGHT_COLOR.alpha())) buffer = 2*float(settings.value("/Map/highlight/buffer", QGis.DEFAULT_HIGHLIGHT_BUFFER_MM)) min_width = 2*float(settings.value("/Map/highlight/min_width", QGis.DEFAULT_HIGHLIGHT_MIN_WIDTH_MM)) self.highlight.setColor(color) # sets also fill with default alpha color.setAlpha(alpha) self.highlight.setFillColor(color) # sets fill with alpha self.highlight.setBuffer(buffer) self.highlight.setMinWidth(min_width) self.highlight.setWidth(4.0) self.highlight.show() self.timer = QTimer(self) self.timer.setSingleShot(True) self.timer.timeout.connect(self.delete_highlight) self.timer.start(3000) def delete_highlight(self): if self.highlight is not None: self.highlight.hide() del self.highlight self.highlight = None def unsetMapTool(self): if self.canvas is not None and self.mapTool is not None: # this will call mapToolDeactivated self.canvas.unsetMapTool(self.mapTool) def highlightActionTriggered(self, action): self.highlightFeatureButton.setDefaultAction(action) if action == self.highlightFeatureAction: self.highlightFeature() elif action == self.scaleHighlightFeatureAction: self.highlightFeature(CanvasExtent.Scale) elif action == self.panHighlightFeatureAction: self.highlightFeature(CanvasExtent.Pan)