Exemplo n.º 1
0
    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""

        icon_path = os.path.join(self.plugin_dir, 'res', 'icon.png')
        self.add_action(icon_path,
                        text=self.tr(u'go2mapillary'),
                        callback=self.run,
                        parent=self.iface.mainWindow())

        self.dlg = go2mapillaryDockWidget()

        self.dockwidget = QDockWidget("go2mapillary", self.iface.mainWindow())
        self.dockwidget.setObjectName("go2mapillary")
        self.dockwidget.setWidget(self.dlg)
        self.dlg.webView.page().setNetworkAccessManager(
            QgsNetworkAccessManager.instance())
        self.dlg.webView.page().mainFrame().setScrollBarPolicy(
            Qt.Vertical, Qt.ScrollBarAlwaysOff)
        self.dlg.webView.page().mainFrame().setScrollBarPolicy(
            Qt.Horizontal, Qt.ScrollBarAlwaysOff)
        self.canvas.mapToolSet.connect(self.toggleViewer)
        self.viewer = mapillaryViewer(self.dlg.webView)
        self.viewer.messageArrived.connect(self.viewerConnection)
        QgsExpressionContextUtils.setGlobalVariable("mapillaryCurrentKey",
                                                    "noKey")
        self.mapSelectionTool = None
        self.coverage = mapillary_coverage(self.iface)
        self.mapillaryOverview = None
        self.mapillaryCoverage = None
        self.mapillaryLocations = None
Exemplo n.º 2
0
    def initGui(self):
        """Initalise the Plugin-UI"""
        if not pyratImport:
            iface.messageBar().pushMessage("PyRAT not found!",
                                           level=Qgis.Critical)
            return

        if 'PyRAT' not in [
                action.text()
                for action in iface.mainWindow().menuBar().actions()
        ]:
            self.pyratMenu = iface.mainWindow().menuBar().addMenu('PyRAT')
        else:
            self.pyratMenu = [
                action.menu()
                for action in iface.mainWindow().menuBar().actions()
                if action.text() == 'PyRAT'
            ][0]

        action = QAction("Layer2PyRAT", iface.mainWindow())
        action.triggered.connect(PyRATBridge.layerToPyrat)
        self.pyratMenu.addAction(action)

        action = QAction("PyRAT2Layer", iface.mainWindow())
        action.triggered.connect(PyRATBridge.pyratToLayer)
        self.pyratMenu.addAction(action)

        action = QAction("Cleanup PyRAT", iface.mainWindow())
        action.triggered.connect(PyRATBridge.clearPyRAT)
        self.pyratMenu.addAction(action)

        action = QAction("Show PyRAT GUI", iface.mainWindow())
        action.triggered.connect(self.showPyrat)
        self.pyratMenu.addAction(action)

        self.pyratMenu.addSeparator()

        # Init PyRAT-Tools, adapted from pyrat.viewer for qgis
        from inspect import getmembers, isclass

        modules = [
            pyrat.load, pyrat.save, pyrat.transform, pyrat.filter, pyrat.polar,
            pyrat.insar, pyrat.plugins, pyrat.viewer
        ]

        for current_module in modules:
            modules = getmembers(current_module, isclass)
            for mod in modules:
                if issubclass(mod[1], pyrat.Worker):
                    plugin = mod[1]
                    if (hasattr(plugin, 'gui')
                            and plugin.gui['entry'] != "Python console"):
                        self.addMenuEntry(plugin)

        self.pyratLayerTree = QDockWidget("PyRAT Layers", iface.mainWindow())
        PyRATBridge.layerTreeWidget = LayerTreeWidget(
            parent=self.pyratLayerTree, viewer=ViewerToQGISInterface)
        self.pyratLayerTree.setObjectName("PyRAT Layers")
        self.pyratLayerTree.setWidget(PyRATBridge.layerTreeWidget)
        iface.addDockWidget(Qt.LeftDockWidgetArea, self.pyratLayerTree)
    def __init__(self, base_config, iface):
        QDockWidget.__init__(self, iface.mainWindow())
        self.setupUi(self)
        self.iface = iface
        self.db_simple_factory = DbSimpleFactory()
        QgsGui.instance().enableAutoGeometryRestore(self)

        self.schema_validations = {}
        self.requested_roles = [ValidationResultModel.Roles.MESSAGE]

        self.current_configuration = ValidateConfiguration()
        self.current_schema_identificator = ""
        self.current_models_model = SchemaModelsModel()
        self.current_datasets_model = SchemaDatasetsModel()
        self.current_baskets_model = SchemaBasketsModel()
        self.current_filter_mode = SchemaDataFilterMode.NO_FILTER

        self.filter_data_panel = FilterDataPanel(self)
        self.filter_data_panel.setMaximumHeight(self.fontMetrics().lineSpacing() * 10)
        self.filter_layout.addWidget(self.filter_data_panel)
        self._reset_gui()

        self.run_button.clicked.connect(self._run)
        self.visibilityChanged.connect(self._visibility_changed)

        self.result_table_view.setContextMenuPolicy(Qt.CustomContextMenu)
        self.result_table_view.customContextMenuRequested.connect(self._table_clicked)
Exemplo n.º 4
0
 def __init__(self, parent=None):
     QDockWidget.__init__(self, parent)
     self.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)
     self.setWidget(MyQueriesWidget())
     self.setWindowTitle(tr("ui_my_queries", "QuickOSM - My queries"))
     self.widget().signal_delete_query_successful.connect(
         self.signal_delete_query_successful.emit)
Exemplo n.º 5
0
    def __init__(self, iface, parent=None):
        QDockWidget.__init__(self, parent)
        self.setupUi(self)
        self.iface = iface
        self.message_bar = self.iface.messageBar()
        self.layer = None

        self._gui_elements = [
            self.layers_combo, self.unfinished_only_check,
            self.unfinished_fields_combo, self.previous_button,
            self.next_button, self.defects_list, self.columns_choice_button
        ]

        self._toggle_gui_elements(False)

        self.settings = QSettings("CatAIS", "VeriSO")

        self.next_button.clicked.connect(self.next_button_clicked)
        self.previous_button.clicked.connect(self.previous_button_clicked)
        self.defects_list.currentItemChanged.connect(
            self.defects_list_currentItemChanged)
        self.layers_combo.currentIndexChanged.connect(
            self.layers_combo_currentIndexChanged)
        self.unfinished_fields_combo.currentIndexChanged.connect(
            self.unfinished_fields_combo_currentIndexChanged)
        self.unfinished_only_check.toggled.connect(
            self.unfinished_only_check_toggled)
        self.columns_choice_button.clicked.connect(
            self.columns_choice_button_clicked)
    def __init__(self, iface):
        QDockWidget.__init__(self, iface.mainWindow())
        self.setupUi(self)
        self.newsFrame.setVisible(False)

        self.iface = iface
        self.search_threads = None  # []
        self.extent_renderer = RubberBandResultRenderer()

        self.cmbStatusFilter.addItem(self.tr('All'), STATUS_FILTER_ALL)
        self.cmbStatusFilter.addItem(self.tr('Valid'), STATUS_FILTER_ONLY_WORKS)
        self.cmbStatusFilter.currentIndexChanged.connect(self.start_search)

        if hasattr(self.txtSearch, 'setPlaceholderText'):
            self.txtSearch.setPlaceholderText(self.tr("Search string..."))

        self.delay_timer = QTimer(self)
        self.delay_timer.setSingleShot(True)
        self.delay_timer.setInterval(250)

        self.delay_timer.timeout.connect(self.start_search)
        self.txtSearch.textChanged.connect(self.delay_timer.start)
        self.btnFilterByExtent.toggled.connect(self.toggle_filter_button)
        self.one_process_work = QMutex()

        self.add_last_used_services()
        
        self.show_news()
Exemplo n.º 7
0
 def __init__(self, iface, layers, parent=None):
     QDockWidget.__init__(self, parent)
     self.setupUi(self)
     self.layers = layers
     self.count_id = None
     self.sensor = None
     self.status = self.layers.IMPORT_STATUS_DEFINITIVE
Exemplo n.º 8
0
 def __init__(self, parent=None):
     QDockWidget.__init__(self, parent)
     self.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)
     self.setWidget(QueryWidget())
     self.setWindowTitle(tr("ui_query", "QuickOSM - Query"))
     self.widget().signal_new_query_successful.connect(
         self.signal_new_query_successful.emit)
Exemplo n.º 9
0
    def initGui(self):
        # add action to toolbar
        self.action = QAction(QIcon(":/plugins/mutant/img/icon.svg"), "Mutant",
                              self.iface.mainWindow())
        self.iface.addToolBarIcon(self.action)
        self.tool = MutantMap(self.canvas, self.action)
        self.saveTool = None
        self.action.triggered.connect(self.activateTool)
        self.tool.deactivated.connect(self.deactivateTool)

        # create the widget to display information
        self.mutantwidget = MutantWidget(self.iface)
        self.tool.moved.connect(self.mutantwidget.toolMoved)
        self.tool.pressed.connect(self.mutantwidget.toolPressed)
        self.mutantwidget.toggleMutant.clicked.connect(self.toggleTool)
        self.mutantwidget.plotOnMove.clicked.connect(self.toggleMouseClick)

        # create the dockwidget with the correct parent and add the widget
        self.mutantdockwidget = QDockWidget("Mutant", self.iface.mainWindow())
        self.mutantdockwidget.setObjectName("Mutant")
        self.mutantdockwidget.setWidget(self.mutantwidget)
        # QObject.connect(self.mutantdockwidget,
        # SIGNAL('visibilityChanged ( bool )'), self.showHideDockWidget)

        # add the dockwidget to iface
        self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.mutantdockwidget)
Exemplo n.º 10
0
    def __init__(self, iface):
        QDockWidget.__init__(self, iface.mainWindow())
        self.setupUi(self)
        self.newsFrame.setVisible(False)

        self.iface = iface
        self.search_threads = None  # []
        self.extent_renderer = RubberBandResultRenderer()

        self.cmbStatusFilter.addItem(self.tr('All'), STATUS_FILTER_ALL)
        self.cmbStatusFilter.addItem(self.tr('Valid'),
                                     STATUS_FILTER_ONLY_WORKS)
        self.cmbStatusFilter.currentIndexChanged.connect(self.start_search)

        if hasattr(self.txtSearch, 'setPlaceholderText'):
            self.txtSearch.setPlaceholderText(self.tr("Search string..."))

        self.delay_timer = QTimer(self)
        self.delay_timer.setSingleShot(True)
        self.delay_timer.setInterval(250)

        self.delay_timer.timeout.connect(self.start_search)
        self.txtSearch.textChanged.connect(self.delay_timer.start)
        self.btnFilterByExtent.toggled.connect(self.toggle_filter_button)
        self.one_process_work = QMutex()

        self.add_last_used_services()

        self.show_news()
Exemplo n.º 11
0
    def initGui(self):
        # Create action that will show plugin widget
        self.action = QAction(
            QIcon(os.path.join(self.plugin_dir, "icons/select2.png")),
            # the following does not seem to work anymore, maybe since PyQt5?!
            #QIcon(':/plugins/LayerFeatureLabeler/icons/select.png'),
            u"LayerFeatureLabeler",
            self.iface.mainWindow())
        # connect the action to the run method
        self.action.triggered.connect(self.run)

        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.action)
        self.iface.addPluginToMenu(u"&VectorLayerTool", self.action)

        #creating dock view intance
        # self.dock = attributePainterDialog(self.iface)
        self.dockwidget = QDockWidget("Layer Feature Labeler",
                                      self.iface.mainWindow())
        self.dockwidget.setObjectName("Layer Feature Labeler")
        self.dockwidget.setWidget(self.dock)
        self.layerHighlighted = None
        self.sourceFeat = None

        # here the map tool is choosen
        self.sourceMapTool = IdentifyGeometry(self.canvas, pickMode='active')
        self.destinationMapTool = IdentifyGeometry(self.canvas,
                                                   pickMode='active')
Exemplo n.º 12
0
    def on_view_plots(self, plot_type):

        layer = self.iface.activeLayer()
        if not layer:
            return

        if layer.id() not in self.__config:
            if layer.geometryType() != QgsWkbTypes.NullGeometry:
                dlg = ConfigurePlotDialog(layer, self.iface.mainWindow())
                if dlg.exec_():
                    conf = dlg.config()
                    self.__config[layer.id()] = conf

                    json_config = json.dumps(self.__config)
                    QgsProject.instance().writeEntry("QGeoloGIS", "config",
                                                     json_config)
                else:
                    return
            else:
                return

        if plot_type == "logs":
            self.__dock = QDockWidget("Well Logs")
        else:
            self.__dock = QDockWidget("Timeseries")
        self.__dock.setObjectName("QGeoloGIS_plot_view_dock")
        dialog = MainDialog(self.__dock, plot_type, self.__config, layer,
                            self.iface)
        self.__dock.setWidget(dialog)
        self.iface.addDockWidget(Qt.LeftDockWidgetArea, self.__dock)
Exemplo n.º 13
0
    def __init__(self, iface, parent=None):
        QDockWidget.__init__(self, parent)

        self.setupUi(self)
        self.iface = iface
        self.message_bar = self.iface.messageBar()
        # self.layer = None
        self._gui_elements = [self.treeWidget]
Exemplo n.º 14
0
    def __init__(self):
        """Constructor for the dialog.
        
        """

        QDockWidget.__init__(self)

        self.setupUi(self)
Exemplo n.º 15
0
 def __init__(self):
     """Constructor for the dialog.
     
     """
     
     QDockWidget.__init__(self)
                     
     self.setupUi(self)
Exemplo n.º 16
0
    def __init__(self, parent, plugin):
        self.plugin = plugin
        QDockWidget.__init__(self, parent)
        self.setupUi(self)

        self.btnApply.setIcon(
            QIcon(str(DIR_PLUGIN_ROOT / "resources/arrow_green.png")))
        self.btnMask.setIcon(
            QIcon(str(DIR_PLUGIN_ROOT / "resources/add_mask.png")))
        self.btnLayer.setIcon(
            QIcon(str(DIR_PLUGIN_ROOT / "resources/add_layer.png")))
        self.btnHelp.setIcon(
            QIcon(QgsApplication.iconPath("mActionHelpContents.svg")))

        self.tableResult.installEventFilter(self)  # cf. eventFilter method
        self.tableResult.cellDoubleClicked.connect(self.onChoose)
        self.tableResult.cellEntered.connect(self.cellEntered)

        self.editSearch.returnPressed.connect(self.onReturnPressed)
        self.btnSearch.clicked.connect(self.onReturnPressed)
        self.btnApply.clicked.connect(self.onApply)
        self.btnHelp.clicked.connect(
            lambda: showPluginHelp(filename="../doc/index"))

        self.btnLocalize.clicked.connect(self.doLocalize)
        self.btnMask.clicked.connect(self.onMask)
        self.btnLayer.clicked.connect(self.onLayer)

        self.singleLayerId = {
            QgsWkbTypes.PolygonGeometry: None,
            QgsWkbTypes.LineGeometry: None,
            QgsWkbTypes.PointGeometry: None,
        }
        self.singleLayerName = {
            QgsWkbTypes.PolygonGeometry: "OSM Place Search Polygons",
            QgsWkbTypes.LineGeometry: "OSM Place Search Lines",
            QgsWkbTypes.PointGeometry: "OSM Place Search Points",
        }
        self.memoryLayerType = {
            QgsWkbTypes.PolygonGeometry: "MultiPolygon",
            QgsWkbTypes.LineGeometry: "MultiLineString",
            QgsWkbTypes.PointGeometry: "Point",
        }

        try:
            self.cbExtent.setChecked(tools.limitSearchToExtent)
        except:
            self.cbExtent.setChecked(tools.limitSearchToExtent)

        self.currentExtent = self.plugin.canvas.extent()

        self.tableResult.horizontalHeader().setSectionResizeMode(
            QHeaderView.ResizeToContents)

        try:
            self.editSearch.setText(self.plugin.lastSearch)
        except:
            pass
 def _setDocWidget(self):
     self._dockwidget = QDockWidget(
         QApplication.translate("OpenLayersOverviewWidget",
                                "OpenLayers Overview"),
         self._iface.mainWindow())
     self._dockwidget.setObjectName("dwOpenlayersOverview")
     self._oloWidget = OpenLayersOverviewWidget(self._iface,
                                                self._dockwidget,
                                                self._olLayerTypeRegistry)
     self._dockwidget.setWidget(self._oloWidget)
 def __init__(self, parent,iface,msettings):
     self.parent = parent
     self.iface=iface
     #midvsettings instance
     self.ms = msettings
     self.ms.loadSettings()
     #initiate the dockwidget
     QDockWidget.__init__(self, self.parent)        
     self.setAttribute(Qt.WA_DeleteOnClose)
     self.setupUi( self )#Required by Qt4 to initialize the UI
     self.initUI()
 def __init__(self, parent, iface, msettings):
     self.parent = parent
     self.iface = iface
     #midvsettings instance
     self.ms = msettings
     self.ms.loadSettings()
     #initiate the dockwidget
     QDockWidget.__init__(self, self.parent)
     self.setAttribute(Qt.WA_DeleteOnClose)
     self.setupUi(self)  #Required by Qt4 to initialize the UI
     self.initUI()
Exemplo n.º 20
0
    def __init__(self, iface, parent=None, featuresId=None, layer=None):

        QDockWidget.__init__(self)

        self.setupUi(self)

        self.DEFAULT_URL = ("http://" + config.IP + ":" + str(config.PORT) +
                            "/viewer.html")
        self.DEFAULT_EMPTY = ("http://" + config.IP + ":" + str(config.PORT) +
                              "/none.html")
        self.DEFAULT_BLANK = ("http://" + config.IP + ":" + str(config.PORT) +
                              "/blank.html")

        # Create Viewer
        self.CreateViewer()

        self.plugin_path = os.path.dirname(os.path.realpath(__file__))
        self.iface = iface
        self.canvas = self.iface.mapCanvas()
        self.parent = parent

        # Orientation from image
        self.yaw = math.pi
        self.bearing = None

        self.layer = layer
        self.featuresId = featuresId

        self.actualPointDx = None
        self.actualPointSx = None
        self.actualPointOrientation = None

        self.selected_features = qgsutils.getToFeature(self.layer,
                                                       self.featuresId)

        # Get image path
        self.current_image = self.GetImage()

        # Check if image exist
        if os.path.exists(self.current_image) is False:
            qgsutils.showUserAndLogMessage(u"Information: ",
                                           u"There is no associated image.")
            self.resetQgsRubberBand()
            self.ChangeUrlViewer(self.DEFAULT_EMPTY)
            return

        # Copy file to local server
        self.CopyFile(self.current_image)

        # Set RubberBand
        self.resetQgsRubberBand()
        self.setOrientation()
        self.setPosition()
Exemplo n.º 21
0
class SeptimaGeoSearch(object):

    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface

        # initialize plugin directory
        self.plugin_dir = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()).path() + "/python/plugins/" + __package__

        # initialize locale. Default to Danish
        self.config = QSettings()
        localePath = ""
        try:
            locale = self.config.value("locale/userLocale")[0:2]
        except:
            locale = 'da'

        if QFileInfo(self.plugin_dir).exists():
            localePath = self.plugin_dir + "/i18n/" + locale + ".qt.qm"

        if QFileInfo(localePath).exists():
            self.translator = QTranslator()
            self.translator.load(localePath)

            if qVersion() > '4.3.3':
                QgsApplication.installTranslator(self.translator)
        
        # new config method
        self.settings = Settings()
        self.options_factory = OptionsFactory(self.settings)
        self.options_factory.setTitle('Geosearch DK')
        iface.registerOptionsWidgetFactory(self.options_factory)

    def initGui(self):
        # create the widget to display information
        self.searchwidget = SearchBox(self.iface)
        # create the dockwidget with the correct parent and add the valuewidget
        self.searchdockwidget = QDockWidget(
            "Geosearch DK", self.iface.mainWindow()
        )
        self.searchdockwidget.setObjectName("Geosearch DK")
        self.searchdockwidget.setWidget(self.searchwidget)
        # add the dockwidget to iface
        self.iface.addDockWidget(
            Qt.TopDockWidgetArea, self.searchdockwidget
        )
        # Make changed settings apply immediately
        self.settings.settings_updated.connect(self.searchwidget.readconfig)

    def unload(self):
        self.searchwidget.unload() # try to avoid processing events, when QGIS is closing
        self.iface.removeDockWidget(self.searchdockwidget)
        self.iface.unregisterOptionsWidgetFactory(self.options_factory)
Exemplo n.º 22
0
 def initGui(self):
     # create the widget to display information
     self.searchwidget = SearchBox(self.iface)
     # create the dockwidget with the correct parent and add the valuewidget
     self.searchdockwidget = QDockWidget("Geosearch DK",
                                         self.iface.mainWindow())
     self.searchdockwidget.setObjectName("Geosearch DK")
     self.searchdockwidget.setWidget(self.searchwidget)
     # add the dockwidget to iface
     self.iface.addDockWidget(Qt.TopDockWidgetArea, self.searchdockwidget)
     # Make changed settings apply immediately
     self.settings.settings_updated.connect(self.searchwidget.readconfig)
Exemplo n.º 23
0
    def initGui(self):
        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        icon_path = os.path.join(self.plugin_dir, 'res', 'icon.png')
        self.mainAction = self.add_action(icon_path,
                                          text=self.tr(u'go2mapillary'),
                                          callback=self.run,
                                          checkable=True,
                                          parent=self.iface.mainWindow())

        self.dlg = go2mapillaryDockWidget()

        self.dockwidget = QDockWidget("go2mapillary", self.iface.mainWindow())
        self.dockwidget.setObjectName("go2mapillary")
        self.dockwidget.setWidget(self.dlg)
        self.dockwidget.visibilityChanged.connect(
            self.mlyDockwidgetvisibilityChanged)
        self.dlg.webView.page().setNetworkAccessManager(
            QgsNetworkAccessManager.instance())
        self.dlg.webView.page().mainFrame().setScrollBarPolicy(
            Qt.Vertical, Qt.ScrollBarAlwaysOff)
        self.dlg.webView.page().mainFrame().setScrollBarPolicy(
            Qt.Horizontal, Qt.ScrollBarAlwaysOff)
        self.canvas.mapToolSet.connect(self.toggleViewer)
        self.viewer = mapillaryViewer(self)
        self.viewer.messageArrived.connect(self.viewerConnection)
        self.viewer.openFilter.connect(self.filter_images_func)
        #QgsExpressionContextUtils.setGlobalVariable( "mapillaryCurrentKey","noKey")
        QgsExpressionContextUtils.removeGlobalVariable("mapillaryCurrentKey")
        self.mapSelectionTool = None
        self.coverage = mapillary_coverage(self)
        self.filterDialog = mapillaryFilter(self)
        self.filterAction_images = QAction(QIcon(icon_path),
                                           'filter mapillary coverage',
                                           self.iface.mainWindow())
        self.filterAction_sequences = QAction(QIcon(icon_path),
                                              'filter mapillary coverage',
                                              self.iface.mainWindow())
        self.filterAction_overview = QAction(QIcon(icon_path),
                                             'filter mapillary coverage',
                                             self.iface.mainWindow())
        self.filterAction_images.triggered.connect(self.filter_images_func)
        self.filterAction_sequences.triggered.connect(
            self.filter_sequences_func)
        self.filterAction_overview.triggered.connect(self.filter_overview_func)
        self.sample_cursor = mapillary_cursor(self)
        self.sample_settings = mapillarySettings(self)
        self.sample_cursor.update_ds(
            self.sample_settings.settings['sample_source'])
        self.samples_form = mapillaryForm(self)
        self.iface.projectRead.connect(self.removeMapillaryLayerGroup)
        self.canvas.mapCanvasRefreshed.connect(self.mapRefreshed)
        self.enableMapillaryRender = False
Exemplo n.º 24
0
    def __init__(self, parent=None):
        QDockWidget.__init__(self, parent)
        self.setObjectName("PythonConsole")
        self.setWindowTitle(QCoreApplication.translate("PythonConsole", "Python Console"))
        # self.setAllowedAreas(Qt.BottomDockWidgetArea)

        self.console = PythonConsoleWidget(self)
        self.setWidget(self.console)
        self.setFocusProxy(self.console)

        # try to restore position from stored main window state
        if iface and not iface.mainWindow().restoreDockWidget(self):
            iface.mainWindow().addDockWidget(Qt.BottomDockWidgetArea, self)
Exemplo n.º 25
0
    def __init__(self, parent, canvas, add_dock_widget):
        QDockWidget.__init__(self, parent)
        self.setupUi(self)

        self.selectCurrentPathAction = QAction(self.tr('Select current path'), self.selectButton)
        self.selectCurrentPathAction.triggered.connect(self.onSelectCurrentPathAction)
        self.selectButton.setDefaultAction(self.selectCurrentPathAction)
        self.configureSelectionAction = QAction(self.tr('Configure Select'), self.selectButton)
        self.configureSelectionAction.triggered.connect(self.onConfigureSelectAction)
        self.selectButton.addAction(self.configureSelectionAction)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.canvas = canvas
        self.addDockWidget = add_dock_widget
Exemplo n.º 26
0
    def __init__(self, parent=None):
        QDockWidget.__init__(self, parent)
        self.setObjectName("PythonConsole")
        self.setWindowTitle(QCoreApplication.translate("PythonConsole", "Python Console"))
        # self.setAllowedAreas(Qt.BottomDockWidgetArea)

        self.console = PythonConsoleWidget(self)
        self.setWidget(self.console)
        self.setFocusProxy(self.console)

        # try to restore position from stored main window state
        if iface and not iface.mainWindow().restoreDockWidget(self):
            iface.mainWindow().addDockWidget(Qt.BottomDockWidgetArea, self)
Exemplo n.º 27
0
class SeptimaGeoSearch(object):
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface

        # initialize plugin directory
        self.plugin_dir = QFileInfo(QgsApplication.qgisUserDatabaseFilePath()
                                    ).path() + "/python/plugins/" + __package__

        # initialize locale. Default to Danish
        self.config = QSettings()
        localePath = ""
        try:
            locale = self.config.value("locale/userLocale")[0:2]
        except:
            locale = 'da'

        if QFileInfo(self.plugin_dir).exists():
            localePath = self.plugin_dir + "/i18n/" + locale + ".qt.qm"

        if QFileInfo(localePath).exists():
            self.translator = QTranslator()
            self.translator.load(localePath)

            if qVersion() > '4.3.3':
                QgsApplication.installTranslator(self.translator)

        # new config method
        self.settings = Settings()
        self.options_factory = OptionsFactory(self.settings)
        self.options_factory.setTitle('Geosearch DK')
        iface.registerOptionsWidgetFactory(self.options_factory)

    def initGui(self):
        # create the widget to display information
        self.searchwidget = SearchBox(self.iface)
        # create the dockwidget with the correct parent and add the valuewidget
        self.searchdockwidget = QDockWidget("Geosearch DK",
                                            self.iface.mainWindow())
        self.searchdockwidget.setObjectName("Geosearch DK")
        self.searchdockwidget.setWidget(self.searchwidget)
        # add the dockwidget to iface
        self.iface.addDockWidget(Qt.TopDockWidgetArea, self.searchdockwidget)
        # Make changed settings apply immediately
        self.settings.settings_updated.connect(self.searchwidget.readconfig)

    def unload(self):
        self.searchwidget.unload(
        )  # try to avoid processing events, when QGIS is closing
        self.iface.removeDockWidget(self.searchdockwidget)
        self.iface.unregisterOptionsWidgetFactory(self.options_factory)
Exemplo n.º 28
0
    def __init__(self, iface, layer, currentFeature):
        self.iface = iface
        self.layer = layer
        self.renderer = self.iface.mapCanvas().mapSettings()
        self.settings = MySettings()
        QDockWidget.__init__(self)
        self.setupUi(self)

        self.setWindowTitle("ItemBrowser: %s" % layer.name())
        if layer.isSpatial() is False:
            self.panCheck.setChecked(False)
            self.panCheck.setEnabled(False)
            self.scaleCheck.setChecked(False)
            self.scaleCheck.setEnabled(False)

        self.previousButton.setArrowType(Qt.LeftArrow)
        self.nextButton.setArrowType(Qt.RightArrow)
        icon = QIcon(":/plugins/itembrowser/icons/openform.svg")
        self.editFormButton.setIcon(icon)

        # actions
        icon = QIcon(":/plugins/itembrowser/icons/action.svg")
        self.actionButton.setIcon(icon)
        self.attrAction = layer.actions()
        actions = [self.attrAction.actions()[i] for i in range(len(self.attrAction.actions()))]
        preferredAction = layer.customProperty("ItemBrowserPreferedAction", "")
        if preferredAction not in actions:
            dfltAction = self.attrAction.defaultAction("Layer")
            if dfltAction:
                preferredAction = dfltAction.name()
        preferredActionFound = False
        for i, action in enumerate(actions):
            qAction = QAction(QIcon(":/plugins/itembrowser/icons/action.svg"), action.name(), self)
            qAction.triggered.connect(lambda checked, uid=action.id(),i=i: self.doAction(uid,i))
            self.actionButton.addAction(qAction)
            if action.name() == preferredAction:
                self.actionButton.setDefaultAction(qAction)
                preferredActionFound = True
        if len(actions) == 0:
            self.actionButton.setEnabled(False)
        elif not preferredActionFound:
            self.actionButton.setDefaultAction(self.actionButton.actions()[0])

        self.rubber = QgsRubberBand(self.iface.mapCanvas())
        self.selectionChanged()
        if currentFeature == self.listCombo.currentIndex():
            self.on_listCombo_currentIndexChanged(currentFeature)
        else:
            self.listCombo.setCurrentIndex(currentFeature)
        self.layer.willBeDeleted.connect(self.close)
        self.layer.selectionChanged.connect(self.selectionChanged)
Exemplo n.º 29
0
    def __init__(self, parent, iface):
        QDockWidget.__init__(self, parent)
        self.setupUi(self)
        self.layerComboBox.currentIndexChanged.connect(self.layerChanged)
        self.stateButton.clicked.connect(self.stateChanged)
        self.iface = iface
        self.layerComboBox.insertItem(self.layerComboBox.count(),
                                      self.tr('Wastewater Structure'),
                                      'wastewater_structure')
        self.layerComboBox.insertItem(self.layerComboBox.count(),
                                      self.tr('Reach'), 'reach')
        self.stateButton.setProperty('state', 'inactive')

        self.mapToolAddReach = QgepMapToolAddReach(
            self.iface, QgepLayerManager.layer('vw_qgep_reach'))
Exemplo n.º 30
0
 def toggleWidget(self, event):
     if self.searchDockWidget == None:
         self.searchDockWidget = QDockWidget(self.iface.mainWindow())
         self.searchDockWidget.setWindowTitle(self.tr(u'Suche'))
         self.searchDockWidget.setWidget(self.dlg)
         self.searchDockWidget.closeEvent = self.toggleWidget
         self.iface.addDockWidget(self.searchDockWidgetArea,
                                  self.searchDockWidget)
         self.action.setChecked(True)
     else:
         self.searchDockWidgetArea = self.iface.mainWindow().dockWidgetArea(
             self.searchDockWidget)
         self.iface.removeDockWidget(self.searchDockWidget)
         self.searchDockWidget = None
         self.action.setChecked(False)
Exemplo n.º 31
0
    def __init__(self, parent, iface1, mdl1):
        QDockWidget.__init__(self, parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.parent = parent
        self.location = Qt.RightDockWidgetArea
        self.iface = iface1

        self.setupUi(self)
        #self.connect(self, SIGNAL("dockLocationChanged(Qt::DockWidgetArea)"), self.setLocation)
        self.mdl = mdl1
        #self.showed = False

        self.mdl.rowsInserted.connect(self.addPersistentEditorForRows)
        self.cboXAxis.currentIndexChanged.connect(self.changeXAxisLabeling)
        self.butLoadXAxisSteps.clicked.connect(self.loadXAxisStepsFromFile)
        self.butSaveAs.clicked.connect(self.saveAs)
Exemplo n.º 32
0
    def __init__(self, iface, chart):

        dir_path = os.path.dirname(os.path.realpath(__file__))
        qml = os.path.join(dir_path, "qml", "scatterplot.qml")
        self.view = QQuickView()
        self.view.setResizeMode(QQuickView.SizeRootObjectToView)
        self.view.rootContext().setContextProperty("pychart", chart)
        self.view.setColor(QColor("#000000"))
        self.view.setSource(QUrl.fromLocalFile(qml))

        self.container = QWidget.createWindowContainer(self.view)
        self.widget = QDockWidget()
        self.widget.setWidget(self.container)
        iface.addDockWidget(Qt.BottomDockWidgetArea, self.widget)

        self.read_settings()
Exemplo n.º 33
0
 def eventFilter(self, source, event):
     ''' Event Filter '''
     if (event.type() == QEvent.MouseButtonPress
             and source is self.VManager.viewport()
             and self.VManager.itemAt(event.pos()) is None):
         self.VManager.clearSelection()
     return QDockWidget.eventFilter(self, source, event)
Exemplo n.º 34
0
 def resizeEvent(self, event):
     fsize = max(8, event.size().width() / 50)
     if fsize != self.fontSize:
         self.fontSize = fsize
         self.dockWidgetContents.setStyleSheet(
             "font-weight: bold; font-size: {}pt".format(self.fontSize))
     return QDockWidget.resizeEvent(self, event)
Exemplo n.º 35
0
    def __init__(self):
        QDockWidget.__init__(self)
        self.setWindowTitle('Shogun Editor')
        self.setContextMenuPolicy(Qt.DefaultContextMenu)
        self.setLayoutDirection(Qt.LeftToRight)
        self.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)
        self.setFloating(False)

        self.dockWidgetContents = QWidget(self)
        self.dockWidgetContents.setGeometry(QRect(20, 30, 320, 700))
        self.newConnectionButton = QPushButton(self.dockWidgetContents)
        self.newConnectionButton.setGeometry(QRect(10, 0, 141, 27))
        self.newConnectionButton.setText('New Connection')
        self.treeWidget = QTreeWidget(self.dockWidgetContents)
        self.treeWidget.setGeometry(QRect(10, 40, 300, 650))
        self.treeWidget.setContextMenuPolicy(Qt.CustomContextMenu)
        self.treeWidget.setHeaderHidden(True)
        self.treeWidget.setColumnCount(1)
 def _setDocWidget(self):
     self._dockwidget = QDockWidget(QApplication.translate(
         "OpenLayersOverviewWidget", "OpenLayers Overview"),
                                    self._iface.mainWindow())
     self._dockwidget.setObjectName("dwOpenlayersOverview")
     self._oloWidget = OpenLayersOverviewWidget(self._iface,
                                                self._dockwidget,
                                                self._olLayerTypeRegistry)
     self._dockwidget.setWidget(self._oloWidget)
 def __init__(self):
     QDockWidget.__init__(self)
     # Set up the user interface from Designer.
     self.ui = Ui_PDOKservices()
     self.ui.setupUi(self)
     self.servicesView = self.ui.servicesView
     # only select one row at a time:
     self.servicesView.setSelectionMode(self.servicesView.SingleSelection)
     # select whole row if an item is clicked
     self.servicesView.setSelectionBehavior(self.servicesView.SelectRows)
     self.servicesView.setAutoScroll(False)
     self.layerSearch = self.ui.layerSearch
     self.geocoderSearch = self.ui.geocoderSearch
     self.geocoderResultSearch = self.ui.geocoderResultSearch
     self.geocoderResultView = self.ui.geocoderResultView
     self.geocoderResultView.setSelectionMode(self.geocoderResultView.SingleSelection)
     # select whole row if an item is clicked
     self.geocoderResultView.setSelectionBehavior(self.geocoderResultView.SelectRows)
     self.tabs = self.ui.tabWidget
     self.radioDocked = self.ui.radio_docked_widget
     self.btnCheckPdokJson = self.ui.btn_check_pdokjson
Exemplo n.º 38
0
 def toggleWidget(self, event):
     if self.searchDockWidget == None:
         self.searchDockWidget = QDockWidget(self.iface.mainWindow())
         self.searchDockWidget.setWindowTitle(self.tr(u'Suche'))
         self.searchDockWidget.setWidget(self.dlg)
         self.searchDockWidget.closeEvent = self.toggleWidget
         self.iface.addDockWidget(self.searchDockWidgetArea, self.searchDockWidget)
         self.action.setChecked(True)
     else:
         self.searchDockWidgetArea = self.iface.mainWindow().dockWidgetArea(self.searchDockWidget)
         self.iface.removeDockWidget(self.searchDockWidget)
         self.searchDockWidget = None
         self.action.setChecked(False)
Exemplo n.º 39
0
 def initGui(self):
     # create the widget to display information
     self.searchwidget = SearchBox(self.iface)
     # create the dockwidget with the correct parent and add the valuewidget
     self.searchdockwidget = QDockWidget(
         "Geosearch DK", self.iface.mainWindow()
     )
     self.searchdockwidget.setObjectName("Geosearch DK")
     self.searchdockwidget.setWidget(self.searchwidget)
     # add the dockwidget to iface
     self.iface.addDockWidget(
         Qt.TopDockWidgetArea, self.searchdockwidget
     )
     # Make changed settings apply immediately
     self.settings.settings_updated.connect(self.searchwidget.readconfig)
Exemplo n.º 40
0
 def initGui(self):
     # Create action that will show plugin widget
     self.action = QAction(
         QIcon(os.path.join(self.plugin_dir,"icon.png")),
         u"AttributePainter", self.iface.mainWindow())
     # connect the action to the run method
     self.action.triggered.connect(self.run)
     # Add toolbar button and menu item
     self.iface.addToolBarIcon(self.action)
     self.iface.addPluginToMenu(u"&foglioMappale", self.action)
     #creating dock view intance
     self.dock = attributePainterDialog(self.iface)
     self.apdockwidget=QDockWidget("AttributePainter" , self.iface.mainWindow() )
     self.apdockwidget.setObjectName("AttributePainter")
     self.apdockwidget.setWidget(self.dock)
     self.layerHighlighted = None
     self.sourceFeat = None
     #setting dock view buttons behavior
     self.dock.PickSource.toggled.connect(self.setSourceMapTool)
     self.dock.ResetSource.clicked.connect(self.resetSource)
     self.dock.PickDestination.clicked.connect(self.applyToDestination)
     self.dock.PickDestination.setDisabled(True)
     self.dock.PickApply.setDisabled(True)
     self.dock.PickApply.toggled.connect(self.setDestinationMapTool)
     self.dock.checkBox.clicked.connect(self.selectAllCheckbox)
     self.dock.tableWidget.setColumnCount(3)
     self.initTable()
     #setting interface behaviours
     self.session = destinationLayerState()
     try:
         #QGIS2 API
         self.iface.legendInterface().currentLayerChanged.connect(self.checkOnLayerChange)
     except:
         #QGIS3 API
         self.iface.currentLayerChanged.connect(self.checkOnLayerChange)
     self.iface.addDockWidget( Qt.LeftDockWidgetArea, self.apdockwidget )
     self.iface.projectRead.connect(self.resetSource)
     self.iface.newProjectCreated.connect(self.resetSource)
     self.canvas.mapToolSet.connect(self.toggleMapTool)
     self.sourceMapTool = IdentifyGeometry(self.canvas,pickMode='selection')
     self.destinationMapTool = IdentifyGeometry(self.canvas,pickMode='active')
     self.sourceMapTool.geomIdentified.connect(self.setSourceFeature)
     self.destinationMapTool.geomIdentified.connect(self.setDestinationFeature)
     #Call reset procedure to initialize widget
     self.dock.tableWidget.itemChanged.connect(self.highLightCellOverride)
     self.resetSource()
     self.actualLayer = None
class OLOverview(object):

    def __init__(self, iface, olLayerTypeRegistry):
        self._iface = iface
        self._olLayerTypeRegistry = olLayerTypeRegistry
        self._dockwidget = None
        self._oloWidget = None

    # Private
    def _setDocWidget(self):
        self._dockwidget = QDockWidget(QApplication.translate(
            "OpenLayersOverviewWidget", "OpenLayers Overview"),
                                       self._iface.mainWindow())
        self._dockwidget.setObjectName("dwOpenlayersOverview")
        self._oloWidget = OpenLayersOverviewWidget(self._iface,
                                                   self._dockwidget,
                                                   self._olLayerTypeRegistry)
        self._dockwidget.setWidget(self._oloWidget)

    def _initGui(self):
        self._setDocWidget()
        self._iface.addDockWidget(Qt.LeftDockWidgetArea, self._dockwidget)

    def _unload(self):
        self._dockwidget.close()
        self._iface.removeDockWidget(self._dockwidget)
        del self._oloWidget
        self._dockwidget = None

    # Public
    def setVisible(self, visible):
        if visible:
            if self._dockwidget is None:
                self._initGui()
        else:
            if self._dockwidget is not None:
                self._unload()
Exemplo n.º 42
0
class attributePainter:

    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        self.canvas = self.iface.mapCanvas()
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # Source feature rubberband definition
        colorSource = QColor(250,0,0,200)
        self.sourceEvid = QgsRubberBand(self.canvas)
        self.sourceEvid.setColor(colorSource)
        self.sourceEvid.setWidth(3)


    def initGui(self):
        # Create action that will show plugin widget
        self.action = QAction(
            QIcon(os.path.join(self.plugin_dir,"icon.png")),
            u"AttributePainter", self.iface.mainWindow())
        # connect the action to the run method
        self.action.triggered.connect(self.run)
        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.action)
        self.iface.addPluginToMenu(u"&foglioMappale", self.action)
        #creating dock view intance
        self.dock = attributePainterDialog(self.iface)
        self.apdockwidget=QDockWidget("AttributePainter" , self.iface.mainWindow() )
        self.apdockwidget.setObjectName("AttributePainter")
        self.apdockwidget.setWidget(self.dock)
        self.layerHighlighted = None
        self.sourceFeat = None
        #setting dock view buttons behavior
        self.dock.PickSource.toggled.connect(self.setSourceMapTool)
        self.dock.ResetSource.clicked.connect(self.resetSource)
        self.dock.PickDestination.clicked.connect(self.applyToDestination)
        self.dock.PickDestination.setDisabled(True)
        self.dock.PickApply.setDisabled(True)
        self.dock.PickApply.toggled.connect(self.setDestinationMapTool)
        self.dock.checkBox.clicked.connect(self.selectAllCheckbox)
        self.dock.tableWidget.setColumnCount(3)
        self.initTable()
        #setting interface behaviours
        self.session = destinationLayerState()
        try:
            #QGIS2 API
            self.iface.legendInterface().currentLayerChanged.connect(self.checkOnLayerChange)
        except:
            #QGIS3 API
            self.iface.currentLayerChanged.connect(self.checkOnLayerChange)
        self.iface.addDockWidget( Qt.LeftDockWidgetArea, self.apdockwidget )
        self.iface.projectRead.connect(self.resetSource)
        self.iface.newProjectCreated.connect(self.resetSource)
        self.canvas.mapToolSet.connect(self.toggleMapTool)
        self.sourceMapTool = IdentifyGeometry(self.canvas,pickMode='selection')
        self.destinationMapTool = IdentifyGeometry(self.canvas,pickMode='active')
        self.sourceMapTool.geomIdentified.connect(self.setSourceFeature)
        self.destinationMapTool.geomIdentified.connect(self.setDestinationFeature)
        #Call reset procedure to initialize widget
        self.dock.tableWidget.itemChanged.connect(self.highLightCellOverride)
        self.resetSource()
        self.actualLayer = None

    def selectAllCheckbox(self):
        '''
        select or deselect items in qtablewidget on "select all attributes" checkbox clicked
        '''
        for rowTabWidget in range(0,self.dock.tableWidget.rowCount()):
            self.dock.tableWidget.item(rowTabWidget,0).setCheckState(self.dock.checkBox.checkState())

    def initTable(self):
        '''
        QTableWidget initialization
        '''
        header = QTableWidgetItem("  ")
        header.setTextAlignment(Qt.AlignLeft)
        self.dock.tableWidget.setHorizontalHeaderItem(0,header)
        header = QTableWidgetItem("FIELD")
        header.setTextAlignment(Qt.AlignLeft)
        self.dock.tableWidget.setHorizontalHeaderItem(1,header)
        header = QTableWidgetItem("VALUE")
        header.setTextAlignment(Qt.AlignLeft)
        self.dock.tableWidget.setHorizontalHeaderItem(2,header)
        self.dock.tableWidget.resizeColumnsToContents()

    def setComboField(self,content,type,layer):
        '''
        returns a qcombobox loaded with compatible field names (depending on selected layer)
        '''
        combo = QComboBox();
        fieldNames = self.scanLayerFieldsNames(layer)
        fieldTypes = self.scanLayerFieldsTypes(layer)
        choices = []
        for n in range(0,len(fieldTypes)):
            if fieldTypes[n] == type:
                choices.append(fieldNames[n])
        combo.addItems(choices)
        if content in choices:
            combo.setCurrentIndex(choices.index(content))
        else:
            combo.addItem(content)
            combo.setCurrentIndex(combo.count()-1)
        combo.activated.connect(lambda: self.highlightCompatibleFields(LayerChange=None))
        return combo


    def getFieldsIterator(self,layer):
        try:
            return layer.pendingFields
        except:
            return layer.fields
                

    def scanLayerFieldsNames(self,layer):
        '''
        returns fields names as strings list
        '''
        if layer:
            return [field.name() for field in self.getFieldsIterator(layer)()]
        else:
            return []

    def scanLayerFieldsTypes(self,layer):
        '''
        returns fields types as qvariant list
        '''
        if layer:
            return [field.type() for field in self.getFieldsIterator(layer)()]
        else:
            return []

    def selectSource(self): 
        '''
        source feature selection procedure
        '''
        if self.layerHighlighted:
            self.resetSource()
        try:
            self.dock.tableWidget.itemChanged.disconnect(self.highLightCellOverride)
        except:
            pass
        #take first selected feature as source feature
        self.sourceFeat = self.selectedFeature
        #hightlight source feature with rubberband
        self.sourceEvid.setToGeometry(self.sourceFeat.geometry(),self.selectedLayer)
        #get current layer attributes labels list
        field_names = self.scanLayerFieldsNames(self.selectedLayer)
        field_types = self.scanLayerFieldsTypes(self.selectedLayer)
        self.sourceAttrsTab=[]
        self.dock.tableWidget.setRowCount(len(field_names))
        #loading attributes labels and values in QTableWidget
        for n in range(0,len(field_names)):
                item=QTableWidgetItem()
                item.setFlags(item.flags() | Qt.ItemIsUserCheckable)
                item.setCheckState(Qt.Unchecked)
                item.setText("")
                #set first column as checkbox
                self.dock.tableWidget.setItem(n,0,item)
                #set second colunm as attribute label as qcombobox widget
                self.dock.tableWidget.setCellWidget(n,1,self.setComboField(field_names[n],field_types[n],self.canvas.currentLayer()))
                #set third column as attribute value
                item = QTableWidgetItem()
                item.setData(Qt.DisplayRole,self.sourceFeat.attributes()[n])
                self.dock.tableWidget.setItem(n,2,item)
        #resize table to contents
        self.dock.tableWidget.resizeColumnsToContents()
        self.dock.tableWidget.horizontalHeader().setStretchLastSection(True)
        #procedure to recover same field selection if current source feature has the same layer of the precedent one
        if self.selectedLayer.id() != self.activeLayer:
            self.sourceAttrs={}
            self.activeLayer = self.selectedLayer.id()
        else:
            for Attr in self.sourceAttrs:
                self.dock.tableWidget.item(Attr,0).setCheckState(Qt.Checked)
        #Enable button to apply or reset
        self.dock.ResetSource.setEnabled(True)
        self.dock.tableWidget.itemChanged.connect(self.highLightCellOverride)
        self.checkOnLayerChange(self.canvas.currentLayer())

    def highLightCellOverride(obj,item):
        '''
        landing method on cell value change
        '''
        if item.column() == 2:
            item.setBackground(QBrush(QColor(183,213,225)))
            #item.setForeground (QBrush(QColor(255,0,0)))

    def toggleMapTool(self,mapTool):
        '''
        landing method on canvas maptool change
        '''
        self.dock.PickSource.blockSignals(True)
        self.dock.PickApply.blockSignals(True)
        if mapTool != self.sourceMapTool and mapTool != self.destinationMapTool:
            self.dock.PickSource.setChecked(False)
            self.dock.PickApply.setChecked(False)
        elif mapTool == self.sourceMapTool:
            self.dock.PickApply.setChecked(False)
        elif mapTool == self.destinationMapTool:
            self.dock.PickSource.setChecked(False)
        self.dock.PickSource.blockSignals(False)
        self.dock.PickApply.blockSignals(False)

    def checkOnLayerChange(self,cLayer):
        '''
        landing method on current layer change
        '''
        if cLayer and cLayer.type() == QgsMapLayer.VectorLayer:
            self.session.backupState(self.layerHighlighted, self.dock.tableWidget)
            # Restore a session for the current layer or custom table items to it
            if self.layerHighlighted:
                self.layerHighlighted.editingStarted.disconnect(self.checkEditable)
                self.layerHighlighted.editingStopped.disconnect(self.checkEditable)
            if cLayer:
                self.layerHighlighted = cLayer
                self.checkEditable()
                cLayer.editingStarted.connect(self.checkEditable)
                cLayer.editingStopped.connect(self.checkEditable)
            self.session.restoreState(cLayer,self.dock.tableWidget)
    
    def highlightCompatibleFields(self, LayerChange = True):
        '''
        method to highlight compatible field on selected feature (even on different layer)
        '''
        if self.dock.tableWidget.rowCount()>0:
            source_field_names = self.scanLayerFieldsNames(self.selectedLayer)
            source_field_types = self.scanLayerFieldsTypes(self.selectedLayer)
            destination_field_names = self.scanLayerFieldsNames(self.canvas.currentLayer())
            self.dock.tableWidget.itemChanged.disconnect(self.highLightCellOverride)
            for row in range (0,self.dock.tableWidget.rowCount()):
                if LayerChange:
                    self.dock.tableWidget.setCellWidget(row,1,self.setComboField(source_field_names[row],source_field_types[row],self.canvas.currentLayer()))
                if self.dock.tableWidget.cellWidget(row,1).currentText() in destination_field_names:
                    #self.dock.tableWidget.item(row,1).setForeground(QBrush(QColor(0,0,0)))
                    self.dock.tableWidget.item(row,2).setForeground(QBrush(QColor(0,0,0)))
                else:
                    #self.dock.tableWidget.item(row,1).setForeground(QBrush(QColor(130,130,130)))
                    self.dock.tableWidget.item(row,2).setForeground(QBrush(QColor(130,130,130)))
            self.dock.tableWidget.itemChanged.connect(self.highLightCellOverride)

    def checkEditable(self):
        '''
        method to enable or disable apply to destination button
        '''
        if self.layerHighlighted:
            self.highlightCompatibleFields()
            if self.layerHighlighted.isEditable() and self.sourceFeat:
                self.dock.PickDestination.setEnabled(True)
                self.dock.PickApply.setEnabled(True)
            else:
                self.dock.PickDestination.setDisabled(True)
                self.dock.PickApply.setDisabled(True)
    
    def resetSource(self):
        '''
        method to clear source and reset attribute table
        '''
        self.dock.tableWidget.itemChanged.disconnect(self.highLightCellOverride)
        self.doReset()
        #if self.canvas.layers()!=[]:
        #    self.iface.activeLayer().removeSelection()
        self.dock.tableWidget.itemChanged.connect(self.highLightCellOverride)

    def doReset(self):
        '''
        method to clear source and reset attribute table
        '''
        self.dock.PickDestination.setDisabled(True)
        #clear source highlight
        self.sourceEvid.reset()
        #clear source definition
        self.sourceFeat = None
        self.sourceAttrs={}
        self.activeLayer = "nn"
        self.session.removeState(self.canvas.currentLayer())
        self.layerHighlighted = None
        #clear dock widget
        while self.dock.tableWidget.rowCount()>0:
            self.dock.tableWidget.removeRow(0)
        self.dock.PickDestination.setEnabled(False)
        self.dock.ResetSource.setEnabled(False)

    def applyToDestination(self):
        '''
        method to apply selected fields to selected destination features
        '''
        if self.canvas.currentLayer().selectedFeatures()!=[]:
            self.sourceAttributes = self.getSourceAttrs()
            #apply source attribute values to selected destination features
            for f in self.canvas.currentLayer().selectedFeatures():
                self.applyToFeature(f,self.sourceAttributes)
            self.iface.activeLayer().removeSelection() 
            self.canvas.currentLayer().triggerRepaint()
        else:
            pass
            #print ("nothing selected")

    def getSourceAttrs(self):
        '''
        rebuild source attribute dict set to apply to destination features
        '''
        sourceAttrs={}
        for rowTabWidget in range(0,self.dock.tableWidget.rowCount()):
            rowCheckbox = self.dock.tableWidget.item(rowTabWidget,0)
            #take only checked attributes
            if rowCheckbox.checkState() == Qt.Checked:
                sourceAttrs.update({rowTabWidget:[self.dock.tableWidget.cellWidget(rowTabWidget,1).currentText(),self.dock.tableWidget.item(rowTabWidget,2).data(Qt.DisplayRole)]})
        return sourceAttrs

    def applyToFeature(self,feature,sourceSet):
        '''
        method to apply destination fields cyclying between feature fields
        '''
        #print (sourceSet.items())
        for attrId,attrValue in sourceSet.items():
            try:
                feature[attrValue[0]]=attrValue[1]
                self.canvas.currentLayer().updateFeature(feature)
                self.canvas.currentLayer().triggerRepaint()
            except Exception as e:
                print ('Exception in applyToFeature',e)
            self.highlight(feature.geometry())

    def highlight(self,geometry):
        def processEvents():
            try:
                qApp.processEvents()
            except:
                QApplication.processEvents()
                
        highlight = QgsRubberBand(self.canvas, geometry.type())
        highlight.setColor(QColor("#36AF6C"))
        highlight.setFillColor(QColor("#36AF6C"))
        highlight.setWidth(2)
        highlight.setToGeometry(geometry,self.canvas.currentLayer())
        processEvents()
        sleep(.1)
        highlight.hide()
        processEvents()
        sleep(.1)
        highlight.show()
        processEvents()
        sleep(.1)
        highlight.reset()
        processEvents()
        

    def run(self):
        '''
        show/hide the widget
        '''
        if self.apdockwidget.isVisible():
            self.apdockwidget.hide()
            self.resetSource()
        else:
            self.apdockwidget.show()

    def unload(self):
        '''
        Remove the plugin widget and clear source feature highlight
        '''
        if self.sourceFeat:
            self.sourceEvid.reset()
        self.iface.removeToolBarIcon(self.action)
        self.iface.removeDockWidget(self.apdockwidget)
        self.canvas.mapToolSet.disconnect(self.toggleMapTool)
        try:
            self.iface.legendInterface().currentLayerChanged.disconnect(self.checkOnLayerChange)
        except:
            self.iface.currentLayerChanged.disconnect(self.checkOnLayerChange)
        self.iface.projectRead.disconnect(self.resetSource)

    def setSourceFeature(self, layer, feature):
        '''
        landing method on source maptool identify
        '''
        self.selectedLayer = layer
        self.selectedFeature = feature
        self.dock.PickSource.setChecked(False)
        self.canvas.setMapTool(self.oldMapTool)
        self.selectSource()

    def setDestinationFeature(self, layer, feature):
        '''
        landing method on destination maptool identify
        '''
        sourceAttributes = self.getSourceAttrs()
        self.applyToFeature(feature,sourceAttributes)

    def setSourceMapTool(self, checked):
        '''
        landing method on pick source button toggle
        '''
        if checked:
            self.oldMapTool = self.canvas.mapTool()
            self.canvas.setMapTool(self.sourceMapTool)
        else:
            self.oldMapTool = self.canvas.mapTool()

    def setDestinationMapTool(self,checked):
        '''
        landing method on pick apply button toggle
        '''
        if checked:
            self.oldMapTool = self.canvas.mapTool()
            self.canvas.setMapTool(self.destinationMapTool)
        else:
            self.canvas.setMapTool(self.oldMapTool)
Exemplo n.º 43
0
class PostNAS_Search:

    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)
        # initialize locale
        locale = QSettings().value('locale/userLocale')[0:2]
        locale_path = os.path.join(self.plugin_dir,'i18n','PostNAS_Search_{}.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)

        # Create the dialog (after translation) and keep reference
        self.dlg = PostNAS_SearchDialog(iface=self.iface)
        self.conf = PostNAS_ConfDialog(iface=self.iface)

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'&PostNAS_Search')

        self.searchDockWidget = None
        self.searchDockWidgetArea = Qt.LeftDockWidgetArea

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('PostNAS_Search', message)

    def initGui(self):
        # Create Conf-Action and Menuentry
        self.confAction = QAction("Einstellungen", self.iface.mainWindow())
        self.confAction.setWhatsThis("Konfiguration der PostNAS-Suche")
        self.confAction.setStatusTip("Konfiguration der PostNAS-Suche")
        self.confAction.triggered.connect(self.showConf)

        if hasattr(self.iface, "addPluginToDatabaseMenu"):
            self.iface.addPluginToDatabaseMenu("&PostNAS-Suche", self.confAction)
        else:
            self.iface.addPluginToMenu("&PostNAS-Suche", self.confAction)

        self.toggleSearchAction = QAction(u"Flurstücksuche", self.iface.mainWindow())
        self.toggleSearchAction.setWhatsThis(u"Starten/Schliessen der Flurstücksuche")
        self.toggleSearchAction.setStatusTip(u"Starten/Schliessen der Flurstücksuche")
        self.toggleSearchAction.triggered.connect(self.toggleWidget)

        if hasattr(self.iface, "addPluginToDatabaseMenu"):
            self.iface.addPluginToDatabaseMenu("&PostNAS-Suche", self.toggleSearchAction)
        else:
            self.iface.addPluginToMenu("&PostNAS-Suche", self.toggleSearchAction)

        self.fulltextindex = QAction(u"Volltextindex erstellen", self.iface.mainWindow())
        self.fulltextindex.setWhatsThis(u"Erzeugt einen Volltextindex in der Datenbank um die Suche zu beschleunigen")
        self.fulltextindex.setStatusTip(u"Erzeugt einen Volltextindex in der Datenbank um die Suche zu beschleunigen")
        self.fulltextindex.triggered.connect(self.createFulltextindex)

        if hasattr(self.iface, "addPluginToDatabaseMenu"):
            self.iface.addPluginToDatabaseMenu("&PostNAS-Suche", self.fulltextindex)
        else:
            self.iface.addPluginToMenu("&PostNAS-Suche", self.fulltextindex)

        # Create action that will start plugin configuration
        self.action = QAction(QIcon(":/plugins/PostNAS_Search/search_24x24.png"),u"Flurstücksuche", self.iface.mainWindow())
        self.action.setCheckable(True)
        # connect the action to the run method
        self.action.triggered.connect(self.toggleWidget)

        # Add toolbar button and menu item
        self.iface.addToolBarIcon(self.action)

    def toggleWidget(self, event):
        if self.searchDockWidget == None:
            self.searchDockWidget = QDockWidget(self.iface.mainWindow())
            self.searchDockWidget.setWindowTitle(self.tr(u'Suche'))
            self.searchDockWidget.setWidget(self.dlg)
            self.searchDockWidget.closeEvent = self.toggleWidget
            self.iface.addDockWidget(self.searchDockWidgetArea, self.searchDockWidget)
            self.action.setChecked(True)
        else:
            self.searchDockWidgetArea = self.iface.mainWindow().dockWidgetArea(self.searchDockWidget)
            self.iface.removeDockWidget(self.searchDockWidget)
            self.searchDockWidget = None
            self.action.setChecked(False)

    def showConf(self):
        dlg = PostNAS_ConfDialog(self)
        dlg.exec_()

    def createFulltextindex(self):
        dlg = PostNAS_CreateFulltextindex(self)
        dlg.exec_()

    def unload(self):
        # Remove the Toolbar Icon
        self.iface.removeToolBarIcon(self.action)
        # Remove DockWidget
        if self.searchDockWidget != None:
            self.iface.removeDockWidget(self.searchDockWidget)

        if hasattr(self.iface, "removePluginDatabaseMenu"):
            self.iface.removePluginDatabaseMenu("&PostNAS-Suche", self.confAction)
            self.iface.removePluginDatabaseMenu("&PostNAS-Suche", self.toggleSearchAction)
            self.iface.removePluginDatabaseMenu("&PostNAS-Suche", self.fulltextindex)
        else:
            self.iface.removePluginMenu("&PostNAS-Suche", self.confAction)
            self.iface.removePluginMenu("&PostNAS-Suche", self.toggleSearchAction)
            self.iface.removePluginMenu("&PostNAS-Suche", self.fulltextindex)

        if self.confAction:
            self.confAction.deleteLater()
            self.confAction = None

        if self.toggleSearchAction:
            self.toggleSearchAction.deleteLater()
            self.toggleSearchAction = None

        if self.fulltextindex:
            self.fulltextindex.deleteLater()
            self.fulltextindex = None
Exemplo n.º 44
0
    def __init__(self, iface):
        QMainWindow.__init__(self)
        self.resize(600, 600)
        self.layer = None
        self.iface = iface
        self.dstpoints = []
        self.srcpoints = []
        self.filename = None
        self.cursrc = None
        self.curdst = None
        self.xform_m2r = None
        self.xform_r2m = None

        self.canvas = QgsMapCanvas(self)
        #self.canvas.setCachingEnabled(True)
        self.canvas.setCanvasColor(Qt.white)
        self.canvas.setWheelAction(QgsMapCanvas.WheelZoomToMouseCursor)

        self.setCentralWidget(self.canvas)

        def t(name):
            return QgsApplication.getThemeIcon('/' + name)
        actionZoomIn = QAction(t('mActionZoomIn.svg'), "Zoom in", self)
        actionZoomOut = QAction(t('mActionZoomOut.svg'), "Zoom out", self)
        actionZoomToLayer = QAction(t('mActionZoomToLayer.svg'), "Zoom To Layer", self)
        actionZoomToDest = QAction("Zoom To Map", self)
        actionPan = QAction(t('mActionPan.svg'), "Pan", self)
        actionOpen = QAction(t('mActionFileOpen.svg'), "Open", self)
        actionSave = QAction(t('mActionFileSaveAs.svg'), "Save", self)
        actionAdd = QAction("Add GCP", self)
        actionDeleteAll = QAction("Delete All GCPs", self)

        actionZoomIn.setCheckable(True)
        actionZoomOut.setCheckable(True)
        actionPan.setCheckable(True)
        actionAdd.setCheckable(True)

        actionZoomIn.triggered.connect(self.zoomIn)
        actionZoomOut.triggered.connect(self.zoomOut)
        actionZoomToLayer.triggered.connect(self.zoomToLayer)
        actionZoomToDest.triggered.connect(self.zoomToDest)
        actionPan.triggered.connect(self.pan)
        actionOpen.triggered.connect(self.showOpen)
        actionSave.triggered.connect(self.savePoints)
        actionAdd.triggered.connect(self.addGcp)
        actionDeleteAll.triggered.connect(self.deleteAll)

        self.toolbar = self.addToolBar("Canvas actions")
        self.toolbar.addAction(actionOpen)
        self.toolbar.addAction(actionSave)
        self.toolbar.addSeparator()
        self.toolbar.addAction(actionPan)
        self.toolbar.addAction(actionZoomIn)
        self.toolbar.addAction(actionZoomOut)
        self.toolbar.addAction(actionZoomToLayer)
        self.toolbar.addAction(actionZoomToDest)
        self.toolbar.addSeparator()
        self.toolbar.addAction(actionAdd)
        self.toolbar.addSeparator()
        self.toolbar.addAction(actionDeleteAll)

        self.toolPan = QgsMapToolPan(self.canvas)
        self.toolPan.setAction(actionPan)
        self.toolZoomIn = QgsMapToolZoom(self.canvas, False)
        self.toolZoomIn.setAction(actionZoomIn)
        self.toolZoomOut = QgsMapToolZoom(self.canvas, True)
        self.toolZoomOut.setAction(actionZoomOut)
        self.toolSrcAdd = CaptureTool(self.canvas, self.iface.cadDockWidget())
        self.toolSrcAdd.pointSelected.connect(self.addSrcPoint)
        self.toolSrcAdd.pointDeleted.connect(self.delSrcPoint)
        self.toolDestAdd = CaptureTool(self.iface.mapCanvas(), self.iface.cadDockWidget())
        self.toolDestAdd.pointSelected.connect(self.addDestPoint)
        self.toolDestAdd.pointDeleted.connect(self.delDestPoint)
        #self.toolDestAdd.setAction(actionAdd)

        self.pan()

        self.overview = QgsMapOverviewCanvas(None, self.canvas)
        self.overview_dock = QDockWidget("Overview")
        self.overview_dock.setWidget(self.overview)
        self.addDockWidget(Qt.BottomDockWidgetArea, self.overview_dock)
        self.canvas.enableOverviewMode(self.overview)

        statusbar = self.statusBar()
        self.coordslabel = QLabel(statusbar)
        self.canvas.xyCoordinates.connect(self.showMouseCoordinates)
        statusbar.addPermanentWidget(self.coordslabel)
Exemplo n.º 45
0
    def setupUi(self):
        self.setWindowTitle(self.tr("DB Manager"))
        self.setWindowIcon(QIcon(":/db_manager/icon"))
        self.resize(QSize(700, 500).expandedTo(self.minimumSizeHint()))

        # create central tab widget and add the first 3 tabs: info, table and preview
        self.tabs = QTabWidget()
        self.info = InfoViewer(self)
        self.tabs.addTab(self.info, self.tr("Info"))
        self.table = TableViewer(self)
        self.tabs.addTab(self.table, self.tr("Table"))
        self.preview = LayerPreview(self)
        self.tabs.addTab(self.preview, self.tr("Preview"))
        self.setCentralWidget(self.tabs)

        # display close button for all tabs but the first 3 ones, i.e.
        # HACK: just hide the close button where not needed (GS)
        self.tabs.setTabsClosable(True)
        self.tabs.tabCloseRequested.connect(self.close_tab)
        tabbar = self.tabs.tabBar()
        for i in range(3):
            btn = tabbar.tabButton(i, QTabBar.RightSide) if tabbar.tabButton(i, QTabBar.RightSide) else tabbar.tabButton(i, QTabBar.LeftSide)
            btn.resize(0, 0)
            btn.hide()

        # Creates layout for message bar
        self.layout = QGridLayout(self.info)
        self.layout.setContentsMargins(0, 0, 0, 0)
        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.layout.addItem(spacerItem, 1, 0, 1, 1)
        # init messageBar instance
        self.infoBar = QgsMessageBar(self.info)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.infoBar.setSizePolicy(sizePolicy)
        self.layout.addWidget(self.infoBar, 0, 0, 1, 1)

        # create database tree
        self.dock = QDockWidget("Tree", self)
        self.dock.setObjectName("DB_Manager_DBView")
        self.dock.setFeatures(QDockWidget.DockWidgetMovable)
        self.tree = DBTree(self)
        self.dock.setWidget(self.tree)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dock)

        # create status bar
        self.statusBar = QStatusBar(self)
        self.setStatusBar(self.statusBar)

        # create menus
        self.menuBar = QMenuBar(self)
        self.menuDb = QMenu(self.tr("&Database"), self)
        self.menuBar.addMenu(self.menuDb)
        self.menuSchema = QMenu(self.tr("&Schema"), self)
        actionMenuSchema = self.menuBar.addMenu(self.menuSchema)
        self.menuTable = QMenu(self.tr("&Table"), self)
        actionMenuTable = self.menuBar.addMenu(self.menuTable)
        self.menuHelp = None  # QMenu(self.tr("&Help"), self)
        # actionMenuHelp = self.menuBar.addMenu(self.menuHelp)

        self.setMenuBar(self.menuBar)

        # create toolbar
        self.toolBar = QToolBar("Default", self)
        self.toolBar.setObjectName("DB_Manager_ToolBar")
        self.addToolBar(self.toolBar)

        # create menus' actions

        # menu DATABASE
        sep = self.menuDb.addSeparator()
        sep.setObjectName("DB_Manager_DbMenu_placeholder")
        sep.setVisible(False)

        self.actionRefresh = self.menuDb.addAction(QIcon(":/db_manager/actions/refresh"), self.tr("&Refresh"),
                                                   self.refreshActionSlot, QKeySequence("F5"))
        self.actionSqlWindow = self.menuDb.addAction(QIcon(":/db_manager/actions/sql_window"), self.tr("&SQL window"),
                                                     self.runSqlWindow, QKeySequence("F2"))
        self.menuDb.addSeparator()
        self.actionClose = self.menuDb.addAction(QIcon(), self.tr("&Exit"), self.close, QKeySequence("CTRL+Q"))

        # menu SCHEMA
        sep = self.menuSchema.addSeparator()
        sep.setObjectName("DB_Manager_SchemaMenu_placeholder")
        sep.setVisible(False)

        actionMenuSchema.setVisible(False)

        # menu TABLE
        sep = self.menuTable.addSeparator()
        sep.setObjectName("DB_Manager_TableMenu_placeholder")
        sep.setVisible(False)

        self.actionImport = self.menuTable.addAction(QIcon(":/db_manager/actions/import"),
                                                     self.tr("&Import layer/file"), self.importActionSlot)
        self.actionExport = self.menuTable.addAction(QIcon(":/db_manager/actions/export"), self.tr("&Export to file"),
                                                     self.exportActionSlot)
        self.menuTable.addSeparator()
        #self.actionShowSystemTables = self.menuTable.addAction(self.tr("Show system tables/views"), self.showSystemTables)
        #self.actionShowSystemTables.setCheckable(True)
        #self.actionShowSystemTables.setChecked(True)
        actionMenuTable.setVisible(False)

        # add actions to the toolbar
        self.toolBar.addAction(self.actionRefresh)
        self.toolBar.addAction(self.actionSqlWindow)
        self.toolBar.addAction(self.actionImport)
        self.toolBar.addAction(self.actionExport)
    def __init__(self, iface, version):
        QDockWidget.__init__(self, None)
        self.iface = iface
        self.clouddb = True
        self.version = version
        # Set up the user interface from Designer.
        self.ui = Ui_QgisCloudPlugin()
        self.ui.setupUi(self)
        self.storage_exceeded = True
        
        myAbout = DlgAbout()
        self.ui.aboutText.setText(
            myAbout.aboutString() +
            myAbout.contribString() +
            myAbout.licenseString() +
            "<p>Versions:<ul>" +
            "<li>QGIS: %s</li>" % str(Qgis.QGIS_VERSION).encode("utf-8") +
            "<li>Python: %s</li>" % sys.version.replace("\n", " ") +
            "<li>OS: %s</li>" % platform.platform() +
            "</ul></p>")
            
        data_protection_link = """<a href="http://qgiscloud.com/pages/privacy">%s</a>""" % (self.tr("Privacy Policy"))
            
        self.ui.lblVersionPlugin.setText("%s &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;%s" % (self.version,  data_protection_link))
        self.ui.lblVersionPlugin.setOpenExternalLinks(True)            

        self.ui.tblLocalLayers.setColumnCount(6)
        header = ["Layers","Table Schema","Table name", "Geometry type", "SRID","Data Source"]
        self.ui.tblLocalLayers.setHorizontalHeaderLabels(header)
        self.ui.tblLocalLayers.resizeColumnsToContents()
#        self.ui.tblLocalLayers.setEditTriggers(QAbstractItemView.NoEditTriggers)
        
        self.ui.btnUploadData.setEnabled(False)
        self.ui.btnPublishMap.setEnabled(False)
        self.ui.btnMapDelete.setEnabled(False)
        self.ui.progressWidget.hide()
        self.ui.btnLogout.hide()
        self.ui.lblLoginStatus.hide()
        self.ui.widgetServices.hide()
        self.ui.widgetDatabases.setEnabled(False)
        self.ui.widgetMaps.setEnabled(False)
        self.ui.labelOpenLayersPlugin.hide()

        try:
            from .openlayers_menu import OpenlayersMenu
            self.ui.btnBackgroundLayer.setMenu(OpenlayersMenu(self.iface))
        except:
                self.ui.btnBackgroundLayer.hide()
                self.ui.labelOpenLayersPlugin.show()

        # map<data source, table name>
        self.data_sources_table_names = {}
        # flag to disable update of local data sources during upload
        self.do_update_local_data_sources = True

        self.ui.btnLogin.clicked.connect(self.check_login)
        self.ui.btnDbCreate.clicked.connect(self.create_database)
        self.ui.btnDbDelete.clicked.connect(self.delete_database)
        self.ui.btnDbRefresh.clicked.connect(self.refresh_databases)
        self.ui.btnMapDelete.clicked.connect(self.delete_map)
        self.ui.btnMapLoad.clicked.connect(self.map_load)
        self.ui.tabMaps.itemDoubleClicked.connect(self.map_load)
        self.ui.tabDatabases.itemSelectionChanged.connect(self.select_database)
        self.ui.tabMaps.itemSelectionChanged.connect(self.select_map)
        self.ui.btnPublishMap.clicked.connect(self.publish_map)
        self.ui.btnRefreshLocalLayers.clicked.connect(self.refresh_local_data_sources)
        self.ui.cbUploadDatabase.currentTextChanged.connect(self.update_data_sources_table_names)
        self.iface.newProjectCreated.connect(self.reset_load_data)
        self.iface.projectRead.connect(self.reset_load_data)

        self.PROJECT_INSTANCE.layerWillBeRemoved.connect(self.remove_layer)
        self.PROJECT_INSTANCE.layerWasAdded.connect(self.add_layer)
        
        self.ui.cbUploadDatabase.currentIndexChanged.connect(lambda idx: self.activate_upload_button())
        self.ui.btnUploadData.clicked.connect(self.upload_data)

        self.ui.editServer.textChanged.connect(self.serverURL)
        self.ui.resetUrlBtn.clicked.connect(self.resetApiUrl)

        self.read_settings()
        self.api = API()
        self.db_connections = DbConnections()
        self.local_data_sources = LocalDataSources()
        self.data_upload = DataUpload(
            self.iface, self.statusBar(), self.ui.lblProgress, self.api,
            self.db_connections)

        if self.URL == "":
            self.ui.editServer.setText(self.api.api_url())
        else:
            self.ui.editServer.setText(self.URL)

        self.palette_red = QPalette(self.ui.lblVersionPlugin.palette())
        self.palette_red.setColor(QPalette.WindowText, Qt.red)
Exemplo n.º 47
0
 def activate(self):
     self.activateWindow()
     self.raise_()
     QDockWidget.setFocus(self)
Exemplo n.º 48
0
 def __init__(self, parent):
     QDockWidget.__init__(self, parent)
     self.setWidget(Widget(self))
     self.setWindowTitle("Azimuth and distance")
Exemplo n.º 49
0
class DBManager(QMainWindow):

    def __init__(self, iface, parent=None):
        QMainWindow.__init__(self, parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setupUi()
        self.iface = iface

        # restore the window state
        settings = QgsSettings()
        self.restoreGeometry(settings.value("/DB_Manager/mainWindow/geometry", QByteArray(), type=QByteArray))
        self.restoreState(settings.value("/DB_Manager/mainWindow/windowState", QByteArray(), type=QByteArray))

        self.tabs.currentChanged.connect(self.tabChanged)
        self.tree.selectedItemChanged.connect(self.itemChanged)
        self.itemChanged(None)

    def closeEvent(self, e):
        self.unregisterAllActions()
        # clear preview, this will delete the layer in preview tab
        self.preview.loadPreview(None)

        # save the window state
        settings = QgsSettings()
        settings.setValue("/DB_Manager/mainWindow/windowState", self.saveState())
        settings.setValue("/DB_Manager/mainWindow/geometry", self.saveGeometry())

        QMainWindow.closeEvent(self, e)

    def refreshItem(self, item=None):
        with OverrideCursor(Qt.WaitCursor):
            try:
                if item is None:
                    item = self.tree.currentItem()
                self.tree.refreshItem(item)  # refresh item children in the db tree
            except BaseError as e:
                DlgDbError.showError(e, self)

    def itemChanged(self, item):
        with OverrideCursor(Qt.WaitCursor):
            try:
                self.reloadButtons()
                # clear preview, this will delete the layer in preview tab
                self.preview.loadPreview(None)
                self.refreshTabs()
            except BaseError as e:
                DlgDbError.showError(e, self)

    def reloadButtons(self):
        db = self.tree.currentDatabase()
        if not hasattr(self, '_lastDb'):
            self._lastDb = db

        elif db == self._lastDb:
            return

        # remove old actions
        if self._lastDb is not None:
            self.unregisterAllActions()

        # add actions of the selected database
        self._lastDb = db
        if self._lastDb is not None:
            self._lastDb.registerAllActions(self)

    def tabChanged(self, index):
        with OverrideCursor(Qt.WaitCursor):
            try:
                self.refreshTabs()
            except BaseError as e:
                DlgDbError.showError(e, self)

    def refreshTabs(self):
        index = self.tabs.currentIndex()
        item = self.tree.currentItem()
        table = self.tree.currentTable()

        # enable/disable tabs
        self.tabs.setTabEnabled(self.tabs.indexOf(self.table), table is not None)
        self.tabs.setTabEnabled(self.tabs.indexOf(self.preview), table is not None and table.type in [table.VectorType,
                                                                                                      table.RasterType] and table.geomColumn is not None)
        # show the info tab if the current tab is disabled
        if not self.tabs.isTabEnabled(index):
            self.tabs.setCurrentWidget(self.info)

        current_tab = self.tabs.currentWidget()
        if current_tab == self.info:
            self.info.showInfo(item)
        elif current_tab == self.table:
            self.table.loadData(item)
        elif current_tab == self.preview:
            self.preview.loadPreview(item)

    def refreshActionSlot(self):
        self.info.setDirty()
        self.table.setDirty()
        self.preview.setDirty()
        self.refreshItem()

    def importActionSlot(self):
        db = self.tree.currentDatabase()
        if db is None:
            self.infoBar.pushMessage(self.tr("No database selected or you are not connected to it."),
                                     QgsMessageBar.INFO, self.iface.messageTimeout())
            return

        outUri = db.uri()
        schema = self.tree.currentSchema()
        if schema:
            outUri.setDataSource(schema.name, "", "", "")

        from .dlg_import_vector import DlgImportVector

        dlg = DlgImportVector(None, db, outUri, self)
        dlg.exec_()

    def exportActionSlot(self):
        table = self.tree.currentTable()
        if table is None:
            self.infoBar.pushMessage(self.tr("Select the table you want export to file."), QgsMessageBar.INFO,
                                     self.iface.messageTimeout())
            return

        inLayer = table.toMapLayer()
        if inLayer.type() != QgsMapLayer.VectorLayer:
            self.infoBar.pushMessage(
                self.tr("Select a vector or a tabular layer you want export."),
                QgsMessageBar.WARNING, self.iface.messageTimeout())
            return

        from .dlg_export_vector import DlgExportVector

        dlg = DlgExportVector(inLayer, table.database(), self)
        dlg.exec_()

        inLayer.deleteLater()

    def runSqlWindow(self):
        db = self.tree.currentDatabase()
        if db is None:
            self.infoBar.pushMessage(self.tr("No database selected or you are not connected to it."),
                                     QgsMessageBar.INFO, self.iface.messageTimeout())
            # force displaying of the message, it appears on the first tab (i.e. Info)
            self.tabs.setCurrentIndex(0)
            return

        from .dlg_sql_window import DlgSqlWindow

        query = DlgSqlWindow(self.iface, db, self)
        dbname = db.connection().connectionName()
        tabname = self.tr("Query ({0})").format(dbname)
        index = self.tabs.addTab(query, tabname)
        self.tabs.setTabIcon(index, db.connection().icon())
        self.tabs.setCurrentIndex(index)
        query.nameChanged.connect(functools.partial(self.update_query_tab_name, index, dbname))

    def runSqlLayerWindow(self, layer):
        from .dlg_sql_layer_window import DlgSqlLayerWindow
        query = DlgSqlLayerWindow(self.iface, layer, self)
        lname = layer.name()
        tabname = self.tr("Layer ({0})").format(lname)
        index = self.tabs.addTab(query, tabname)
        # self.tabs.setTabIcon(index, db.connection().icon())
        self.tabs.setCurrentIndex(index)

    def update_query_tab_name(self, index, dbname, queryname):
        if not queryname:
            queryname = self.tr("Query")
        tabname = u"%s (%s)" % (queryname, dbname)
        self.tabs.setTabText(index, tabname)

    def showSystemTables(self):
        self.tree.showSystemTables(self.actionShowSystemTables.isChecked())

    def registerAction(self, action, menuName, callback=None):
        """ register an action to the manager's main menu """
        if not hasattr(self, '_registeredDbActions'):
            self._registeredDbActions = {}

        if callback is not None:
            def invoke_callback(x):
                return self.invokeCallback(callback)

        if menuName is None or menuName == "":
            self.addAction(action)

            if menuName not in self._registeredDbActions:
                self._registeredDbActions[menuName] = list()
            self._registeredDbActions[menuName].append(action)

            if callback is not None:
                action.triggered.connect(invoke_callback)
            return True

        # search for the menu
        actionMenu = None
        helpMenuAction = None
        for a in self.menuBar.actions():
            if not a.menu() or a.menu().title() != menuName:
                continue
            if a.menu() != self.menuHelp:
                helpMenuAction = a

            actionMenu = a
            break

        # not found, add a new menu before the help menu
        if actionMenu is None:
            menu = QMenu(menuName, self)
            if helpMenuAction is not None:
                actionMenu = self.menuBar.insertMenu(helpMenuAction, menu)
            else:
                actionMenu = self.menuBar.addMenu(menu)

        menu = actionMenu.menu()
        menuActions = menu.actions()

        # get the placeholder's position to insert before it
        pos = 0
        for pos in range(len(menuActions)):
            if menuActions[pos].isSeparator() and menuActions[pos].objectName().endswith("_placeholder"):
                menuActions[pos].setVisible(True)
                break

        if pos < len(menuActions):
            before = menuActions[pos]
            menu.insertAction(before, action)
        else:
            menu.addAction(action)

        actionMenu.setVisible(True)  # show the menu

        if menuName not in self._registeredDbActions:
            self._registeredDbActions[menuName] = list()
        self._registeredDbActions[menuName].append(action)

        if callback is not None:
            action.triggered.connect(invoke_callback)

        return True

    def invokeCallback(self, callback, *params):
        """ Call a method passing the selected item in the database tree,
                the sender (usually a QAction), the plugin mainWindow and
                optionally additional parameters.

                This method takes care to override and restore the cursor,
                but also catches exceptions and displays the error dialog.
        """
        with OverrideCursor(Qt.WaitCursor):
            try:
                callback(self.tree.currentItem(), self.sender(), self, *params)
            except BaseError as e:
                # catch database errors and display the error dialog
                DlgDbError.showError(e, self)

    def unregisterAction(self, action, menuName):
        if not hasattr(self, '_registeredDbActions'):
            return

        if menuName is None or menuName == "":
            self.removeAction(action)

            if menuName in self._registeredDbActions:
                if self._registeredDbActions[menuName].count(action) > 0:
                    self._registeredDbActions[menuName].remove(action)

            action.deleteLater()
            return True

        for a in self.menuBar.actions():
            if not a.menu() or a.menu().title() != menuName:
                continue

            menu = a.menu()
            menuActions = menu.actions()

            menu.removeAction(action)
            if menu.isEmpty():  # hide the menu
                a.setVisible(False)

            if menuName in self._registeredDbActions:
                if self._registeredDbActions[menuName].count(action) > 0:
                    self._registeredDbActions[menuName].remove(action)

                # hide the placeholder if there're no other registered actions
                if len(self._registeredDbActions[menuName]) <= 0:
                    for i in range(len(menuActions)):
                        if menuActions[i].isSeparator() and menuActions[i].objectName().endswith("_placeholder"):
                            menuActions[i].setVisible(False)
                            break

            action.deleteLater()
            return True

        return False

    def unregisterAllActions(self):
        if not hasattr(self, '_registeredDbActions'):
            return

        for menuName in self._registeredDbActions:
            for action in list(self._registeredDbActions[menuName]):
                self.unregisterAction(action, menuName)
        del self._registeredDbActions

    def close_tab(self, index):
        widget = self.tabs.widget(index)
        if widget not in [self.info, self.table, self.preview]:
            self.tabs.removeTab(index)
            widget.deleteLater()

    def setupUi(self):
        self.setWindowTitle(self.tr("DB Manager"))
        self.setWindowIcon(QIcon(":/db_manager/icon"))
        self.resize(QSize(700, 500).expandedTo(self.minimumSizeHint()))

        # create central tab widget and add the first 3 tabs: info, table and preview
        self.tabs = QTabWidget()
        self.info = InfoViewer(self)
        self.tabs.addTab(self.info, self.tr("Info"))
        self.table = TableViewer(self)
        self.tabs.addTab(self.table, self.tr("Table"))
        self.preview = LayerPreview(self)
        self.tabs.addTab(self.preview, self.tr("Preview"))
        self.setCentralWidget(self.tabs)

        # display close button for all tabs but the first 3 ones, i.e.
        # HACK: just hide the close button where not needed (GS)
        self.tabs.setTabsClosable(True)
        self.tabs.tabCloseRequested.connect(self.close_tab)
        tabbar = self.tabs.tabBar()
        for i in range(3):
            btn = tabbar.tabButton(i, QTabBar.RightSide) if tabbar.tabButton(i, QTabBar.RightSide) else tabbar.tabButton(i, QTabBar.LeftSide)
            btn.resize(0, 0)
            btn.hide()

        # Creates layout for message bar
        self.layout = QGridLayout(self.info)
        self.layout.setContentsMargins(0, 0, 0, 0)
        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum, QSizePolicy.Expanding)
        self.layout.addItem(spacerItem, 1, 0, 1, 1)
        # init messageBar instance
        self.infoBar = QgsMessageBar(self.info)
        sizePolicy = QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Fixed)
        self.infoBar.setSizePolicy(sizePolicy)
        self.layout.addWidget(self.infoBar, 0, 0, 1, 1)

        # create database tree
        self.dock = QDockWidget("Tree", self)
        self.dock.setObjectName("DB_Manager_DBView")
        self.dock.setFeatures(QDockWidget.DockWidgetMovable)
        self.tree = DBTree(self)
        self.dock.setWidget(self.tree)
        self.addDockWidget(Qt.LeftDockWidgetArea, self.dock)

        # create status bar
        self.statusBar = QStatusBar(self)
        self.setStatusBar(self.statusBar)

        # create menus
        self.menuBar = QMenuBar(self)
        self.menuDb = QMenu(self.tr("&Database"), self)
        self.menuBar.addMenu(self.menuDb)
        self.menuSchema = QMenu(self.tr("&Schema"), self)
        actionMenuSchema = self.menuBar.addMenu(self.menuSchema)
        self.menuTable = QMenu(self.tr("&Table"), self)
        actionMenuTable = self.menuBar.addMenu(self.menuTable)
        self.menuHelp = None  # QMenu(self.tr("&Help"), self)
        # actionMenuHelp = self.menuBar.addMenu(self.menuHelp)

        self.setMenuBar(self.menuBar)

        # create toolbar
        self.toolBar = QToolBar("Default", self)
        self.toolBar.setObjectName("DB_Manager_ToolBar")
        self.addToolBar(self.toolBar)

        # create menus' actions

        # menu DATABASE
        sep = self.menuDb.addSeparator()
        sep.setObjectName("DB_Manager_DbMenu_placeholder")
        sep.setVisible(False)

        self.actionRefresh = self.menuDb.addAction(QIcon(":/db_manager/actions/refresh"), self.tr("&Refresh"),
                                                   self.refreshActionSlot, QKeySequence("F5"))
        self.actionSqlWindow = self.menuDb.addAction(QIcon(":/db_manager/actions/sql_window"), self.tr("&SQL window"),
                                                     self.runSqlWindow, QKeySequence("F2"))
        self.menuDb.addSeparator()
        self.actionClose = self.menuDb.addAction(QIcon(), self.tr("&Exit"), self.close, QKeySequence("CTRL+Q"))

        # menu SCHEMA
        sep = self.menuSchema.addSeparator()
        sep.setObjectName("DB_Manager_SchemaMenu_placeholder")
        sep.setVisible(False)

        actionMenuSchema.setVisible(False)

        # menu TABLE
        sep = self.menuTable.addSeparator()
        sep.setObjectName("DB_Manager_TableMenu_placeholder")
        sep.setVisible(False)

        self.actionImport = self.menuTable.addAction(QIcon(":/db_manager/actions/import"),
                                                     self.tr("&Import layer/file"), self.importActionSlot)
        self.actionExport = self.menuTable.addAction(QIcon(":/db_manager/actions/export"), self.tr("&Export to file"),
                                                     self.exportActionSlot)
        self.menuTable.addSeparator()
        #self.actionShowSystemTables = self.menuTable.addAction(self.tr("Show system tables/views"), self.showSystemTables)
        #self.actionShowSystemTables.setCheckable(True)
        #self.actionShowSystemTables.setChecked(True)
        actionMenuTable.setVisible(False)

        # add actions to the toolbar
        self.toolBar.addAction(self.actionRefresh)
        self.toolBar.addAction(self.actionSqlWindow)
        self.toolBar.addAction(self.actionImport)
        self.toolBar.addAction(self.actionExport)
Exemplo n.º 50
0
class MainWindow(QMainWindow):
    def __init__(self, iface):
        QMainWindow.__init__(self)
        self.resize(600, 600)
        self.layer = None
        self.iface = iface
        self.dstpoints = []
        self.srcpoints = []
        self.filename = None
        self.cursrc = None
        self.curdst = None
        self.xform_m2r = None
        self.xform_r2m = None

        self.canvas = QgsMapCanvas(self)
        #self.canvas.setCachingEnabled(True)
        self.canvas.setCanvasColor(Qt.white)
        self.canvas.setWheelAction(QgsMapCanvas.WheelZoomToMouseCursor)

        self.setCentralWidget(self.canvas)

        def t(name):
            return QgsApplication.getThemeIcon('/' + name)
        actionZoomIn = QAction(t('mActionZoomIn.svg'), "Zoom in", self)
        actionZoomOut = QAction(t('mActionZoomOut.svg'), "Zoom out", self)
        actionZoomToLayer = QAction(t('mActionZoomToLayer.svg'), "Zoom To Layer", self)
        actionZoomToDest = QAction("Zoom To Map", self)
        actionPan = QAction(t('mActionPan.svg'), "Pan", self)
        actionOpen = QAction(t('mActionFileOpen.svg'), "Open", self)
        actionSave = QAction(t('mActionFileSaveAs.svg'), "Save", self)
        actionAdd = QAction("Add GCP", self)
        actionDeleteAll = QAction("Delete All GCPs", self)

        actionZoomIn.setCheckable(True)
        actionZoomOut.setCheckable(True)
        actionPan.setCheckable(True)
        actionAdd.setCheckable(True)

        actionZoomIn.triggered.connect(self.zoomIn)
        actionZoomOut.triggered.connect(self.zoomOut)
        actionZoomToLayer.triggered.connect(self.zoomToLayer)
        actionZoomToDest.triggered.connect(self.zoomToDest)
        actionPan.triggered.connect(self.pan)
        actionOpen.triggered.connect(self.showOpen)
        actionSave.triggered.connect(self.savePoints)
        actionAdd.triggered.connect(self.addGcp)
        actionDeleteAll.triggered.connect(self.deleteAll)

        self.toolbar = self.addToolBar("Canvas actions")
        self.toolbar.addAction(actionOpen)
        self.toolbar.addAction(actionSave)
        self.toolbar.addSeparator()
        self.toolbar.addAction(actionPan)
        self.toolbar.addAction(actionZoomIn)
        self.toolbar.addAction(actionZoomOut)
        self.toolbar.addAction(actionZoomToLayer)
        self.toolbar.addAction(actionZoomToDest)
        self.toolbar.addSeparator()
        self.toolbar.addAction(actionAdd)
        self.toolbar.addSeparator()
        self.toolbar.addAction(actionDeleteAll)

        self.toolPan = QgsMapToolPan(self.canvas)
        self.toolPan.setAction(actionPan)
        self.toolZoomIn = QgsMapToolZoom(self.canvas, False)
        self.toolZoomIn.setAction(actionZoomIn)
        self.toolZoomOut = QgsMapToolZoom(self.canvas, True)
        self.toolZoomOut.setAction(actionZoomOut)
        self.toolSrcAdd = CaptureTool(self.canvas, self.iface.cadDockWidget())
        self.toolSrcAdd.pointSelected.connect(self.addSrcPoint)
        self.toolSrcAdd.pointDeleted.connect(self.delSrcPoint)
        self.toolDestAdd = CaptureTool(self.iface.mapCanvas(), self.iface.cadDockWidget())
        self.toolDestAdd.pointSelected.connect(self.addDestPoint)
        self.toolDestAdd.pointDeleted.connect(self.delDestPoint)
        #self.toolDestAdd.setAction(actionAdd)

        self.pan()

        self.overview = QgsMapOverviewCanvas(None, self.canvas)
        self.overview_dock = QDockWidget("Overview")
        self.overview_dock.setWidget(self.overview)
        self.addDockWidget(Qt.BottomDockWidgetArea, self.overview_dock)
        self.canvas.enableOverviewMode(self.overview)

        statusbar = self.statusBar()
        self.coordslabel = QLabel(statusbar)
        self.canvas.xyCoordinates.connect(self.showMouseCoordinates)
        statusbar.addPermanentWidget(self.coordslabel)

    def __del__(self):
        for x in self.dstpoints:
            self.iface.mapCanvas().scene().removeItem(x)

    def zoomIn(self):
        self.canvas.setMapTool(self.toolZoomIn)

    def zoomOut(self):
        self.canvas.setMapTool(self.toolZoomOut)

    def addGcp(self):
        self.canvas.setMapTool(self.toolSrcAdd)
        self.iface.mapCanvas().setMapTool(self.toolDestAdd)

    def addDestPoint(self, pt):
        if self.curdst:
            self.curdst.setPoint(pt)
        else:
            self.curdst = CanvasItem(self.iface.mapCanvas(), pt)
        self.curdst.setCompleted(False)
        self.registerPoint()

    def addSrcPoint(self, pt):
        if self.cursrc:
            self.cursrc.setPoint(pt)
        else:
            self.cursrc = CanvasItem(self.canvas, pt)
        self.cursrc.setCompleted(False)
        self.registerPoint()

    def delDestPoint(self, pt):
        idx = self.dstpoints.index(pt)
        self.iface.mapCanvas().scene().removeItem(self.dstpoints[idx])
        del self.dstpoints[idx]
        self.canvas.scene().removeItem(self.srcpoints[idx])
        del self.srcpoints[idx]

    def delSrcPoint(self, pt):
        idx = self.srcpoints.index(pt)
        self.iface.mapCanvas().scene().removeItem(self.dstpoints[idx])
        del self.dstpoints[idx]
        self.canvas.scene().removeItem(self.srcpoints[idx])
        del self.srcpoints[idx]

    def registerPoint(self):
        if not self.cursrc or not self.curdst:
            return

        self.cursrc.setCompleted(True)
        self.cursrc.setDirty(True)
        self.curdst.setCompleted(True)
        self.curdst.setDirty(True)
        self.srcpoints.append(self.cursrc)
        self.dstpoints.append(self.curdst)
        self.cursrc = None
        self.curdst = None

    def deleteAll(self):
        for x in self.dstpoints:
            self.iface.mapCanvas().scene().removeItem(x)
        for x in self.srcpoints:
            self.canvas.scene().removeItem(x)
        self.dstpoints = []
        self.srcpoints = []

    def zoomToLayer(self):
        if self.layer:
            self.canvas.setExtent(self.layer.extent())
            self.canvas.refresh()

    def zoomToDest(self):
        pts = [x.pt for x in self.dstpoints]
        if len(pts) < 2:
            return
        r = QgsRectangle(pts[0], pts[1])
        for pt in pts[2:]:
            r.include(pt)

        self.iface.mapCanvas().setExtent(r)
        self.iface.mapCanvas().refresh()

    def pan(self):
        self.canvas.setMapTool(self.toolPan)

    def showOpen(self):
        startdir = '.'
        filters = QgsProviderRegistry.instance().fileRasterFilters()
        lastFilter = "Multi-resolution Seamless Image Database (*.sid *.SID)"

        dlg = QFileDialog(self)
        dlg.setWindowTitle("Open raster")
        dlg.setFileMode(QFileDialog.ExistingFile)
        dlg.setNameFilter(filters)
        dlg.selectNameFilter(lastFilter)
        dlg.fileSelected.connect(self.openFile)
        dlg.show()

    def openFile(self, filename):
        if not filename:
            return

        if self.layer:
            QgsMapLayerRegistry.instance().removeMapLayers([self.layer.id()])

        self.deleteAll()
        self.setWindowTitle(os.path.basename(filename))
        self.filename = filename
        with CrsDialogSuspender():
            self.layer = QgsRasterLayer(filename, "Raster")
        QgsMapLayerRegistry.instance().addMapLayers([self.layer], False)
        self.canvas.setLayerSet([QgsMapCanvasLayer(self.layer, True, True)])
        self.canvas.setExtent(self.layer.extent())

        # figure out source file transform
        ds = gdal.Open(filename)
        xform = ds.GetGeoTransform(True)
        if not xform:
            # qgis inverts y when the transform does not exist
            xform = [0.0, 1.0, 0.0, 0.0, 0.0, -1.0]

        self.xform_r2m = xform
        invxform = gdal.InvGeoTransform(xform)
        if len(invxform) == 2:
            invxform = invxform[1]
        self.xform_m2r = invxform

        # load points
        gcp_filename = filename + ".gcps"
        if os.path.exists(gcp_filename):
            self.loadPoints(gcp_filename)

        self.zoomToLayer()

    def map2raster(self, x, y):
        return gdal.ApplyGeoTransform(self.xform_m2r, x, y)
    def raster2map(self, x, y):
        return gdal.ApplyGeoTransform(self.xform_r2m, x, y)

    def loadPoints(self, filename):
        self.srcpoints = []
        self.dstpoints = []
        for line in open(filename, 'rt').readlines():
            line.strip()
            if line.startswith('map'):
                continue

            parts = line.split(',')
            if len(parts) < 4:
                continue

            dstpt = QgsPoint(float(parts[0]), float(parts[1]))

            oldsrcx, oldsrcy = float(parts[2]), float(parts[3])
            newsrcx, newsrcy = self.raster2map(oldsrcx, oldsrcy)
            srcpt = QgsPoint(newsrcx, newsrcy)

            self.srcpoints.append(CanvasItem(self.canvas, srcpt))
            self.dstpoints.append(CanvasItem(self.iface.mapCanvas(), dstpt))

    def savePoints(self):
        if not self.filename:
            return
        filename = self.filename + ".gcps"
        out = open(filename, "wt")
        out.write("mapX,mapY,pixelX,pixelY\n")
        for i in range(len(self.srcpoints)):
            self.dstpoints[i].setDirty(False)
            self.srcpoints[i].setDirty(False)
            dstpt = self.dstpoints[i].pt
            srcpt = self.srcpoints[i].pt

            newsrcx, newsrcy = self.map2raster(srcpt.x(), srcpt.y())

            outpts = [dstpt.x(), dstpt.y(), newsrcx, newsrcy]
            out.write("%s,%s,%s,%s\n" % tuple([qgsDoubleToString(x) for x in outpts]))

    def showMouseCoordinates(self, coords):
        self.coordslabel.setText("Coords: %f, %f" % (coords.x(), coords.y()))