예제 #1
0
    def __init__(self, shapefile):
        QtGui.QMainWindow.__init__(self)
        self.setWindowTitle("Map Viewer")

        canvas = qgisGui.QgsMapCanvas()
        canvas.useImageToRender(False)
        canvas.setCanvasColor(QtCore.Qt.white)
        canvas.show()

        layer = qgisCore.QgsVectorLayer(shapefile, "layer1", "ogr")
        if not layer.isValid():
            raise IOError("Invalid shapefile")

        qgisCore.QgsMapLayerRegistry.instance().addMapLayer(layer)
        canvas.setExtent(layer.extent())
        canvas.setLayerSet([qgisGui.QgsMapCanvasLayer(layer)])

        layout = QtGui.QVBoxLayout()
        layout.addWidget(canvas)

        contents = QtGui.QWidget()
        contents.setLayout(layout)
        self.setCentralWidget(contents)
예제 #2
0

if __name__ == "__main__":

    from qgis.core.contextmanagers import qgisapp
    import qgis.PyQt.QtWidgets as qtWdg
    import qgis.gui as qgGui

    from moduls.QvLlegenda import QvLlegenda
    from moduls.QvAtributs import QvAtributs

    with qgisapp(sysexit=False) as app:

        QvApp().carregaIdioma(app, 'ca')

        canv = qgGui.QgsMapCanvas()

        atrib = QvAtributs(canv)

        leyenda = QvLlegenda(canv, atrib)

        leyenda.project.read('D:/qVista/EjemploSimbolos.qgs')

        canv.setWindowTitle('Canvas')
        canv.show()

        leyenda.setWindowTitle('Llegenda')
        leyenda.show()

        # Acciones personalizadas para menú contextual de la leyenda:
        #
    def __init__(self, parent, boundingbox):
        super(ExtentDialog, self).__init__(parent)
        self.setupUi(self)
        self.superParent = None
        temp = self.parent()
        if platform.system() != "Linux":
            font = QFont()
            font.setFamily(u"Segoe UI Symbol")
            self.setFont(font)
        while self.superParent is None:
            if issubclass(type(temp),
                          geographicinformationPanel.Ui_geographicinfo):
                self.superParent = temp
            else:
                temp = temp.parent()
        for info in self.findChildren(qwidgets.QPushButton,
                                      qcore.QRegExp('info_*')):
            info.setIcon(qgui.QIcon(':/resourcesFolder/icons/help_icon.svg'))
            info.setText('')
            info.pressed.connect(self.printHelp)

        self.layers = []
        self.maxExt = None
        self.boundingbox = boundingbox
        self.outBB = False

        # Create MapCanvas
        self.canvas = gui.QgsMapCanvas(self)

        # Append to Dialog Layout
        self.toolBar = qwidgets.QToolBar()
        self.layout = qwidgets.QVBoxLayout(self.frame)
        self.layout.addWidget(self.toolBar)
        self.layout.addWidget(self.canvas)

        # Trigger on scaleChanged
        self.canvas.scaleChanged.connect(self.scaleChanged)
        # Trigger on renderStarting
        self.canvas.renderStarting.connect(self.renderStarting)

        # Create Map Tools
        actionFullExt = qwidgets.QAction(
            qgui.QIcon(':/resourcesFolder/icons/globe.svg'), "Mapa total",
            self)
        actionPan = qwidgets.QAction(
            qgui.QIcon(':/resourcesFolder/icons/pan.svg'), "Mover", self)
        actionZoomIn = qwidgets.QAction(
            qgui.QIcon(':/resourcesFolder/icons/zoom_in.svg'), "Aproximar",
            self)
        actionZoomOut = qwidgets.QAction(
            qgui.QIcon(':/resourcesFolder/icons/zoom_out.svg'), "Afastar",
            self)
        actionSelect = qwidgets.QAction(
            qgui.QIcon(':/resourcesFolder/icons/selection.svg'), 'Desenhar',
            self)
        actionFromLayer = qwidgets.QAction(
            qgui.QIcon(':/resourcesFolder/icons/layers.svg'),
            'Obter de camada', self)

        actionFullExt.setCheckable(False)
        actionPan.setCheckable(True)
        actionZoomIn.setCheckable(True)
        actionZoomOut.setCheckable(True)
        actionSelect.setCheckable(True)

        actionFullExt.triggered.connect(self.fullext)
        actionPan.triggered.connect(self.pan)
        actionZoomIn.triggered.connect(self.zoomIn)
        actionZoomOut.triggered.connect(self.zoomOut)
        actionSelect.triggered.connect(self.select)
        actionFromLayer.triggered.connect(self.chooseLayer)

        # Add to created ToolBar
        self.toolBar.addAction(actionFullExt)
        self.toolBar.addSeparator()
        self.toolBar.addAction(actionPan)
        self.toolBar.addAction(actionZoomIn)
        self.toolBar.addAction(actionZoomOut)
        self.toolBar.addAction(actionSelect)
        self.toolBar.addAction(actionFromLayer)

        self.toolFullExtent = gui.QgsMapToolPan(self.canvas)
        self.toolFullExtent.setAction(actionFullExt)
        self.toolPan = gui.QgsMapToolPan(self.canvas)
        self.toolPan.setAction(actionPan)
        self.toolZoomIn = gui.QgsMapToolZoom(self.canvas, False)  # false = in
        self.toolZoomIn.setAction(actionZoomIn)
        self.toolZoomOut = gui.QgsMapToolZoom(self.canvas, True)  # true = out
        self.toolZoomOut.setAction(actionZoomOut)
        self.toolSelect = SelectionTool(self.canvas, self)
        self.resourcebox.setChecked(True)
        self.pan()

        lugin_path = utils.pluginDirectory('EditorMetadadosMarswInforbiomares')

        # Load Vector
        layerpath = os.path.join(plugin_path, "resourcesFolder/World.shp")
        llayer = core.QgsVectorLayer(layerpath, "WorldLayer", "ogr")

        # Set Layer Symbology
        props = {
            'color_border': '0,0,0,125',
            'style': 'no',
            'style_border': 'solid'
        }
        #s = core.QgsFillSymbolV2.createSimple(props)
        s = core.QgsFillSymbol.createSimple(props)
        #llayer.setRendererV2(core.QgsSingleSymbolRendererV2(s))
        llayer.setRenderer(core.QgsSingleSymbolRenderer(s))

        # Set CRS - necessary to load Raster - it assumes this default CRS
        s = qcore.QSettings()
        oldValidation = str(
            s.value("/Projections/defaultBehaviour", "useGlobal"))
        s.setValue("/Projections/defaultBehaviour", "useGlobal")

        # Load Raster
        fileName = os.path.join(plugin_path, "resourcesFolder/GMRT.tif")
        fileInfo = qcore.QFileInfo(fileName)
        baseName = fileInfo.baseName()
        layer = core.QgsRasterLayer(fileName, baseName)
        layer.setCrs(
            core.QgsCoordinateReferenceSystem(
                4326, core.QgsCoordinateReferenceSystem.EpsgCrsId))
        s.setValue("/Projections/defaultBehaviour", oldValidation)

        # Set Raster ColorRamp
        # layer.setDrawingStyle("SingleBandPseudoColor") # deprecated remove in 2.1.0 please
        vmin = -5683.08
        vmax = 2763.86
        vrange = vmax - vmin
        vadd = vrange // 2
        vint = vmin + vadd
        colDic = {
            'brown': '#90330a',
            'lightblue': '#d5f5f9',
            'blue': '#2099d4'
        }
        valueList = [vmin, vint, vmax]

        lst = [core.QgsColorRampShader.ColorRampItem(valueList[0], qgui.QColor(colDic['blue'])), \
               core.QgsColorRampShader.ColorRampItem(valueList[1],
                                                     qgui.QColor(colDic['lightblue'])), \
               core.QgsColorRampShader.ColorRampItem(valueList[2], qgui.QColor(colDic['brown']))]
        myRasterShader = core.QgsRasterShader()
        myColorRamp = core.QgsColorRampShader()
        myColorRamp.setColorRampItemList(lst)
        myColorRamp.setColorRampType(core.QgsColorRampShader.Interpolated)
        myRasterShader.setRasterShaderFunction(myColorRamp)
        myPseudoRenderer = core.QgsSingleBandPseudoColorRenderer(
            layer.dataProvider(), layer.type(), myRasterShader)
        layer.setRenderer(myPseudoRenderer)

        ## Add vector to map
        #core.QgsMapLayerRegistry.instance().addMapLayer(llayer, False)
        core.QgsProject.instance().addMapLayer(llayer, False)
        ## Add raster to map
        #core.QgsMapLayerRegistry.instance().addMapLayer(layer, False)
        core.QgsProject.instance().addMapLayer(layer, False)

        ## Save Max Extent
        self.maxExt = core.QgsRectangle(-180., -90., 180., 90.)

        # ----------------------------------
        ## Set initial general extent to ZEE or, if one is selected, from the selected boundingbox
        if self.boundingbox.selectionModel().hasSelection() == False:
            ## Change button's title
            self.add_extent.setText(u"Adicionar")
            initialrect = core.QgsRectangle(-46.63064, 22.52146, 9.64473,
                                            47.31826)
        else:
            ## Get selected bounding box coords and resource flag
            index = self.boundingbox.selectionModel().selectedRows()[0].row()
            row = self.boundingbox.model().matrix[index]

            minx = float(row[0].replace(',', '.'))
            miny = float(row[3].replace(',', '.'))
            maxx = float(row[1].replace(',', '.'))
            maxy = float(row[2].replace(',', '.'))

            if minx == 0. and miny == 0. and maxx == 0. and maxy == 0.:
                initialrect = core.QgsRectangle(-46.63064, 22.52146, 9.64473,
                                                47.31826)
            else:
                ## Set fields with these values
                self.xMin.setValue(minx)
                self.xMax.setValue(maxx)
                self.yMin.setValue(miny)
                self.yMax.setValue(maxy)
                self.resourcebox.setChecked(bool(row[4]))

                ## Set the extent and add a bit of zoom out of the selected extent
                initialrect = core.QgsRectangle(minx - minx * 0.1,
                                                miny - miny * 0.1,
                                                maxx + maxx * 0.1,
                                                maxy + maxy * 0.1)

                ## Draw initial extent on the map
                self.toolSelect.drawRect(minx, miny, maxx, maxy)

                ## Change button's title
                self.add_extent.setText(u"Alterar")

        self.canvas.setExtent(initialrect)
        # ----------------------------------

        ## Append layers to MapCanvas
        self.layers.append(llayer)
        self.layers.append(layer)
        #self.layers.append(gui.QgsMapCanvasLayer(llayer))
        #self.layers.append(gui.QgsMapCanvasLayer(layer))
        #self.canvas.setLayerSet(self.layers)
        self.canvas.setLayers([llayer, layer])

        ## Set triggers to buttons
        self.add_extent.clicked.connect(self.add_new_extent)
        self.btn_close.clicked.connect(lambda: self.done(QDialog.Rejected))
        self.finished.connect(self.cleanup)

        ## Disabled coord fields
        self.xMin.setEnabled(False)
        self.xMax.setEnabled(False)
        self.yMin.setEnabled(False)
        self.yMax.setEnabled(False)
예제 #4
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from PyQt4 import QtGui, QtCore
import sys, os
from qgis import core, gui

core.QgsApplication.setPrefixPath('/usr', True)
core.QgsApplication.initQgis()

l = core.QgsVectorLayer(sys.argv[1], os.path.basename(sys.argv[1]), 'ogr')
app = QtGui.QApplication(sys.argv)
canvas = gui.QgsMapCanvas()
canvas.resize(800, 600)
core.QgsMapLayerRegistry.instance().addMapLayer(l)
canvas.setExtent(l.extent())
cl = gui.QgsMapCanvasLayer(l)
layers = [cl]
canvas.setLayerSet(layers)
canvas.show()
retval = app.exec_()
core.QgsApplication.exitQgis()
sys.exit(retval)