def close_project(self, project=None):
        """
        Close the current open project
        """
        if not project is None and not project == self.project:
            return

        self.tracking.clear_logging()
        self.dataentrywidget.clear()
        self.canvas_page.cleanup()
        QgsMapLayerRegistry.instance().removeAllMapLayers()
        for panel in self.panels:
            self.removeDockWidget(panel)
            del panel
            # Remove all the old buttons

        self.panels = []
        oldproject = self.project
        self.project = None
        self.set_projectbuttons(False)
        self.hidedataentry()
        self.infodock.close()
        RoamEvents.selectioncleared.emit()
        RoamEvents.projectClosed.emit(oldproject)
        self.projectwidget.set_open_project(None)
    def __init__(self, methodName):
        """Run once on class initialisation."""
        unittest.TestCase.__init__(self, methodName)
        myPath = os.path.join(TEST_DATA_DIR, 'landsat.tif')
        rasterFileInfo = QFileInfo(myPath)
        mRasterLayer = QgsRasterLayer(rasterFileInfo.filePath(),
                                      rasterFileInfo.completeBaseName())
        rasterRenderer = QgsMultiBandColorRenderer(
            mRasterLayer.dataProvider(), 2, 3, 4)
        mRasterLayer.setRenderer(rasterRenderer)
        #pipe = mRasterLayer.pipe()
        #assert pipe.set(rasterRenderer), 'Cannot set pipe renderer'
        QgsMapLayerRegistry.instance().addMapLayers([mRasterLayer])

        # create composition with composer map
        self.mMapRenderer = QgsMapRenderer()
        layerStringList = QStringList()
        layerStringList.append(mRasterLayer.id())
        self.mMapRenderer.setLayerSet(layerStringList)
        self.mMapRenderer.setProjectionsEnabled(False)
        self.mComposition = QgsComposition(self.mMapRenderer)
        self.mComposition.setPaperSize(297, 210)
        self.mComposerMap = QgsComposerMap(self.mComposition, 20, 20, 200, 100)
        self.mComposerMap.setFrameEnabled(True)
        self.mComposition.addComposerMap(self.mComposerMap)
Exemplo n.º 3
0
    def testStringWithMaxLen(self):
        """ tests that text edit wrappers correctly handle string fields with a maximum length """
        layer = QgsVectorLayer("none?field=fldint:integer", "layer", "memory")
        assert layer.isValid()
        layer.dataProvider().addAttributes([QgsField('max', QVariant.String, 'string', 10),
                                            QgsField('nomax', QVariant.String, 'string', 0)])
        layer.updateFields()
        QgsMapLayerRegistry.instance().addMapLayer(layer)

        reg = QgsEditorWidgetRegistry.instance()
        config = {'IsMultiline': 'True'}

        # first test for field without character limit
        editor = QTextEdit()
        editor.setPlainText('this_is_a_long_string')
        w = reg.create('TextEdit', layer, 2, config, editor, None)
        self.assertEqual(w.value(), 'this_is_a_long_string')

        # next test for field with character limit
        editor = QTextEdit()
        editor.setPlainText('this_is_a_long_string')
        w = reg.create('TextEdit', layer, 1, config, editor, None)

        self.assertEqual(w.value(), 'this_is_a_')

        QgsMapLayerRegistry.instance().removeAllMapLayers()
Exemplo n.º 4
0
    def create_layer(self, data):
        display_name = 'some-layer'
        uri = 'Point?crs=epsg:4326&index=yes&uuid=%s' % uuid.uuid4()
        vlayer = QgsVectorLayer(uri, display_name, 'memory')
        QgsMapLayerRegistry.instance().addMapLayer(vlayer)

        provider = vlayer.dataProvider()
        vlayer.startEditing()
        provider.addAttributes([
            QgsField('population_density', QtCore.QVariant.Double),
        ])
        features = []
        for x, y, density in data:
            feat = QgsFeature()
            geom = QgsGeometry.fromPoint(QgsPoint(x, y))
            feat.setGeometry(geom)
            feat.setAttributes([density])
            features.append(feat)
        provider.addFeatures(features)
        vlayer.commitChanges()

        vlayer.updateExtents()
        self.canvas.setExtent(vlayer.extent())
        cl = QgsMapCanvasLayer(vlayer)
        self.canvas.setLayerSet([cl])
        vlayer.triggerRepaint()
Exemplo n.º 5
0
    def test_ValueMap_representValue(self):
        layer = QgsVectorLayer("none?field=number1:integer&field=number2:double&field=text1:string&field=number3:integer&field=number4:double&field=text2:string",
                               "layer", "memory")
        assert layer.isValid()
        QgsMapLayerRegistry.instance().addMapLayer(layer)
        f = QgsFeature()
        f.setAttributes([2, 2.5, 'NULL', None, None, None])
        assert layer.dataProvider().addFeatures([f])
        reg = QgsEditorWidgetRegistry.instance()
        factory = reg.factory("ValueMap")
        self.assertIsNotNone(factory)

        # Tests with different value types occurring in the value map
        config = {'two': '2', 'twoandhalf': '2.5', 'NULL text': 'NULL',
                  'nothing': self.VALUEMAP_NULL_TEXT}
        self.assertEqual(factory.representValue(layer, 0, config, None, 2), 'two')
        self.assertEqual(factory.representValue(layer, 1, config, None, 2.5), 'twoandhalf')
        self.assertEqual(factory.representValue(layer, 2, config, None, 'NULL'), 'NULL text')
        # Tests with null values of different types, if value map contains null
        self.assertEqual(factory.representValue(layer, 3, config, None, None), 'nothing')
        self.assertEqual(factory.representValue(layer, 4, config, None, None), 'nothing')
        self.assertEqual(factory.representValue(layer, 5, config, None, None), 'nothing')
        # Tests with fallback display for different value types
        config = {}
        self.assertEqual(factory.representValue(layer, 0, config, None, 2), '(2)')
        self.assertEqual(factory.representValue(layer, 1, config, None, 2.5), '(2.50000)')
        self.assertEqual(factory.representValue(layer, 2, config, None, 'NULL'), '(NULL)')
        # Tests with fallback display for null in different types of fields
        self.assertEqual(factory.representValue(layer, 3, config, None, None), '(NULL)')
        self.assertEqual(factory.representValue(layer, 4, config, None, None), '(NULL)')
        self.assertEqual(factory.representValue(layer, 5, config, None, None), '(NULL)')

        QgsMapLayerRegistry.instance().removeAllMapLayers()
Exemplo n.º 6
0
def show_qgis_layer(layer):
    """Show a QGIS layer in the map canvas.

    :param layer: The layer to show.
    :type layer: QgsMapLayer
    """
    QgsMapLayerRegistry.instance().addMapLayer(layer)
Exemplo n.º 7
0
 def accept(self):
     input_path = str(self.leInputPath.text())
     output_path = str(self.leOutputPath.text())
     if not output_path.endswith('.tif'):
         QMessageBox.warning(
             self.parent, self.tr('InaSAFE'),
             (self.tr('Output file name must be tif file')))
     if not os.path.exists(input_path):
         QMessageBox.warning(
             self.parent, self.tr('InaSAFE'),
             (self.tr('Input file is not exist')))
         return
     my_algorithm = str(self.cboAlgorithm.currentText()).lower()
     fileName = convert_mmi_data(input_path, output_path,
                                 the_algorithm=my_algorithm,
                                 algorithm_name=False)
     if self.cBLoadLayer.isChecked():
         fileInfo = QFileInfo(fileName)
         baseName = fileInfo.baseName()
         my_raster_layer = QgsRasterLayer(fileName, baseName)
         if not my_raster_layer.isValid():
             LOGGER.debug("Failed to load")
         else:
             QgsMapLayerRegistry.instance().addMapLayer(my_raster_layer)
     self.done(self.Accepted)
     if not self.test_mode:
         QMessageBox.warning(
             self.parent, self.tr('InaSAFE'),
             (self.tr('Success to convert %1 to %2').
              arg(input_path).arg(output_path)))
 def _layerRemoved(self, layerId):
     if self._layerId and layerId == self._layerId:
         self._layerId = ''
         self.setEnabled(False)
         QgsProject.instance().snapSettingsChanged.disconnect(self._refresh)
         QgsMapLayerRegistry.instance().layerRemoved.disconnect(self._layerRemoved)
         self.snappingEnabledChanged.disconnect(QgsProject.instance().snapSettingsChanged)
Exemplo n.º 9
0
 def finishInit(self):
     # connect signal for layers and populate combobox
     QgsMapLayerRegistry.instance().layersAdded.connect(self.__canvasLayersChanged)
     QgsMapLayerRegistry.instance().layersRemoved.connect(self.__canvasLayersChanged)
     if self.options.groupLayers:
         self.options.legendInterface.groupRelationsChanged.connect(self.__canvasLayersChanged)
     self.__canvasLayersChanged()
Exemplo n.º 10
0
    def testNoSliverPolygons(self):

        # create a layer with some polygons that will be used as a source for "avoid intersections"
        l = QgsVectorLayer('MultiPolygon', 'test_layer', 'memory')
        assert l.isValid()
        QgsMapLayerRegistry.instance().addMapLayer(l)
        QgsProject.instance().writeEntry("Digitizing", "/AvoidIntersectionsList", [l.id()])

        features = []
        for i, wkt in enumerate(feat_wkt):
            f = QgsFeature(i + 1)
            f.setGeometry(QgsGeometry.fromWkt(wkt))
            features.append(f)

        l.dataProvider().addFeatures(features)
        assert l.pendingFeatureCount() == 7

        # create a geometry and remove its intersections with other geometries

        g = QgsGeometry.fromWkt(newg_wkt)
        assert g.avoidIntersections() == 0

        # the resulting multi-polygon must have exactly three parts
        # (in QGIS 2.0 it has one more tiny part that appears at the border between two of the original polygons)
        mpg = g.asMultiPolygon()
        assert len(mpg) == 3
    def __init__(self, snapLayer, parent=None):
        super(LayerSnappingEnabledAction, self).__init__(parent)

        self._layerId = ''
        self._iface = None  # QgisInteface

        if isinstance(snapLayer, QgisInterface):
            self._iface = snapLayer
        elif isinstance(snapLayer, QgsVectorLayer):
            self._layerId = snapLayer.id()
        elif isinstance(snapLayer, str) or isinstance(snapLayer, unicode):
            self._layerId = snapLayer

        self.setCheckable(True)
        self.setText('Toggle Layer Snapping')
        self.setStatusTip('Toggle snapping on this layer')
        self.setIcon(QIcon(':/plugins/ark/snapEnable.png'))

        self._refresh()
        self.triggered.connect(self._triggered)

        # Make sure we catch changes in the main snapping dialog
        QgsProject.instance().snapSettingsChanged.connect(self._refresh)
        # If using current layer, make sure we update when it changes
        if self._iface:
            self._iface.legendInterface().currentLayerChanged.connect(self._refresh)
        # If the layer is removed then disable the button
        QgsMapLayerRegistry.instance().layerRemoved.connect(self._layerRemoved)
        # If we change the settings, make such others are told
        self.snappingEnabledChanged.connect(QgsProject.instance().snapSettingsChanged)
Exemplo n.º 12
0
    def accept(self):
        """Process the layer and field and generate a new layer.

        .. note:: This is called on ok click.

        """
        myIndex = self.cboFields.currentIndex()
        myFieldName = self.cboFields.itemData(
            myIndex, QtCore.Qt.UserRole).toString()

        myIndex = self.cboPolygonLayers.currentIndex()
        myLayerId = self.cboPolygonLayers.itemData(
            myIndex, QtCore.Qt.UserRole).toString()
        myLayer = QgsMapLayerRegistry.instance().mapLayer(myLayerId)

        myFileName = str(myLayer.source())

        myInputLayer = safe_read_layer(myFileName)

        try:
            myOutputLayer = self.minimum_needs(myInputLayer, str(myFieldName))
        except ValueError:
            return

        myNewFile = myFileName[:-4] + '_perka7' + '.shp'

        myOutputLayer.write_to_file(myNewFile)

        myNewLayer = QgsVectorLayer(myNewFile, 'Minimum Needs', 'ogr')
        QgsMapLayerRegistry.instance().addMapLayers([myNewLayer])
        self.done(QtGui.QDialog.Accepted)
Exemplo n.º 13
0
def add_qgis_raser_layer(raster_layer, canvas, bands = None):
    index_group = TerreImageConstant().index_group
    logger.debug("index_group: " + str(index_group))

    if bands:
        if raster_layer.rasterType() == 2:
            logger.debug(bands)
            pir = bands['pir']
            red = bands['red']
            green = bands['green']
            logger.debug('pir: ' + str(pir))
            logger.debug("red: " + str(red))
            logger.debug("green: " + str(green))
            if pir and red and green:
                renderer = raster_layer.renderer()
                # raster_layer.setDrawingStyle("MultiBandColor")
                renderer.setRedBand(pir)
                renderer.setGreenBand(red)
                renderer.setBlueBand(green)
                # raster_layer.setRenderer( renderer )
            # contrastForRasters( raster_layer, 0, 0, [pir, red, green] )
            histogram_stretching(raster_layer, canvas)

    QgsMapLayerRegistry.instance().addMapLayer(raster_layer)
    TerreImageConstant().legendInterface.moveLayer(raster_layer, index_group)
Exemplo n.º 14
0
    def test_cboAggregationToggle(self):
        """Aggregation Combobox toggles on and off as expected."""

        # With aggregation layer
        myResult, myMessage = setup_scenario(
            DOCK,
            hazard='A flood in Jakarta like in 2007',
            exposure='People',
            function='Need evacuation',
            function_id='Flood Evacuation Function',
            aggregation_layer='kabupaten jakarta singlepart',
            aggregation_enabled_flag=True)
        myMessage += ' when an aggregation layer is defined.'
        assert myResult, myMessage

        # With no aggregation layer
        myLayer = DOCK.get_aggregation_layer()
        myId = myLayer.id()
        QgsMapLayerRegistry.instance().removeMapLayer(myId)
        myResult, myMessage = setup_scenario(
            DOCK,
            hazard='A flood in Jakarta like in 2007',
            exposure='People',
            function='Need evacuation',
            function_id='Flood Evacuation Function',
            aggregation_enabled_flag=False)
        myMessage += ' when no aggregation layer is defined.'
        assert myResult, myMessage
Exemplo n.º 15
0
def loadLayers(theLayerList, theClearFlag=True, DIR=TESTDATA):
    """Helper function to load layers as defined in a python list."""
    # First unload any layers that may already be loaded
    if theClearFlag:
        for myLayer in QgsMapLayerRegistry.instance().mapLayers():
            QgsMapLayerRegistry.instance().removeMapLayer(myLayer)

    # Now go ahead and load our layers
    myExposureLayerCount = 0
    myHazardLayerCount = 0
    myCanvasLayers = []

    # Now create our new layers
    for myFile in theLayerList:

        myLayer, myType = loadLayer(myFile, DIR)
        if myType == 'hazard':
            myHazardLayerCount += 1
        elif myType == 'exposure':
            myExposureLayerCount += 1
        # Add layer to the registry (that QGis knows about)
        QgsMapLayerRegistry.instance().addMapLayer(myLayer)

        # Create Map Canvas Layer Instance and add to list
        myCanvasLayers.append(QgsMapCanvasLayer(myLayer))

    # Quickly add any existing CANVAS layers to our list first
    for myLayer in CANVAS.layers():
        myCanvasLayers.append(QgsMapCanvasLayer(myLayer))
    # now load all these layers in the CANVAS
    CANVAS.setLayerSet(myCanvasLayers)
    DOCK.getLayers()

    # Add MCL's to the CANVAS
    return myHazardLayerCount, myExposureLayerCount
Exemplo n.º 16
0
def load_table_layers(config_collection):
    """
    In order to be able to use attribute tables in the composition, the
    corresponding vector layers need to be added to the layer
    registry. This method creates vector layers from the linked tables
    in the configuration items. This is required prior to creating the
    composition from file.
    :param config_collection: Table configuration collection built from
    the template file.
    :type config_collection: TableConfigurationCollection
    :returns: Valid layers that have been successfully added to the
    registry.
    :rtype: list
    """
    table_configs = config_collection.items().values()

    v_layers = []

    for conf in table_configs:
        layer_name = conf.linked_table()
        v_layer = vector_layer(layer_name)

        if v_layer is None:
            return

        if not v_layer.isValid():
            return

        v_layers.append(v_layer)

    QgsMapLayerRegistry.instance().addMapLayers(v_layers, False)

    return v_layers
Exemplo n.º 17
0
    def test_geometryTypes(self):

        geo = [(1, "POINT", "(0 0)"),
               (2, "LINESTRING", "(0 0,1 0)"),
               (3, "POLYGON", "((0 0,1 0,1 1,0 0))"),
               (4, "MULTIPOINT", "((1 1))"),
               (5, "MULTILINESTRING", "((0 0,1 0),(0 1,1 1))"),
               (6, "MULTIPOLYGON", "(((0 0,1 0,1 1,0 0)),((2 2,3 0,3 3,2 2)))")]
        for wkb_type, wkt_type, wkt in geo:
            l = QgsVectorLayer("%s?crs=epsg:4326" % wkt_type, "m1", "memory", False)
            self.assertEqual(l.isValid(), True)
            QgsMapLayerRegistry.instance().addMapLayer(l)

            f1 = QgsFeature(1)
            g = QgsGeometry.fromWkt(wkt_type + wkt)
            self.assertEqual(g is None, False)
            f1.setGeometry(g)
            l.dataProvider().addFeatures([f1])

            l2 = QgsVectorLayer("?layer_ref=%s" % l.id(), "vtab", "virtual", False)
            self.assertEqual(l2.isValid(), True)
            self.assertEqual(l2.dataProvider().featureCount(), 1)
            self.assertEqual(l2.dataProvider().wkbType(), wkb_type)

            QgsMapLayerRegistry.instance().removeMapLayer(l.id())
Exemplo n.º 18
0
    def accept(self):
        """Process the layer and field and generate a new layer.

        .. note:: This is called on OK click.

        """
        index = self.cboFields.currentIndex()
        field_name = self.cboFields.itemData(
            index, QtCore.Qt.UserRole)

        index = self.cboPolygonLayers.currentIndex()
        layer_id = self.cboPolygonLayers.itemData(
            index, QtCore.Qt.UserRole)
        # noinspection PyArgumentList
        layer = QgsMapLayerRegistry.instance().mapLayer(layer_id)

        file_name = layer.source()

        input_layer = safe_read_layer(file_name)

        try:
            output_layer = self.minimum_needs(input_layer, field_name)
        except ValueError:
            return

        new_file = file_name[:-4] + '_perka7' + '.shp'

        output_layer.write_to_file(new_file)

        new_layer = QgsVectorLayer(new_file, 'Minimum Needs', 'ogr')
        # noinspection PyArgumentList
        QgsMapLayerRegistry.instance().addMapLayers([new_layer])
        self.done(QtGui.QDialog.Accepted)
Exemplo n.º 19
0
    def __init__(self, iface, parent = None):
        """Constructor."""
        super(CalcContour, self).__init__(parent)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)
        
        self.iface = iface

        #insert layers into the combobox
        self.populateLayers()

        #instance of the QgsMapTool derived class (line tool)
        self.tool = DsgLineTool(self.iface.mapCanvas())
        self.tool.lineCreated.connect(self.updateLayer)

        #instance of the class responsible to update layer features
        self.contourTool = ContourTool()

        #Connecting slot to deal with adition/removal of layers
        QgsMapLayerRegistry.instance().layersAdded.connect(self.addLayers)
        QgsMapLayerRegistry.instance().layersRemoved.connect(self.populateLayers)
Exemplo n.º 20
0
    def __init__(self, parent=None, iface=None):
        QTabWidget.__init__(self, parent)
        self.setupUi(self)

        self._notif_bar = None
        self._ol_loaded = False
        self._overlay_layer = None
        self.sel_highlight = None
        self.memory_layer = None
        self._db_session = STDMDb.instance().session

        self.set_iface(iface)

        #Web config
        self._web_spatial_loader = WebSpatialLoader(self.spatial_web_view, self)

        #Connect signals
        self._web_spatial_loader.loadError.connect(self.on_spatial_browser_error)
        self._web_spatial_loader.loadProgress.connect(self.on_spatial_browser_loading)
        self._web_spatial_loader.loadFinished.connect(self.on_spatial_browser_finished)
        self._web_spatial_loader.zoomChanged.connect(self.on_map_zoom_level_changed)
        self.rbGMaps.toggled.connect(self.on_load_GMaps)
        self.rbOSM.toggled.connect(self.on_load_OSM)
        self.zoomSlider.sliderReleased.connect(self.on_zoom_changed)
        self.btnResetMap.clicked.connect(self.on_reset_web_map)
        self.btnSync.clicked.connect(self.on_sync_extents)
        QgsMapLayerRegistry.instance().layersWillBeRemoved.connect(self._on_overlay_to_be_removed)
Exemplo n.º 21
0
def add_layer_to_canvas(layer, name, impact_function):
    """Helper method to add layer to QGIS.

    :param layer: The layer.
    :type layer: QgsMapLayer

    :param name: Layer name.
    :type name: str

    :param impact_function: The impact function used.
    :type impact_function: ImpactFunction

    :param iface: QGIS QGisAppInterface instance.
    :type iface: QGisAppInterface
    """
    group_name = impact_function.name

    # noinspection PyArgumentList
    root = QgsProject.instance().layerTreeRoot()
    group_analysis = root.findGroup(group_name)
    group_analysis.setVisible(Qt.Checked)

    layer.setLayerName(name)

    QgsMapLayerRegistry.instance().addMapLayer(layer, False)
    layer_node = group_analysis.addLayer(layer)

    layer_node.setVisible(Qt.Checked)
 def tearDown(self):
     """Destroy the dialog after each test."""
     # Clear all the loaded layers in Map Registry
     # noinspection PyArgumentList,PyUnresolvedReferences
     for layer in QgsMapLayerRegistry.instance().mapLayers():
         # noinspection PyArgumentList,PyUnresolvedReferences
         QgsMapLayerRegistry.instance().removeMapLayer(layer)
Exemplo n.º 23
0
    def prepare_ordered_marker(self, coords, idx):
        """
        Try to display nice marker on a point layer, showing the order of
        the path computed by OSRM.
        """
        self.tsp_marker_lr = QgsVectorLayer(
            "Point?crs=epsg:4326&field=id:integer"
            "&field=TSP_nb:integer(20)&field=Origin_nb:integer(20)",
            "tsp_markers_osrm{}".format(self.nb_route), "memory")
        symbol = QgsSymbolV2.defaultSymbol(self.tsp_marker_lr.geometryType())
        symbol.setSize(4.5)
        symbol.setColor(QtGui.QColor("yellow"))

        ordered_pts = \
            [coords[i["waypoint_index"]] for i in self.parsed['waypoints']]
        print("ordered_pts : ", ordered_pts)

        features = []
        for nb, pt in enumerate(ordered_pts):
            ft = QgsFeature()
            ft.setGeometry(QgsGeometry.fromPoint(QgsPoint(pt)))
            ft.setAttributes([nb, nb + 1, coords.index(pt)])
            features.append(ft)
        self.tsp_marker_lr.dataProvider().addFeatures(features)

        pal_lyr = QgsPalLayerSettings()
        pal_lyr.readFromLayer(self.tsp_marker_lr)
        pal_lyr.enabled = True
        pal_lyr.fieldName = 'TSP_nb'
        pal_lyr.placement= QgsPalLayerSettings.OverPoint
        pal_lyr.setDataDefinedProperty(QgsPalLayerSettings.Size,True,True,'12','')
        pal_lyr.writeToLayer(self.tsp_marker_lr)

        self.tsp_marker_lr.setRendererV2(QgsSingleSymbolRendererV2(symbol))
        QgsMapLayerRegistry.instance().addMapLayer(self.tsp_marker_lr)
Exemplo n.º 24
0
    def Xtest_print_impact_table(self):
        """Test print impact table to pdf."""
        impact_layer_path = test_data_path(
            'impact', 'population_affected_entire_area.shp')
        layer, _ = load_layer(impact_layer_path)
        # noinspection PyUnresolvedReferences,PyArgumentList
        QgsMapLayerRegistry.instance().addMapLayer(layer)
        # noinspection PyCallingNonCallable
        rect = QgsRectangle(106.8194, -6.2108, 106.8201, -6.1964)
        CANVAS.setExtent(rect)
        CANVAS.refresh()

        template = resources_path(
            'qgis-composer-templates', 'a4-portrait-blue.qpt')
        report = ImpactReport(IFACE, template, layer)
        report.template = template  # just to cover set template
        out_path = unique_filename(
            prefix='test_print_impact_table',
            suffix='.pdf',
            dir=temp_dir('test'))
        report.print_impact_table(out_path)

        # Check the file exists
        message = 'Rendered output does not exist: %s' % out_path
        self.assertTrue(os.path.exists(out_path), message)

        # Check the file is not corrupt
        message = 'The output file %s is corrupt' % out_path
        out_size = os.stat(out_path).st_size
        self.assertTrue(out_size > 0, message)
Exemplo n.º 25
0
 def return_batch_route(self, features):
     """Save and/or display the routes retrieved"""
     osrm_batch_route_layer = QgsVectorLayer(
         "Linestring?crs=epsg:4326&field=id:integer"
         "&field=total_time:integer(20)&field=distance:integer(20)",
         "routes_osrm{}".format(self.nb_done), "memory")
     provider = osrm_batch_route_layer.dataProvider()
     provider.addFeatures(features)
     QgsMapLayerRegistry.instance().addMapLayer(osrm_batch_route_layer)
     if self.filename:
         error = QgsVectorFileWriter.writeAsVectorFormat(
             osrm_batch_route_layer, self.filename,
             self.encoding, None, "ESRI Shapefile")
         if error != QgsVectorFileWriter.NoError:
             self.iface.messageBar().pushMessage(
                 "Error",
                 "Can't save the result into {} - Output have been "
                 "added to the canvas (see QGis log for error trace"
                 "back)".format(self.filename), duration=10)
             QgsMessageLog.logMessage(
                 'OSRM-plugin error report :\n {}'.format(error),
                 level=QgsMessageLog.WARNING)
             self.iface.setActiveLayer(osrm_batch_route_layer)
             return -1
         else:
             QtGui.QMessageBox.information(
                 self.iface.mainWindow(), 'Info',
                 "Result saved in {}".format(self.filename))
     if self.check_add_layer.isChecked():
         self.iface.setActiveLayer(osrm_batch_route_layer)
     else:
         QgsMapLayerRegistry.instance().removeMapLayer(
             osrm_batch_route_layer.id())
     self.iface.messageBar().clearWidgets()
Exemplo n.º 26
0
    def testRenderMarkerLayerDataDefined(self):
        """ test that rendering a marker symbol with data defined enabled layer works"""

        points_shp = os.path.join(TEST_DATA_DIR, 'points.shp')
        points_layer = QgsVectorLayer(points_shp, 'Points', 'ogr')
        QgsMapLayerRegistry.instance().addMapLayer(points_layer)

        layer = QgsSimpleMarkerSymbolLayer()
        layer.setDataDefinedProperty("enabled", QgsDataDefined("Class='Biplane'"))
        layer.setColor(QColor(100, 150, 150))
        layer.setSize(5)
        layer.setOutlineStyle(Qt.NoPen)

        symbol = QgsMarkerSymbol()
        symbol.changeSymbolLayer(0, layer)
        points_layer.setRenderer(QgsSingleSymbolRenderer(symbol))

        ms = QgsMapSettings()
        ms.setOutputSize(QSize(400, 400))
        ms.setOutputDpi(96)
        ms.setExtent(QgsRectangle(-133, 22, -70, 52))
        ms.setLayers([points_layer.id()])

        renderchecker = QgsMultiRenderChecker()
        renderchecker.setMapSettings(ms)
        renderchecker.setControlPathPrefix('symbol_layer')
        renderchecker.setControlName('expected_markerlayer_ddenabled')
        self.assertTrue(renderchecker.runTest('markerlayer_ddenabled'))
        QgsMapLayerRegistry.instance().removeMapLayer(points_layer)
 def createLayers(self):
     types = [("Point", ptOursStyle, ptTheirsStyle),
               ("LineString", lineOursStyle, lineTheirsStyle),
               ("Polygon", polygonOursStyle, polygonTheirsStyle)]
     if self.oursgeom is not None:
         geomtype = types[int(self.oursgeom.type())][0]
         style = types[int(self.oursgeom.type())][1]
         self.oursLayer = loadLayerNoCrsDialog(geomtype + "?crs=EPSG:4326", "ours", "memory")
         pr = self.oursLayer.dataProvider()
         feat = QgsFeature()
         feat.setGeometry(self.oursgeom)
         pr.addFeatures([feat])
         self.oursLayer.loadNamedStyle(style)
         self.oursLayer.updateExtents()
         QgsMapLayerRegistry.instance().addMapLayer(self.oursLayer, False)
     else:
         self.oursLayer = None
     if self.theirsgeom is not None:
         geomtype = types[int(self.theirsgeom.type())][0]
         style = types[int(self.theirsgeom.type())][2]
         self.theirsLayer = loadLayerNoCrsDialog(geomtype + "?crs=EPSG:4326", "theirs", "memory")
         pr = self.theirsLayer.dataProvider()
         feat = QgsFeature()
         feat.setGeometry(self.theirsgeom)
         pr.addFeatures([feat])
         self.theirsLayer.loadNamedStyle(style)
         self.theirsLayer.updateExtents()
         QgsMapLayerRegistry.instance().addMapLayer(self.theirsLayer, False)
     else:
         self.theirsLayer = None
Exemplo n.º 28
0
    def test_add_layer_to_registry(self):
        layer_name = layer_interaction.biuniquify_layer_name('this_layer_was_added_for_testing_purpose')

        layer = QgsVectorLayer('Polygon?crs=EPSG:3857', layer_name, 'memory', False)

        number_of_layers = len(QgsMapLayerRegistry.instance().mapLayers())
        layer_interaction.add_layer_to_registry(layer)
        self.layer_list.append(layer.name())

        map_layers = QgsMapLayerRegistry.instance().mapLayers()
        actual = len(map_layers)
        expected = number_of_layers + 1
        message = 'An error occured when adding a layer to the MapLayerRegistry. {} is not {}!'.format(actual, expected)
        self.assertEqual(actual, expected, message)

        layer_added = False
        for layer_key in map_layers:

            if map_layers[layer_key].name() == layer_name:
                layer_added = True
                break

        self.assertTrue(layer_added, 'An error occured when adding a layer to the MapLayerRegistry.')
        number_of_layers = len(map_layers)
        layer_interaction.add_layer_to_registry(None)
        self.assertEqual(len(QgsMapLayerRegistry.instance().mapLayers()), number_of_layers, 'An error occured when trying to add a none-type-layer to the MapLayerRegistry. The number of layers should not increase.')
Exemplo n.º 29
0
    def testRenderLineLayerDataDefined(self):
        """ test that rendering a line symbol with data defined enabled layer works"""

        lines_shp = os.path.join(TEST_DATA_DIR, 'lines.shp')
        lines_layer = QgsVectorLayer(lines_shp, 'Lines', 'ogr')
        QgsMapLayerRegistry.instance().addMapLayer(lines_layer)

        layer = QgsSimpleLineSymbolLayer()
        layer.setDataDefinedProperty("enabled", QgsDataDefined("Name='Highway'"))
        layer.setColor(QColor(100, 150, 150))
        layer.setWidth(5)

        symbol = QgsLineSymbol()
        symbol.changeSymbolLayer(0, layer)
        lines_layer.setRenderer(QgsSingleSymbolRenderer(symbol))

        ms = QgsMapSettings()
        ms.setOutputSize(QSize(400, 400))
        ms.setOutputDpi(96)
        ms.setExtent(QgsRectangle(-133, 22, -70, 52))
        ms.setLayers([lines_layer.id()])

        renderchecker = QgsMultiRenderChecker()
        renderchecker.setMapSettings(ms)
        renderchecker.setControlPathPrefix('symbol_layer')
        renderchecker.setControlName('expected_linelayer_ddenabled')
        self.assertTrue(renderchecker.runTest('linelayer_ddenabled'))
        QgsMapLayerRegistry.instance().removeMapLayer(lines_layer)
Exemplo n.º 30
0
    def build_index(self, project):
        self.searchbox.setEnabled(False)
        self.resultsView.setEnabled(False)
        self.resultsView.addItem("building search index...")

        validformat, settings = valid_search_settings(project.settings)
        if not validformat:
            RoamEvents.raisemessage("Searching", "Invalid search config.", level=1)
            self.searchbox.hide()
            self.resultsView.clear()
            self.resultsView.addItem("Invalid search config found")
            return

        self.indexthread = QThread()
        path = os.path.join(os.environ['APPDATA'], "roam", project.name)

        roam.utils.info("Search index path: {0}".format(path))

        if not os.path.exists(path):
            os.makedirs(path)

        self.indexbuilder = IndexBuilder(path, settings)
        self.indexbuilder.moveToThread(self.indexthread)

        QgsMapLayerRegistry.instance().removeAll.connect(self.indexthread.quit)

        self.indexbuilder.indexBuilt.connect(self.index_built)
        self.indexbuilder.finished.connect(self.indexthread.quit)
        self.indexthread.started.connect(self.indexbuilder.build_index)
        self.indexthread.finished.connect(self.indexbuilder.quit)

        self.indexthread.start()
Exemplo n.º 31
0
def run(item, action, mainwindow):
    db = item.database()
    uri = db.uri()
    iface = mainwindow.iface

    quoteId = db.connector.quoteId
    quoteStr = db.connector.quoteString

    # check if the selected item is a topology schema
    isTopoSchema = False

    if not hasattr(item, 'schema'):
        mainwindow.infoBar.pushMessage(
            "Invalid topology", u'Select a topology schema to continue.',
            QgsMessageBar.INFO, mainwindow.iface.messageTimeout())
        return False

    if item.schema() is not None:
        sql = u"SELECT srid FROM topology.topology WHERE name = %s" % quoteStr(
            item.schema().name)
        c = db.connector._get_cursor()
        db.connector._execute(c, sql)
        res = db.connector._fetchone(c)
        isTopoSchema = res is not None

    if not isTopoSchema:
        mainwindow.infoBar.pushMessage(
            "Invalid topology",
            u'Schema "{0}" is not registered in topology.topology.'.format(
                item.schema().name), QgsMessageBar.WARNING,
            mainwindow.iface.messageTimeout())
        return False

    if (res[0] < 0):
        mainwindow.infoBar.pushMessage(
            "WARNING",
            u'Topology "{0}" is registered as having a srid of {1} in topology.topology, we will assume 0 (for unknown)'
            .format(item.schema().name, res[0]), QgsMessageBar.WARNING,
            mainwindow.iface.messageTimeout())
        toposrid = '0'
    else:
        toposrid = str(res[0])

    # load layers into the current project
    toponame = item.schema().name
    template_dir = os.path.join(current_path, 'templates')

    # do not refresh the canvas until all the layers are added
    prevRenderFlagState = iface.mapCanvas().renderFlag()
    iface.mapCanvas().setRenderFlag(False)
    try:
        provider = db.dbplugin().providerName()
        uri = db.uri()

        # Force use of estimated metadata (topologies can be big)
        uri.setUseEstimatedMetadata(True)

        # FACES

        # face mbr
        uri.setDataSource(toponame, 'face', 'mbr', '', 'face_id')
        uri.setSrid(toposrid)
        uri.setWkbType(QgsWkbTypes.Polygon)
        layerFaceMbr = QgsVectorLayer(uri.uri(False),
                                      u'%s.face_mbr' % toponame, provider)
        layerFaceMbr.loadNamedStyle(os.path.join(template_dir, 'face_mbr.qml'))

        face_extent = layerFaceMbr.extent()

        # face geometry
        sql = u'SELECT face_id, topology.ST_GetFaceGeometry(%s,' \
              'face_id)::geometry(polygon, %s) as geom ' \
              'FROM %s.face WHERE face_id > 0' % \
              (quoteStr(toponame), toposrid, quoteId(toponame))
        uri.setDataSource('', u'(%s\n)' % sql, 'geom', '', 'face_id')
        uri.setSrid(toposrid)
        uri.setWkbType(QgsWkbTypes.Polygon)
        layerFaceGeom = QgsVectorLayer(uri.uri(False), u'%s.face' % toponame,
                                       provider)
        layerFaceGeom.setExtent(face_extent)
        layerFaceGeom.loadNamedStyle(os.path.join(template_dir, 'face.qml'))

        # face_seed
        sql = u'SELECT face_id, ST_PointOnSurface(' \
              'topology.ST_GetFaceGeometry(%s,' \
              'face_id))::geometry(point, %s) as geom ' \
              'FROM %s.face WHERE face_id > 0' % \
              (quoteStr(toponame), toposrid, quoteId(toponame))
        uri.setDataSource('', u'(%s)' % sql, 'geom', '', 'face_id')
        uri.setSrid(toposrid)
        uri.setWkbType(QgsWkbTypes.Point)
        layerFaceSeed = QgsVectorLayer(uri.uri(False),
                                       u'%s.face_seed' % toponame, provider)
        layerFaceSeed.setExtent(face_extent)
        layerFaceSeed.loadNamedStyle(
            os.path.join(template_dir, 'face_seed.qml'))

        # TODO: add polygon0, polygon1 and polygon2 ?

        # NODES

        # node
        uri.setDataSource(toponame, 'node', 'geom', '', 'node_id')
        uri.setSrid(toposrid)
        uri.setWkbType(QgsWkbTypes.Point)
        layerNode = QgsVectorLayer(uri.uri(False), u'%s.node' % toponame,
                                   provider)
        layerNode.loadNamedStyle(os.path.join(template_dir, 'node.qml'))
        node_extent = layerNode.extent()

        # node labels
        uri.setDataSource(toponame, 'node', 'geom', '', 'node_id')
        uri.setSrid(toposrid)
        uri.setWkbType(QgsWkbTypes.Point)
        layerNodeLabel = QgsVectorLayer(uri.uri(False),
                                        u'%s.node_id' % toponame, provider)
        layerNodeLabel.setExtent(node_extent)
        layerNodeLabel.loadNamedStyle(
            os.path.join(template_dir, 'node_label.qml'))

        # EDGES

        # edge
        uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id')
        uri.setSrid(toposrid)
        uri.setWkbType(QgsWkbTypes.LineString)
        layerEdge = QgsVectorLayer(uri.uri(False), u'%s.edge' % toponame,
                                   provider)
        edge_extent = layerEdge.extent()

        # directed edge
        uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id')
        uri.setSrid(toposrid)
        uri.setWkbType(QgsWkbTypes.LineString)
        layerDirectedEdge = QgsVectorLayer(uri.uri(False),
                                           u'%s.directed_edge' % toponame,
                                           provider)
        layerDirectedEdge.setExtent(edge_extent)
        layerDirectedEdge.loadNamedStyle(os.path.join(template_dir,
                                                      'edge.qml'))

        # edge labels
        uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id')
        uri.setSrid(toposrid)
        uri.setWkbType(QgsWkbTypes.LineString)
        layerEdgeLabel = QgsVectorLayer(uri.uri(False),
                                        u'%s.edge_id' % toponame, provider)
        layerEdgeLabel.setExtent(edge_extent)
        layerEdgeLabel.loadNamedStyle(
            os.path.join(template_dir, 'edge_label.qml'))

        # face_left
        uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id')
        uri.setSrid(toposrid)
        uri.setWkbType(QgsWkbTypes.LineString)
        layerFaceLeft = QgsVectorLayer(uri.uri(False),
                                       u'%s.face_left' % toponame, provider)
        layerFaceLeft.setExtent(edge_extent)
        layerFaceLeft.loadNamedStyle(
            os.path.join(template_dir, 'face_left.qml'))

        # face_right
        uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id')
        uri.setSrid(toposrid)
        uri.setWkbType(QgsWkbTypes.LineString)
        layerFaceRight = QgsVectorLayer(uri.uri(False),
                                        u'%s.face_right' % toponame, provider)
        layerFaceRight.setExtent(edge_extent)
        layerFaceRight.loadNamedStyle(
            os.path.join(template_dir, 'face_right.qml'))

        # next_left
        uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id')
        uri.setSrid(toposrid)
        uri.setWkbType(QgsWkbTypes.LineString)
        layerNextLeft = QgsVectorLayer(uri.uri(False),
                                       u'%s.next_left' % toponame, provider)
        layerNextLeft.setExtent(edge_extent)
        layerNextLeft.loadNamedStyle(
            os.path.join(template_dir, 'next_left.qml'))

        # next_right
        uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id')
        uri.setSrid(toposrid)
        uri.setWkbType(QgsWkbTypes.LineString)
        layerNextRight = QgsVectorLayer(uri.uri(False),
                                        u'%s.next_right' % toponame, provider)
        layerNextRight.setExtent(edge_extent)
        layerNextRight.loadNamedStyle(
            os.path.join(template_dir, 'next_right.qml'))

        # Add layers to the layer tree

        faceLayers = [layerFaceMbr, layerFaceGeom, layerFaceSeed]
        nodeLayers = [layerNode, layerNodeLabel]
        edgeLayers = [
            layerEdge, layerDirectedEdge, layerEdgeLabel, layerEdgeFaceLeft,
            layerEdgeFaceRight, layerEdgeNextLeft, layerEdgeNextRight
        ]

        QgsMapLayerRegistry.instance().addMapLayers(faceLayers, False)

        groupFaces = QgsLayerTreeGroup(u'Faces')
        for layer in faceLayers:
            nodeLayer = groupFaces.addLayer(layer)
            nodeLayer.setVisible(Qt.Unchecked)
            nodeLayer.setExpanded(False)

        groupNodes = QgsLayerTreeGroup(u'Nodes')
        for layer in faceLayers:
            nodeLayer = groupNodes.addLayer(layer)
            nodeLayer.setVisible(Qt.Unchecked)
            nodeLayer.setExpanded(False)

        groupEdges = QgsLayerTreeGroup(u'Edges')
        for layer in faceLayers:
            nodeLayer = groupEdges.addLayer(layer)
            nodeLayer.setVisible(Qt.Unchecked)
            nodeLayer.setExpanded(False)

        supergroup = QgsLayerTreeGroup(u'Topology "%s"' % toponame)
        supergroup.insertChildNodes(-1, [groupFaces, groupNodes, groupEdges])

        QgsProject.instance().layerTreeRoot().addChildNode(supergroup)

    finally:

        # Set canvas extent to topology extent, if not yet initialized
        canvas = iface.mapCanvas()
        if (canvas.fullExtent().isNull()):
            ext = node_extent
            ext.combineExtentWith(edge_extent)
            # Grow by 1/20 of largest side
            ext = ext.buffer(max(ext.width(), ext.height()) / 20)
            canvas.setExtent(ext)

        # restore canvas render flag
        iface.mapCanvas().setRenderFlag(prevRenderFlagState)

    return True
Exemplo n.º 32
0
def load_map_layers(uri, parent_dialog, drivetime_layer, args):
    """Style map layers and load them in Qgis

    :param uri: Connection to the database
    :type uri: QgsDataSourceURI

    :param parent_dialog: A dialog that called this function.
    :type parent_dialog: QProgressDialog

    :param drivetime_layer: A layer containing drivetimes
    :type drivetime_layer: QgsVectorLayer

    :param args: List containing database parameters
    :type args: {}

    """

    uri.setDataSource(args['network_schema'], args['network_table'],
                      args['network_geom'])
    network_layer = QgsVectorLayer(uri.uri(), "network", "postgres")

    uri.setDataSource(args['catchment_schema'], args['catchment_table'],
                      args['catchment_geom'])
    catchment_layer = QgsVectorLayer(uri.uri(), "catchment", "postgres")

    # Style the tin, contour and network

    drivetime_style = resources_path('styles', 'qgis', 'drivetimes.qml')
    drivetime_layer.loadNamedStyle(drivetime_style)

    network_style = resources_path('styles', 'qgis', 'network.qml')
    network_layer.loadNamedStyle(network_style)

    catchment_style = resources_path('styles', 'qgis', 'catchment.qml')
    catchment_layer.loadNamedStyle(catchment_style)

    if drivetime_layer.isValid():
        QgsMapLayerRegistry.instance().addMapLayers([drivetime_layer])
    else:
        if parent_dialog:
            display_warning_message_box(
                parent_dialog, parent_dialog.tr("Error"),
                parent_dialog.tr('Error loading isochrone map '
                                 'Could not load drivetimes file!'))
        else:
            display_warning_message_box(
                parent_dialog, 'Error', 'Error loading isochrone map '
                'Could not load drivetimes file!')

    if network_layer.isValid():
        QgsMapLayerRegistry.instance().addMapLayers([network_layer])
    else:
        if parent_dialog:
            display_warning_message_box(
                parent_dialog, parent_dialog.tr("Error"),
                parent_dialog.tr('Error loading isochrone map '
                                 'Could not load network file!'))
        else:
            display_warning_message_box(
                parent_dialog, 'Error', 'Error loading isochrone map '
                'Could not load network file!')

    if catchment_layer.isValid():
        QgsMapLayerRegistry.instance().addMapLayers([catchment_layer])
    else:
        if parent_dialog:
            display_warning_message_box(
                parent_dialog, parent_dialog.tr("Error"),
                parent_dialog.tr('Error loading isochrone map '
                                 'Could not load catchment file!'))
        else:
            display_warning_message_box(
                parent_dialog, 'Error', 'Error loading isochrone map '
                'Could not load catchment file!')
Exemplo n.º 33
0
def idw_interpolation(layer, parent_dialog):
    """Run interpolation using inverse distance weight algorithm

    :param layer: Vector layer with drivetimes
    :type layer: QgsVectorLayer

    :param parent_dialog: A dialog that called this function.
    :type parent_dialog: QProgressDialog

    :returns raster_layer: Interpolated raster layer with drivetimes
    :rtype raster_layer: QgsRasterLayer

    """
    raster_layer = None
    try:
        Processing.initialize()
        Processing.updateAlgsList()

        output_raster = processing.runalg('gdalogr:gridinvdist', layer,
                                          'minutes', 2, 0, 0, 0, 0, 0, 0, 0, 5,
                                          "[temporary file]")

        output_file = output_raster['OUTPUT']
        file_info = QFileInfo(output_file)
        base_name = file_info.baseName()

        # retrieving the raster output , styling it and load it in Qgis

        raster_layer = QgsRasterLayer(output_file, base_name)

    except Exception as exception:  # pylint: disable=broad-except
        # noinspection PyCallByClass,PyTypeChecker,PyArgumentList
        if parent_dialog:
            display_warning_message_box(
                parent_dialog, parent_dialog.tr('Error'),
                parent_dialog.tr('Error loading isochrone map,'
                                 'please check if you have processing '
                                 'plugin installed '))
        else:
            display_warning_message_box(
                parent_dialog, 'Error', 'Error loading isochrone map,'
                'please check if you have processing '
                'plugin installed ')

    if raster_layer:
        if raster_layer.isValid():
            color_shader = QgsColorRampShader()
            color_shader.setColorRampType(QgsColorRampShader.INTERPOLATED)
            colors = {
                'deep_green': '#1a9641',
                'light_green': '#a6d96a',
                'pale_yellow': '#ffffc0',
                'light_red': '#fdae61',
                'red': '#d7191c'
            }
            provider = raster_layer.dataProvider()
            stats = provider.bandStatistics(1, QgsRasterBandStats.All,
                                            raster_layer.extent(), 0)

            values = {}

            if stats:
                min = stats.minimumValue
                max = stats.maximumValue
                stat_range = max - min
                add = stat_range / 4
                values[0] = min
                value = min
                for index in range(1, 4):
                    value += add
                    values[index] = value
                values[4] = max
            else:
                display_warning_message_box(
                    parent_dialog, parent_dialog.tr('Error'),
                    parent_dialog.tr('Error loading isochrone map'
                                     ' Problem indexing the isochrones map'))

            color_list = [
                QgsColorRampShader.ColorRampItem(values[0],
                                                 QColor(colors['deep_green'])),
                QgsColorRampShader.ColorRampItem(values[1],
                                                 QColor(
                                                     colors['light_green'])),
                QgsColorRampShader.ColorRampItem(values[2],
                                                 QColor(
                                                     colors['pale_yellow'])),
                QgsColorRampShader.ColorRampItem(values[3],
                                                 QColor(colors['light_red'])),
                QgsColorRampShader.ColorRampItem(values[4],
                                                 QColor(colors['red']))
            ]

            color_shader.setColorRampItemList(color_list)
            raster_shader = QgsRasterShader()
            raster_shader.setRasterShaderFunction(color_shader)

            renderer = QgsSingleBandPseudoColorRenderer(
                raster_layer.dataProvider(), 1, raster_shader)
            raster_layer.setRenderer(renderer)

        else:
            if parent_dialog:
                display_warning_message_box(
                    parent_dialog, parent_dialog.tr('Problem'),
                    parent_dialog.tr('Problem styling the isochrone map'))
            else:
                display_warning_message_box(
                    parent_dialog, 'Problem',
                    'Problem styling the isochrone map')

        QgsMapLayerRegistry.instance().addMapLayers([raster_layer])

    else:
        if parent_dialog:

            display_warning_message_box(
                parent_dialog, parent_dialog.tr('Error'),
                parent_dialog.tr('Error loading isochrone map '
                                 'Could not load interpolated file!'))
        else:
            display_warning_message_box(
                parent_dialog, 'Error', 'Error loading isochrone map '
                'Could not load interpolated file!')

    return raster_layer
Exemplo n.º 34
0
 def _loadLayer():
     layerfile = os.path.join(os.path.dirname(__file__), "data", "MGRS_100kmSQ_ID_02H.shp")
     layer = loadLayer(layerfile, provider="ogr")
     QgsMapLayerRegistry.instance().addMapLayer(layer)
Exemplo n.º 35
0
    def show_results(self, qgis_impact_layer, engine_impact_layer):
        """Helper function for slot activated when the process is done.

        .. note:: Adapted from the dock

        :param qgis_impact_layer: A QGIS layer representing the impact.
        :type qgis_impact_layer: QgsMapLayer, QgsVectorLayer, QgsRasterLayer

        :param engine_impact_layer: A safe_layer representing the impact.
        :type engine_impact_layer: ReadLayer

        :returns: Provides a report for writing to the dock.
        :rtype: str
        """
        keywords = self.keyword_io.read_keywords(qgis_impact_layer)

        # write postprocessing report to keyword
        output = self.analysis.postprocessor_manager.get_output(
            self.analysis.aggregator.aoi_mode)
        keywords['postprocessing_report'] = output.to_html(
            suppress_newlines=True)
        self.keyword_io.write_keywords(qgis_impact_layer, keywords)

        # Get tabular information from impact layer
        report = m.Message()
        report.add(LOGO_ELEMENT)
        report.add(m.Heading(self.tr('Analysis Results'), **INFO_STYLE))
        report.add(
            self.keyword_io.read_keywords(qgis_impact_layer, 'impact_summary'))

        # Get requested style for impact layer of either kind
        style = engine_impact_layer.get_style_info()
        style_type = engine_impact_layer.get_style_type()

        # Determine styling for QGIS layer
        if engine_impact_layer.is_vector:
            LOGGER.debug('myEngineImpactLayer.is_vector')
            if not style:
                # Set default style if possible
                pass
            elif style_type == 'categorizedSymbol':
                LOGGER.debug('use categorized')
                set_vector_categorized_style(qgis_impact_layer, style)
            elif style_type == 'graduatedSymbol':
                LOGGER.debug('use graduated')
                set_vector_graduated_style(qgis_impact_layer, style)

        elif engine_impact_layer.is_raster:
            LOGGER.debug('myEngineImpactLayer.is_raster')
            if not style:
                qgis_impact_layer.setDrawingStyle("SingleBandPseudoColor")
                # qgis_impact_layer.setColorShadingAlgorithm(
                #    QgsRasterLayer.PseudoColorShader)
            else:
                setRasterStyle(qgis_impact_layer, style)

        else:
            message = self.tr(
                'Impact layer %s was neither a raster or a vector layer') % (
                    qgis_impact_layer.source())
            # noinspection PyExceptionInherit
            raise ReadLayerError(message)

        # Add layers to QGIS
        layers_to_add = []
        if self.show_intermediate_layers:
            layers_to_add.append(self.analysis.aggregator.layer)
        layers_to_add.append(qgis_impact_layer)
        # noinspection PyArgumentList
        QgsMapLayerRegistry.instance().addMapLayers(layers_to_add)
        # make sure it is active in the legend - needed since QGIS 2.4
        self.iface.setActiveLayer(qgis_impact_layer)
        # then zoom to it
        if self.zoom_to_impact_flag:
            self.iface.zoomToActiveLayer()
        if self.hide_exposure_flag:
            exposure_layer = self.analysis.exposure_layer
            legend = self.iface.legendInterface()
            legend.setLayerVisible(exposure_layer, False)

        # append postprocessing report
        report.add(output.to_html())
        # Layer attribution comes last
        report.add(impact_attribution(keywords).to_html(True))
        # Return text to display in report panel
        return report
Exemplo n.º 36
0
 def getLayer(self, l):
     lid = self.layers.get(l)
     if lid is None:
         return lid
     return QgsMapLayerRegistry.instance().mapLayer(lid)
Exemplo n.º 37
0
    def getVectorTables(self, schema=None):
        """ get list of table with a geometry column
                it returns:
                        name (table name)
                        is_system_table
                        type = 'view' (is a view?)
                        geometry_column:
                                f_table_name (the table name in geometry_columns may be in a wrong case, use this to load the layer)
                                f_geometry_column
                                type
                                coord_dimension
                                srid
        """
        reg = VLayerRegistry.instance()
        VLayerRegistry.instance().reset()
        lst = []
        for _, l in list(QgsMapLayerRegistry.instance().mapLayers().items()):
            if l.type() == QgsMapLayer.VectorLayer:

                lname = l.name()
                # if there is already a layer with this name, use the layer id
                # as name
                if reg.has(lname):
                    lname = l.id()
                VLayerRegistry.instance().set(lname, l.id())

                geomType = None
                dim = None
                g = l.dataProvider().wkbType()
                if g == QgsWkbTypes.Point:
                    geomType = 'POINT'
                    dim = 'XY'
                elif g == QgsWkbTypes.LineString:
                    geomType = 'LINESTRING'
                    dim = 'XY'
                elif g == QgsWkbTypes.Polygon:
                    geomType = 'POLYGON'
                    dim = 'XY'
                elif g == QgsWkbTypes.MultiPoint:
                    geomType = 'MULTIPOINT'
                    dim = 'XY'
                elif g == QgsWkbTypes.MultiLineString:
                    geomType = 'MULTILINESTRING'
                    dim = 'XY'
                elif g == QgsWkbTypes.MultiPolygon:
                    geomType = 'MULTIPOLYGON'
                    dim = 'XY'
                elif g == QgsWkbTypes.Point25D:
                    geomType = 'POINT'
                    dim = 'XYZ'
                elif g == QgsWkbTypes.LineString25D:
                    geomType = 'LINESTRING'
                    dim = 'XYZ'
                elif g == QgsWkbTypes.Polygon25D:
                    geomType = 'POLYGON'
                    dim = 'XYZ'
                elif g == QgsWkbTypes.MultiPoint25D:
                    geomType = 'MULTIPOINT'
                    dim = 'XYZ'
                elif g == QgsWkbTypes.MultiLineString25D:
                    geomType = 'MULTILINESTRING'
                    dim = 'XYZ'
                elif g == QgsWkbTypes.MultiPolygon25D:
                    geomType = 'MULTIPOLYGON'
                    dim = 'XYZ'
                lst.append((Table.VectorType, lname, False, False, l.id(),
                            'geometry', geomType, dim, l.crs().postgisSrid()))
        return lst
Exemplo n.º 38
0
 def getAllLayers(self):
     if LayerRegistry._iface and hasattr(LayerRegistry._iface,
                                         'legendInterface'):
         return LayerRegistry._iface.legendInterface().layers()
     return list(QgsMapLayerRegistry.instance().mapLayers().values())
Exemplo n.º 39
0
    def testCreateExpression(self):
        """ Test creating an expression using the widget"""
        layer = QgsVectorLayer(
            "Point?field=fldtxt:string&field=fldint:integer", "test", "memory")
        # setup value relation
        parent_layer = QgsVectorLayer(
            "Point?field=stringkey:string&field=intkey:integer&field=display:string",
            "parent", "memory")
        f1 = QgsFeature(parent_layer.fields(), 1)
        f1.setAttributes(['a', 1, 'value a'])
        f2 = QgsFeature(parent_layer.fields(), 2)
        f2.setAttributes(['b', 2, 'value b'])
        f3 = QgsFeature(parent_layer.fields(), 3)
        f3.setAttributes(['c', 3, 'value c'])
        parent_layer.dataProvider().addFeatures([f1, f2, f3])
        QgsMapLayerRegistry.instance().addMapLayers([layer, parent_layer])

        config = {
            "Layer": parent_layer.id(),
            "Key": 'stringkey',
            "Value": 'display'
        }

        w = QgsValueRelationSearchWidgetWrapper(layer, 0)
        w.setConfig(config)
        c = w.widget()

        # first, set it to the "select value" item
        c.setCurrentIndex(0)

        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.IsNull),
                         '"fldtxt" IS NULL')
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.IsNotNull),
                         '"fldtxt" IS NOT NULL')
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.EqualTo),
                         '')
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.NotEqualTo),
                         '')

        c.setCurrentIndex(1)
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.IsNull),
                         '"fldtxt" IS NULL')
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.IsNotNull),
                         '"fldtxt" IS NOT NULL')
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.EqualTo),
                         '"fldtxt"=\'a\'')
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.NotEqualTo),
                         '"fldtxt"<>\'a\'')
        c.setCurrentIndex(2)
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.IsNull),
                         '"fldtxt" IS NULL')
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.IsNotNull),
                         '"fldtxt" IS NOT NULL')
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.EqualTo),
                         '"fldtxt"=\'b\'')
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.NotEqualTo),
                         '"fldtxt"<>\'b\'')

        # try with numeric field
        w = QgsValueRelationSearchWidgetWrapper(layer, 1)
        config['Key'] = 'intkey'
        w.setConfig(config)
        c = w.widget()
        c.setCurrentIndex(c.findText('value c'))
        self.assertEqual(c.currentIndex(), 3)
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.IsNull),
                         '"fldint" IS NULL')
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.IsNotNull),
                         '"fldint" IS NOT NULL')
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.EqualTo),
                         '"fldint"=3')
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.NotEqualTo),
                         '"fldint"<>3')

        # try with allow null set
        w = QgsValueRelationSearchWidgetWrapper(layer, 1)
        config['AllowNull'] = True
        w.setConfig(config)
        c = w.widget()
        c.setCurrentIndex(c.findText('value c'))
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.IsNull),
                         '"fldint" IS NULL')
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.IsNotNull),
                         '"fldint" IS NOT NULL')
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.EqualTo),
                         '"fldint"=3')
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.NotEqualTo),
                         '"fldint"<>3')

        # try with line edit
        w = QgsValueRelationSearchWidgetWrapper(layer, 1)
        config['UseCompleter'] = True
        w.setConfig(config)
        l = w.widget()
        l.setText('value b')
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.IsNull),
                         '"fldint" IS NULL')
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.IsNotNull),
                         '"fldint" IS NOT NULL')
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.EqualTo),
                         '"fldint"=2')
        self.assertEqual(w.createExpression(QgsSearchWidgetWrapper.NotEqualTo),
                         '"fldint"<>2')
    def testTransparency(self):
        myPath = os.path.join(unitTestDataPath('raster'),
                              'band1_float32_noct_epsg4326.tif')
        myFileInfo = QFileInfo(myPath)
        myBaseName = myFileInfo.baseName()
        myRasterLayer = QgsRasterLayer(myPath, myBaseName)
        myMessage = 'Raster not loaded: %s' % myPath
        assert myRasterLayer.isValid(), myMessage

        renderer = QgsSingleBandGrayRenderer(myRasterLayer.dataProvider(), 1)
        myRasterLayer.setRenderer(renderer)
        myRasterLayer.setContrastEnhancement(
            QgsContrastEnhancement.StretchToMinimumMaximum,
            QgsRaster.ContrastEnhancementMinMax)

        myContrastEnhancement = myRasterLayer.renderer().contrastEnhancement()
        #print ("myContrastEnhancement.minimumValue = %.17g" %
        #       myContrastEnhancement.minimumValue())
        #print ("myContrastEnhancement.maximumValue = %.17g" %
        #        myContrastEnhancement.maximumValue())

        # Unfortunately the minimum/maximum values calculated in C++ and Python
        # are slightly different (e.g. 3.3999999521443642e+38 x
        # 3.3999999521444001e+38)
        # It is not clear where the precision is lost.
        # We set the same values as C++.
        myContrastEnhancement.setMinimumValue(-3.3319999287625854e+38)
        myContrastEnhancement.setMaximumValue(3.3999999521443642e+38)
        #myType = myRasterLayer.dataProvider().dataType(1);
        #myEnhancement = QgsContrastEnhancement(myType);

        myTransparentSingleValuePixelList = []
        rasterTransparency = QgsRasterTransparency()

        myTransparentPixel1 = \
            QgsRasterTransparency.TransparentSingleValuePixel()
        myTransparentPixel1.min = -2.5840000772112106e+38
        myTransparentPixel1.max = -1.0879999684602689e+38
        myTransparentPixel1.percentTransparent = 50
        myTransparentSingleValuePixelList.append(myTransparentPixel1)

        myTransparentPixel2 = \
            QgsRasterTransparency.TransparentSingleValuePixel()
        myTransparentPixel2.min = 1.359999960575336e+37
        myTransparentPixel2.max = 9.520000231087593e+37
        myTransparentPixel2.percentTransparent = 70
        myTransparentSingleValuePixelList.append(myTransparentPixel2)

        rasterTransparency.setTransparentSingleValuePixelList(
            myTransparentSingleValuePixelList)

        rasterRenderer = myRasterLayer.renderer()
        assert rasterRenderer

        rasterRenderer.setRasterTransparency(rasterTransparency)

        QgsMapLayerRegistry.instance().addMapLayers([
            myRasterLayer,
        ])

        myMapRenderer = QgsMapRenderer()

        myLayers = []
        myLayers.append(myRasterLayer.id())
        myMapRenderer.setLayerSet(myLayers)
        myMapRenderer.setExtent(myRasterLayer.extent())

        myChecker = QgsRenderChecker()
        myChecker.setControlName("expected_raster_transparency")
        myChecker.setMapRenderer(myMapRenderer)

        myResultFlag = myChecker.runTest("raster_transparency_python")
        assert myResultFlag, "Raster transparency rendering test failed"
Exemplo n.º 41
0
    def saveAutoField(self):
        """ Do some validation and then call AutoFieldManager """

        # Check layers
        if not self.tblLayers.selectedItems():
            self.msg.show(
                QApplication.translate(
                    "AutoFieldsDockWidgetPy",
                    "[Warning] Please first select a layer."), 'warning')
            return

        # Check expression
        expression = u''
        if self.optXCoord.isChecked():
            expression = u'$x'
        elif self.optYCoord.isChecked():
            expression = u'$y'
        elif self.optLength.isChecked():
            expression = u'$length'
        elif self.optPerimeter.isChecked():
            expression = u'$perimeter'
        elif self.optArea.isChecked():
            expression = u'$area'
        elif self.optDate.isChecked():
            expression = u'now()'
        elif self.optCustomExpression.isChecked():
            if self.expressionDlg:
                expression = self.expressionDlg.expression
            if not self.expressionDlg or not expression:
                self.msg.show(
                    QApplication.translate(
                        "AutoFieldsDockWidgetPy",
                        "[Warning] Please first set a valid custom expression."
                    ), 'warning')
                return
        else:  # optSpatialValue
            pass

        # Check fields
        fieldName = ''
        if self.optNewField.isChecked():
            if self.txtFieldName.text():

                fieldName = self.txtFieldName.text().strip()
                newField = QgsField(
                    fieldName,
                    self.cboFieldType.itemData(
                        self.cboFieldType.currentIndex(), Qt.UserRole))

                length = self.txtFieldLength.value()
                precision = self.txtFieldPrecision.value()
                # Ensure length and precision are valid values when dealing with Real numbers
                if self.fieldTypesDict[
                        self.cboFieldType.currentIndex()] == 'Real':
                    if precision > length:
                        precision = length
                newField.setLength(length)
                newField.setPrecision(precision)

                for item in self.tblLayers.selectedItems():
                    if item.column() == 1:  # It's the layer name item
                        layer = QgsMapLayerRegistry.instance().mapLayer(
                            item.data(Qt.UserRole))
                        if layer.fieldNameIndex(fieldName) != -1:
                            self.msg.show(
                                QApplication.translate( "AutoFieldsDockWidgetPy",
                                    "[Error] The field " ) + fieldName + \
                                QApplication.translate( "AutoFieldsDockWidgetPy",
                                    " already exists in layer " ) + layer.name() + ". " + \
                                QApplication.translate( "AutoFieldsDockWidgetPy",
                                    " If you want to create an AutoField on it, you need to choose it from 'Existing Field' list." ),
                                'warning' )
                        else:
                            res = layer.dataProvider().addAttributes(
                                [newField])
                            if res:
                                layer.updateFields()

                                # Check if fieldName is preserved by the provider after field creation.
                                if layer.fieldNameIndex(fieldName) == -1:
                                    self.msg.show(
                                        QApplication.translate( "AutoFieldsDockWidgetPy",
                                            "[Error] The field " ) + fieldName + \
                                        QApplication.translate( "AutoFieldsDockWidgetPy",
                                            " was probably created with another name by the layer (" ) + \
                                        layer.name() + \
                                        QApplication.translate( "AutoFieldsDockWidgetPy",
                                            ") provider. " ) + \
                                        QApplication.translate( "AutoFieldsDockWidgetPy",
                                            " If you want to create an AutoField on it, you need to choose it from 'Existing Field' list." ),
                                        'warning' )
                                else:

                                    self.doSaveAutoField(
                                        layer, fieldName, expression)

                            else:
                                self.msg.show( QApplication.translate( "AutoFieldsDockWidgetPy",
                                    "[Error] Couldn't create " ) + newField.name() + \
                                    QApplication.translate( "AutoFieldsDockWidgetPy",
                                        " field in " ) + layer.name() + \
                                    QApplication.translate( "AutoFieldsDockWidgetPy", " layer." ),
                                    'warning' )

                # Some fields might have been created, update the field list once
                self.updateFieldList()

            else:
                self.msg.show(
                    QApplication.translate(
                        "AutoFieldsDockWidgetPy",
                        "[Warning] Please first set a name for the new field."
                    ), 'warning')
                return
        else:
            fieldName = self.cboField.currentText()

            for item in self.tblLayers.selectedItems():
                if item.column() == 1:  # It's the layer name item
                    layer = QgsMapLayerRegistry.instance().mapLayer(
                        item.data(Qt.UserRole))
                    self.doSaveAutoField(layer, fieldName, expression)
        Lt = list(set(tab))
        Lt.sort()

    for c_insee, n_couche in Lt:

        #AMORCES_CAD,LIEUDIT,CP.CadastralParcel,SUBFISCAL,CLOTURE,DETAIL_TOPO,HYDRO,VOIE_COMMUNICATION,BU.Building,BORNE_REPERE
        urlWithParams = "url=http://inspire.cadastre.gouv.fr/scpc/" + c_insee + ".wms?contextualWMSLegend=0&crs=EPSG:" + Code_EPSG + "&dpiMode=7&featureCount=10&format=image/png&layers=DETAIL_TOPO&styles=&maxHeight=1024&maxWidth=1280"

        rlayer = QgsRasterLayer(
            urlWithParams,
            'Details_topographiques_' + n_couche + '_' + c_insee, 'wms')

        progress.setText(u'Nom de la commune : ' + n_couche + ' - ' + c_insee)
        progress.setText(u'Validite du flux : %s' % rlayer.isValid())

        QgsMapLayerRegistry.instance().addMapLayer(rlayer)

        if rlayer.isValid() == True:
            iface.messageBar().pushMessage(
                "Information :",
                "Ajout du flux WMS pour la commune : " + n_couche,
                QgsMessageBar.INFO,
                duration=5)
            iface.mapCanvas().refresh()

        else:
            iface.messageBar().pushMessage("Warning :",
                                           "WMS invalide pour la commune : " +
                                           n_couche,
                                           QgsMessageBar.WARNING,
                                           duration=15)
Exemplo n.º 43
0
 def featuresdeleted(self, layerid, featureids):
     layer = QgsMapLayerRegistry.instance().mapLayer(layerid)
     self.reloadselection(layer, deleted=featureids)
     self.canvas.refresh()
Exemplo n.º 44
0
    def __init__(self,
                 parent,
                 iface,
                 autoFieldManager,
                 messageManager,
                 language='en'):
        self.iface = iface
        self.msg = messageManager
        self.language = language
        QDockWidget.__init__(self, parent)
        # Set up the user interface from Designer.
        self.setupUi(self)

        self.autoFieldManager = autoFieldManager
        self.geometryDict = ['points', 'lines', 'polygons']
        self.fieldTypesDict = ['Integer', 'Real', 'String', 'Date']

        self.root = QgsProject.instance().layerTreeRoot()

        # UI stuff that wasn't set/initialized in Qt-Designer
        self.tblLayers.setColumnWidth(0, 24)
        self.tblLayers.setColumnWidth(1, 140)
        self.tblLayers.setColumnWidth(2, 110)
        self.tblLayers.horizontalHeader().setResizeMode(0, QHeaderView.Fixed)
        self.tblLayers.sortItems(1, Qt.AscendingOrder)
        self.cboField.setEnabled(False)
        self.cboFieldType.setItemData(0, QVariant.Int, Qt.UserRole)
        self.cboFieldType.setItemData(1, QVariant.Double, Qt.UserRole)
        self.cboFieldType.setItemData(2, QVariant.String, Qt.UserRole)
        self.cboFieldType.setItemData(3, QVariant.Date, Qt.UserRole)
        self.fieldTypeChanged(self.cboFieldType.currentIndex()
                              )  # Update length/precision controls
        self.btnGroup = QButtonGroup()
        self.btnGroup.addButton(self.optXCoord)
        self.btnGroup.addButton(self.optYCoord)
        self.btnGroup.addButton(self.optLength)
        self.btnGroup.addButton(self.optPerimeter)
        self.btnGroup.addButton(self.optArea)
        self.btnGroup.addButton(self.optDate)
        self.btnGroup.addButton(self.optCustomExpression)
        #self.btnGroup.addButton( self.optSpatialValue )
        self.updateExpressionControls(self.optCustomExpression)

        self.frameFields.setEnabled(False)
        self.frameExpression.setEnabled(False)
        self.populateLayersTable()

        QgsMapLayerRegistry.instance().legendLayersAdded.connect(
            self.populateLayersTable)
        QgsMapLayerRegistry.instance().layersRemoved.connect(
            self.populateLayersTable)
        # Also listen to Layer Tree node position changes
        self.root.addedChildren.connect(self.populateLayersTable)
        self.root.removedChildren.connect(self.populateLayersTable)

        self.tblLayers.itemSelectionChanged.connect(
            self.updateFieldAndExpressionControls)
        self.optNewField.toggled.connect(self.newFieldToggled)
        self.cboField.currentIndexChanged.connect(self.fieldChanged)
        self.cboFieldType.currentIndexChanged.connect(self.fieldTypeChanged)
        self.btnSaveAutoField.clicked.connect(self.saveAutoField)
        self.btnNewCustomExpression.clicked.connect(self.setCustomExpression)
        self.btnGroup.buttonClicked.connect(self.updateExpressionControls)

        self.expressionDlg = None

        # 'List of AutoFields' Tab
        settings = QSettings()
        check = settings.value(self.autoFieldManager.settingsPrefix +
                               "/showOnlyEnabledAutoFields",
                               True,
                               type=bool)
        self.chkOnlyEnabledAutoFields.setChecked(check)
        check = settings.value(self.autoFieldManager.settingsPrefix +
                               "/calculateOnExistingFeatures",
                               True,
                               type=bool)
        self.chkCalculateOnExisting.setChecked(check)
        self.btnRemoveAutoFields.setEnabled(False)
        self.tblAutoFields.sortItems(0, Qt.AscendingOrder)
        self.populateAutoFieldsTable()
        self.autoFieldManager.autoFieldCreated.connect(
            self.populateAutoFieldsTable)
        self.autoFieldManager.autoFieldRemoved.connect(
            self.populateAutoFieldsTable)
        self.autoFieldManager.autoFieldEnabled.connect(
            self.populateAutoFieldsTable)
        self.autoFieldManager.autoFieldDisabled.connect(
            self.populateAutoFieldsTable)
        self.tblAutoFields.itemSelectionChanged.connect(
            self.updateRemoveAutoFieldButton)
        self.chkOnlyEnabledAutoFields.toggled.connect(
            self.saveShowOnlyEnabledPreference)
        self.chkCalculateOnExisting.toggled.connect(
            self.saveCalculateOnExistingPreference)
        self.btnRemoveAutoFields.clicked.connect(self.removeAutoFieldFromTable)

        # Context menu
        self.tblAutoFields.setContextMenuPolicy(Qt.CustomContextMenu)
        self.tblAutoFields.customContextMenuRequested.connect(
            self.openAutoFieldContextMenu)

        # About Tab
        self.btnHelp.clicked.connect(self.openDocumentation)
 def tearDown(self):
     QgsMapLayerRegistry.instance().removeAllMapLayers()
Exemplo n.º 46
0
    def load_template(self, map_settings):
        """Load composer template for merged report.

        Validate it as well. The template needs to have:
        1. QgsComposerMap with id 'impact-map' for merged impact map.
        2. QgsComposerPicture with id 'safe-logo' for InaSAFE logo.
        3. QgsComposerLabel with id 'summary-report' for a summary of two
        impacts.
        4. QgsComposerLabel with id 'aggregation-area' to indicate the area
        of aggregation.
        5. QgsComposerScaleBar with id 'map-scale' for impact map scale.
        6. QgsComposerLegend with id 'map-legend' for impact map legend.
        7. QgsComposerPicture with id 'organisation-logo' for organisation
        logo.
        8. QgsComposerLegend with id 'impact-legend' for map legend.
        9. QgsComposerHTML with id 'merged-report-table' for the merged report.

        :param map_settings: Map settings.
        :type map_settings: QgsMapSettings, QgsMapRenderer

        """
        # Create Composition
        template_composition = TemplateComposition(self.template_path,
                                                   map_settings)

        # Validate the component in the template
        component_ids = [
            'impact-map', 'safe-logo', 'summary-report', 'aggregation-area',
            'map-scale', 'map-legend', 'organisation-logo',
            'merged-report-table'
        ]
        template_composition.component_ids = component_ids
        if len(template_composition.missing_elements) > 0:
            raise ReportCreationError(
                self.tr('Components: %s could not be found' %
                        ', '.join(template_composition.missing_elements)))

        # Prepare map substitution and set to composition
        impact_title = '%s and %s' % (self.first_impact['map_title'],
                                      self.second_impact['map_title'])
        substitution_map = {
            'impact-title': impact_title,
            'hazard-title': self.first_impact['hazard_title'],
            'disclaimer': self.disclaimer
        }
        template_composition.substitution = substitution_map

        # Load Template
        try:
            template_composition.load_template()
        except TemplateLoadingError:
            raise

        # Draw Composition
        # Set InaSAFE logo
        composition = template_composition.composition
        safe_logo = composition.getComposerItemById('safe-logo')
        safe_logo.setPictureFile(self.safe_logo_path)

        # set organisation logo
        org_logo = composition.getComposerItemById('organisation-logo')
        org_logo.setPictureFile(self.organisation_logo_path)

        # Set Map Legend
        legend = composition.getComposerItemById('map-legend')

        if qgis_version() < 20400:
            layers = map_settings.layerSet()
        else:
            layers = map_settings.layers()

        if qgis_version() < 20600:
            legend.model().setLayerSet(layers)
            legend.synchronizeWithModel()
        else:
            root_group = legend.modelV2().rootGroup()

            layer_ids = map_settings.layers()
            for layer_id in layer_ids:
                # noinspection PyUnresolvedReferences
                layer = QgsMapLayerRegistry.instance().mapLayer(layer_id)
                root_group.addLayer(layer)
            legend.synchronizeWithModel()

        return composition
Exemplo n.º 47
0
    def on_legend_click(self, current, column=0):
        "changes menu when user click on legend"
        self.current_group_idx = -1
        name = ''
        self.current_layers = []
        self.info.setText('No group selected')
        for act in self.actions:
            if act.text() in [
                    'checkout', 'update', 'commit', 'view', 'branch',
                    'historize'
            ]:
                act.setVisible(False)
        if current:
            try:  # qgis 2.2
                name = current.text(0)
            except:  #qgis 2.4
                name = current.data()
        # we could look if we have something in selected layers
        # but we prefer impose grouping, otherwize it'll be easy to make errors

        # need to get all layers including subgroups
        rel_map = {}
        for grp, lay in self.iface.legendInterface().groupLayerRelationship():
            rel_map[grp] = lay

        if not name or name not in rel_map:  # not a group
            return

        group_idx = [
            i for i, x in enumerate(self.iface.legendInterface().groups())
            if x == name
        ]
        if len(group_idx) != 1:
            self.info.setText("More than one group with this name")
            self.current_layers = []
            return
        [self.current_group_idx] = group_idx

        replaced = True
        while replaced:
            replaced = False
            for i, item in enumerate(rel_map[name]):
                if item in rel_map:
                    rel_map[name][i:i + 1] = rel_map[item]
                    replaced = True

        self.current_layers = rel_map[name]
        # we should check that the selection is homogeneous
        previous_conn = ()
        for layer_id in self.current_layers:
            layer = QgsMapLayerRegistry.instance().mapLayer(layer_id)
            uri = QgsDataSourceURI(layer.source())
            if previous_conn:
                if (uri.database(), uri.schema()) != previous_conn:
                    self.current_layers = []
                    self.info.setText("Layers don't share db and schema")
                    return
            else:
                previous_conn = (uri.database(), uri.schema())

        if not self.current_layers:
            return

        if not len(previous_conn[0]):
            self.current_layers = []
            self.info.setText("Not versionable")
            return

        layer = QgsMapLayerRegistry.instance().mapLayer(self.current_layers[0])
        uri = QgsDataSourceURI(layer.source())
        selection_type = ''
        if layer.providerType() == "spatialite":
            rev = 0
            try:
                rev = versioning_base.revision(uri.database())
            except:
                self.current_layers = []
                self.info.setText("The selected group is not a working copy")
                return
            self.info.setText(uri.database() + ' rev=' + str(rev))
            selection_type = 'working copy'
        if layer.providerType() == "postgres":
            mtch = re.match(r'(.+)_([^_]+)_rev_(head|\d+)', uri.schema())
            if mtch:
                self.info.setText(uri.database() + ' ' + mtch.group(1) +
                                  ' branch=' + mtch.group(2) + ' rev=' +
                                  mtch.group(3))
                if mtch.group(3) == 'head':
                    selection_type = 'head'
                else:
                    selection_type = 'versioned'
            else:
                # check if it's a working copy
                rev = 0
                try:
                    rev = versioning_base.pg_revision(self.pg_conn_info(),
                                                      uri.schema())
                    selection_type = 'working copy'
                    self.info.setText(uri.database() + ' ' + uri.schema() +
                                      ' rev=' + str(rev))
                except:
                    self.info.setText('Unversioned schema')
                    selection_type = 'unversioned'

        # refresh the available commands
        assert (selection_type)
        if selection_type == 'unversioned':
            for act in self.actions:
                if act.text() == 'historize':
                    act.setVisible(True)
        elif selection_type == 'versioned':
            for act in self.actions:
                if act.text() in ['view', 'branch']:
                    act.setVisible(True)
        elif selection_type == 'head':
            for act in self.actions:
                if act.text() in ['checkout', 'view', 'branch']:
                    act.setVisible(True)
        elif selection_type == 'working copy':
            for act in self.actions:
                if act.text() in ['update', 'commit']:
                    act.setVisible(True)
Exemplo n.º 48
0
 def tearDown(self):
     QgsMapLayerRegistry.instance().addMapLayer(self.vlayer)
     QgsMapLayerRegistry.instance().removeMapLayer(self.vlayer.id())
     super(self.__class__, self).tearDown()
Exemplo n.º 49
0
    def on_click_load(self):

        # default value of the progress bar is set to 0
        self.counter = 0
        self.ui.progressBar.setValue(self.counter)

        # check if the user wants to limit the selection by distinct value
        if self.ui.checkBox.isChecked():

            load_key = self.ui.load_field.currentText()

            # if the data type is not a string
            if self.data_type != str:
                load_key = ast.literal_eval(load_key)

            self.ourList = self.collection.find({self.key: load_key})

        else:
            query_text = self.ui.query_field.currentText().strip()
            if query_text == '':
                query = {}
            else:
                query = ast.literal_eval(query_text)
                if type(query) is not dict:
                    QMessageBox.about(self, "Warning!", "Query must be a dict!")
                    return
            self.ourList = self.collection.find(query)
        self.percent = 100 / float(self.ourList.count())
        # get the first level of attributes, we can modify which fields we want to use
        self.single_return = self.collection.find_one({}, {'geom': 0, 'fibres': 0, 'date': 0})
        # {} , {"geom": 1}
        self.attr_list = self.single_return.keys()

        # list defined for the attributes table
        self.attr_list_new = []
        # list defined for structural access to tables
        self.attr_list_structure = []

        # locate the sub attributes and store them in sub_attr_list
        for attr in self.attr_list:

            # append keys from the first layer
            self.attr_list_new.append(str(attr))
            self.attr_list_structure.append([attr])

            # if the key is a dictionary
            if type(self.single_return[attr]) is dict:

                # find all of the sub keys in the dictionary
                sub_keys_list = self.single_return[attr].keys()

                # search through the list of sub keys
                for sub_key in sub_keys_list:
                    # structural code for ease of access later
                    struct_sub = [attr], [sub_key]

                    # append the sub keys to our main list, define differences
                    self.attr_list_new.append(str(attr) + "." + str(sub_key))
                    # create a structure for ease of access
                    self.attr_list_structure.append(struct_sub)

            else:
                pass
        QMessageBox.about(self, "Info", "Fields are"+ (', '.join(self.attr_list_new)))
        # define the dataLayer type as either Point, LineString or Polygon
        self.dataLayer = QgsVectorLayer(self.geometry_name, self.collection_name, "memory")

        # prepare the layer for the data we will be inputing
        self.dataLayer.startEditing()
        self.layerData = self.dataLayer.dataProvider()

        # create the shapefile attributes based on existing mongoDB field
        for attribute in (self.attr_list_new):
            self.layerData.addAttributes([QgsField(attribute, QVariant.String)])

        # our attribute container
        self.feature = QgsFeature()

        self.feature.initAttributes(len(self.attr_list_new))
        
        for value in self.ourList:
            # print value[self.geom_name]["type"]
            
            # if the user has selected a collection with point geometry
            if value[self.geom_name]["type"] == "Point":

                x_coord = value[self.geom_name]["coordinates"][0]
                y_coord = value[self.geom_name]["coordinates"][1]

                self.populate_attributes(value)

                try:
                    self.feature.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(x_coord, y_coord)))
                except:
                    self.feature.setGeometry(QgsGeometry.fromPoint(QgsPoint(x_coord, y_coord)))

                (res, outFeats) = self.dataLayer.dataProvider().addFeatures([self.feature])

                # update the progress bar
                self.event_progress()

                self.ui.load_collection.setEnabled(False)
                self.ui.listCol.setEnabled(False)

            elif value[self.geom_name]["type"] == "LineString":

                # used to store a list of poly lines
                line_string = []

                # checks the geometry and only imports valid geometry
                if self.check_valid_geom(value):

                    for y in range(len(value[self.geom_name]["coordinates"])):

                        # do not use unless needed, in case there is a multiLineString Object in the DB

                        try:
                            line_string.append(QgsPoint(value[self.geom_name]["coordinates"][y][0],
                                                        value[self.geom_name]["coordinates"][y][1]))
                        except:

                            qgis.utils.iface.messageBar().pushMessage("Error", "Error loading Linestring on {}: {}".format(str(value["_id"]), str(sys.exc_info()[0])), level=Qgis.critical)

                    self.populate_attributes(value)
                    self.feature.setGeometry(QgsGeometry.fromPolyline(line_string))
                    (res, outFeats) = self.dataLayer.dataProvider().addFeatures([self.feature])
                    del line_string[:]

                    # update the progress bar
                    self.event_progress()

                self.ui.load_collection.setEnabled(False)
                self.ui.listCol.setEnabled(False)

            # this deals with Polygon geometry
            elif value[self.geom_name]["type"] == "Polygon":

                # store the polygon points
                poly_shape = []
                # store the line (a poly has multiple lines)
                line_string = []

                # checks the geometry and only imports valid geometry
                if self.check_valid_geom(value):

                    for y in range(len(value[self.geom_name]["coordinates"][0])):

                        try:
                            line_string.append(QgsPoint(value[self.geom_name]["coordinates"][0][y][0],
                                                        value[self.geom_name]["coordinates"][0][y][1]))
                        except:

                            qgis.utils.iface.messageBar().pushMessage("Error", "Error loading Polygon {}: {}".format(str(value["_id"]), str(sys.exc_info()[0])), level=QgsMessageBar.CRITICAL)
                            
                    poly_shape.append(line_string);

                    self.populate_attributes(value)

                    try:
                        ps = QgsGeometry.fromPolygonXY(poly_shape)
                        self.feature.setGeometry(ps)
                    except AttributeError:
                        ps = QgsGeometry.fromPolygon(poly_shape)
                        self.feature.setGeometry(ps)
                    except:

                        qgis.utils.iface.messageBar().pushMessage("Error", "Error on {}: {}".format(str(value["_id"]), str(sys.exc_info()[0])), level=QgsMessageBar.CRITICAL)
                    
                    (res, outFeats) = self.dataLayer.dataProvider().addFeatures([self.feature])
                    del line_string[:]
                    del poly_shape[:]

                    # update the progress bar
                    self.event_progress()

                    self.ui.load_collection.setEnabled(False)
                    self.ui.listCol.setEnabled(False)

            # this deals with Polygon geometry
            elif value[self.geom_name]["type"] == "MultiPolygon":

                # store the polygon points
                poly_shape = []

                # checks the geometry and only imports valid geometry
                if self.check_valid_geom(value):

                    multi_poly_shape = []

                    for multi_shape in value[self.geom_name]["coordinates"]:

                        for shape in multi_shape:

                            each_shape = []

                            for xy in shape:

                                try:
                                    each_shape.append(QgsPoint(xy[0], xy[1]))
                                except:
                                    qgis.utils.iface.messageBar().pushMessage("Error", "Error loading Multipolygon {}: {}".format(str(value["_id"]), str(sys.exc_info()[0])), level=QgsMessageBar.CRITICAL)


                        multi_poly_shape.append(each_shape)

                    # final append at highest level
                    poly_shape.append(multi_poly_shape)

                    self.populate_attributes(value)
                    try:
                        ps = QgsGeometry.fromMultiPolygonXY(poly_shape)
                        self.feature.setGeometry(ps)
                    except AttributeError:
                        ps = QgsGeometry.fromMultiPolygon(poly_shape)
                        self.feature.setGeometry(ps)

                    except:
                        qgis.utils.iface.messageBar().pushMessage("Error", "Error on {}: {}".format(str(value["_id"]), str(sys.exc_info()[0])), level=QgsMessageBar.CRITICAL)

                    (res, outFeats) = self.dataLayer.dataProvider().addFeatures([self.feature])

                    del poly_shape[:]

                    # update the progress bar
                    self.event_progress()

                    self.ui.load_collection.setEnabled(False)
                    self.ui.listCol.setEnabled(False)
            else:

                qgis.utils.iface.messageBar().pushMessage("Error", "Failed to load geometry due to {} being unsupported".format(value[self.geom_name]["type"]), level=QgsMessageBar.CRITICAL)
                    
            self.ui.listCol.setEnabled(True)

        # commits the changes made to the layer and adds the layer to the map
        self.dataLayer.commitChanges()

        # the path we will be writing to is the plugin folder dependant on the layer name
        write_to = str(os.path.abspath(__file__ + "/../../")) + "/" + str(self.collection_name) + ".shp"
        write_error = QgsVectorFileWriter.writeAsVectorFormat(self.dataLayer, write_to, "system", self.dataLayer.crs(),
                                                              "ESRI Shapefile")
        self.dataLayer = QgsVectorLayer(write_to, self.collection_name, "ogr")
        try:
            QgsProject.instance().addMapLayer(self.dataLayer)
        except:
            QgsMapLayerRegistry.instance().addMapLayer(self.dataLayer)
Exemplo n.º 50
0
    def branch(self):
        """create branch and import layers"""
        layer = QgsMapLayerRegistry.instance().mapLayer(self.current_layers[0])
        uri = QgsDataSourceURI(layer.source())
        mtch = re.match(r'(.+)_([^_]+)_rev_(head|\d+)', uri.schema())
        schema = mtch.group(1)
        base_branch = mtch.group(2)
        base_rev = mtch.group(3)
        assert (schema)
        dlg = QDialog()
        dlg.setWindowTitle('Enter branch name')
        layout = QVBoxLayout(dlg)
        button_box = QDialogButtonBox(dlg)
        button_box.setStandardButtons(QDialogButtonBox.Cancel
                                      | QDialogButtonBox.Ok)
        button_box.accepted.connect(dlg.accept)
        button_box.rejected.connect(dlg.reject)

        line_edit = QLineEdit(dlg)
        layout.addWidget(line_edit)
        layout.addWidget(button_box)
        if not dlg.exec_():
            return
        branch = line_edit.text()

        if not branch:
            print 'aborted'
            return

        pcur = versioning_base.Db(psycopg2.connect(self.pg_conn_info()))
        pcur.execute("SELECT * FROM " + schema + ".revisions "
                     "WHERE branch = '" + branch + "'")
        if pcur.fetchone():
            pcur.close()
            QMessageBox.warning(self.iface.mainWindow(), "Warning",
                                "Branch " + branch + ' already exists.')
            return
        pcur.close()

        # get the commit message
        if not self.q_commit_msg_dlg.exec_():
            return
        commit_msg = self.commit_msg_dlg.commitMessage.document().toPlainText()
        if not commit_msg:
            QMessageBox.warning(self.iface.mainWindow(), "Warning",
                                "No commit message, aborting commit")
            print "aborted"
            return
        versioning_base.add_branch(uri.connectionInfo(), schema, branch,
                                   commit_msg, base_branch, base_rev)
        grp_name = branch + ' revision head'
        grp_idx = self.iface.legendInterface().addGroup(grp_name)
        for layer_id in reversed(self.current_layers):
            layer = QgsMapLayerRegistry.instance().mapLayer(layer_id)
            new_uri = QgsDataSourceURI(layer.source())
            new_uri.setDataSource(schema + '_' + branch + '_rev_head',
                                  new_uri.table(), new_uri.geometryColumn(),
                                  new_uri.sql(), new_uri.keyColumn())
            display_name = QgsMapLayerRegistry.instance().mapLayer(
                layer_id).name()

            new_layer = self.iface.addVectorLayer(
                new_uri.uri().replace('()', ''), display_name, 'postgres')
            self.iface.legendInterface().moveLayer(new_layer, grp_idx)
Exemplo n.º 51
0
 def activeLayer(self):
     """Get pointer to the active layer (layer selected in the legend)."""
     # noinspection PyArgumentList
     layers = QgsMapLayerRegistry.instance().mapLayers()
     for item in layers:
         return layers[item]
Exemplo n.º 52
0
    def execute(self):
        """
        Reimplementation of the execute method from the parent class
        """
        QgsMessageLog.logMessage(
            self.tr('Starting ') + self.getName() + self.tr(' Process.'),
            "DSG Tools Plugin", QgsMessageLog.CRITICAL)
        self.startTimeCount()
        try:
            self.setStatus(self.tr('Running'), 3)  #now I'm running!
            self.abstractDb.deleteProcessFlags(
                self.getName())  #erase previous flags
            classesWithElem = self.parameters['Classes']
            if len(classesWithElem) == 0:
                self.setStatus(
                    self.tr('No classes selected!. Nothing to be done.'),
                    1)  #Finished
                QgsMessageLog.logMessage(
                    self.tr('No classes selected! Nothing to be done.'),
                    "DSG Tools Plugin", QgsMessageLog.CRITICAL)
                return 1
            error = False
            for key in classesWithElem:
                # preparation
                classAndGeom = self.classesWithElemDict[key]
                lyr = self.loadLayerBeforeValidationProcess(classAndGeom)
                # specific EPSG search
                parameters = {
                    'tableSchema': classAndGeom['tableSchema'],
                    'tableName': classAndGeom['tableName'],
                    'geometryColumn': classAndGeom['geom']
                }
                srid = self.abstractDb.findEPSG(parameters=parameters)

                # running the process in the temp table
                coverage = self.createUnifiedLayer([lyr])
                result, output = self.runProcessinAlg(coverage)
                self.splitUnifiedLayer(output, [lyr])
                try:
                    QgsMapLayerRegistry.instance().removeMapLayer(
                        coverage.id())
                except:
                    QgsMessageLog.logMessage(
                        self.tr(
                            'Error while trying to remove coverage layer.'),
                        "DSG Tools Plugin", QgsMessageLog.CRITICAL)

                # storing flags
                if len(result) > 0:
                    error = True
                    recordList = []
                    for tupple in result:
                        recordList.append(
                            ('{0}.{1}'.format(classAndGeom['tableSchema'],
                                              classAndGeom['tableName']),
                             tupple[0], self.tr('Cleaning error.'), tupple[1],
                             classAndGeom['geom']))
                    numberOfProblems = self.addFlag(recordList)
                    QgsMessageLog.logMessage(
                        str(numberOfProblems) + self.tr(' feature(s) from ') +
                        classAndGeom['lyrName'] +
                        self.tr(' with cleaning errors. Check flags.'),
                        "DSG Tools Plugin", QgsMessageLog.CRITICAL)
                else:
                    QgsMessageLog.logMessage(
                        self.tr('There are no cleaning errors on ') +
                        classAndGeom['lyrName'] + '.', "DSG Tools Plugin",
                        QgsMessageLog.CRITICAL)
                self.logLayerTime(classAndGeom['lyrName'])
            if error:
                self.setStatus(
                    self.tr('There are cleaning errors. Check log.'),
                    4)  #Finished with errors
            else:
                self.setStatus(self.tr('There are no cleaning errors.'),
                               1)  #Finished
            return 1
        except Exception as e:
            QgsMessageLog.logMessage(':'.join(e.args), "DSG Tools Plugin",
                                     QgsMessageLog.CRITICAL)
            self.finishedWithError()
            return 0
Exemplo n.º 53
0
    def processLoading(self):
        '''
        Load all the layers in QGIS
        and apply corresponding style
        '''
        self.startTime = datetime.now()
        QApplication.setOverrideCursor(Qt.WaitCursor)

        # default style to apply for Cadastre layers
        self.themeDir = unicode(self.dialog.liTheme.currentText())
        if not os.path.exists(
                os.path.join(self.qc.plugin_dir, "styles/%s" % self.themeDir)):
            self.themeDir = self.defaultThemeDir

        # set Cadastre SVG path if not set
        cadastreSvgPath = os.path.join(self.qc.plugin_dir,
                                       "styles/%s/svg" % self.themeDir)
        s = QSettings()
        qgisSvgPaths = s.value("svg/searchPathsForSVG", 10, type=str)
        if not cadastreSvgPath in qgisSvgPaths:
            if qgisSvgPaths:
                qgisSvgPaths = u"%s|%s" % (qgisSvgPaths, cadastreSvgPath)
            else:
                qgisSvgPaths = u"%s" % cadastreSvgPath
            s.setValue("svg/searchPathsForSVG", qgisSvgPaths)
            self.qc.updateLog(
                u"* Le chemin contenant les SVG du plugin Cadastre a été ajouté dans les options de QGIS"
            )

        # Get selected options
        providerName = self.dialog.dbpluginclass.providerName()
        qgisCadastreLayers = []
        self.dialog.schema = unicode(self.dialog.liDbSchema.currentText())
        self.dialog.totalSteps = len(self.qgisCadastreLayerList)

        # Run the loading
        self.updateTimer()
        self.qc.updateLog(u'Chargement des tables :')

        # Get database list of tables
        if self.dialog.dbType == 'postgis':
            schemaSearch = [
                s for s in self.dialog.db.schemas()
                if s.name == self.dialog.schema
            ]
            schemaInst = schemaSearch[0]
            dbTables = self.dialog.db.tables(schemaInst)
        if self.dialog.dbType == 'spatialite':
            dbTables = self.dialog.db.tables()

        # Get commune filter by expression
        communeExpression = self.dialog.communeFilter.text()
        communeFilter = None
        cExp = QgsExpression(communeExpression)
        if not cExp.hasParserError():
            self.qc.updateLog(u'Filtrage à partir des communes : %s' %
                              communeExpression)
            cReq = QgsFeatureRequest(cExp)
            cTableList = [a for a in dbTables if a.name == 'geo_commune']
            cTable = cTableList[0]
            cUniqueCol = 'ogc_fid'
            cSchema = self.dialog.schema
            cGeomCol = 'geom'
            cLayerUri = self.dialog.db.uri()
            cLayerUri.setDataSource(cSchema, cTable.name, cGeomCol, '',
                                    cUniqueCol)
            clayer = QgsVectorLayer(cLayerUri.uri(), 'com', providerName)
            cfeatures = clayer.getFeatures(cReq)
            cids = [a['commune'] for a in cfeatures]
            if len(cids):
                communeFilter = cids
        else:
            self.qc.updateLog(
                u'Filtrage à partir des communes : expression invalide !')

        # Loop throuhg qgisQastreLayerList and load each corresponding table
        for item in self.qgisCadastreLayerList:

            if item['label'] not in self.mainLayers and self.dialog.cbMainLayersOnly.isChecked(
            ):
                continue

            if item.has_key('dbType') and item['dbType'] != self.dialog.dbType:
                continue

            # update progress bar
            self.qc.updateLog(u'* %s' % item['label'])
            self.dialog.step += 1
            self.qc.updateProgressBar()

            # Tables - Get db_manager table instance
            tableList = [a for a in dbTables if a.name == item['table']]
            if len(tableList) == 0 and not item.has_key('isView'):
                self.qc.updateLog(u'  - Aucune table trouvée pour %s' %
                                  item['label'])
                continue

            if tableList:
                table = tableList[0]
                source = table.name
                uniqueField = table.getValidQGisUniqueFields(True)
                if uniqueField:
                    uniqueCol = uniqueField.name
                else:
                    uniqueCol = 'ogc_fid'

            schema = self.dialog.schema

            # View
            if item.has_key('isView'):
                if self.dialog.dbType == 'spatialite':
                    schemaReplace = ''
                else:
                    schemaReplace = '"%s".' % self.dialog.schema
                source = item['table'].replace('schema.', schemaReplace)
                uniqueCol = item['key']
                schema = None

            sql = item['sql']
            geomCol = item['geom']

            if communeFilter:
                communeFilterText = "'" + "', '".join(communeFilter) + "'"
                nschema = ''
                if self.dialog.dbType == 'postgis':
                    nschema = '"%s".' % schema
                if 'subset' in item:
                    subset = item['subset']
                    sql += subset % communeFilterText
                else:
                    itemcol = item['table']
                    if item['table'] == 'geo_label':
                        itemcol = 'ogc_fid'
                    subset = itemcol + '''
                         IN (

                            SELECT b.''' + itemcol + '''
                            FROM  ''' + nschema + item['table'] + ''' b
                            JOIN  ''' + nschema + '''geo_commune c
                            ON ST_Within(b.geom, c.geom)
                            WHERE 2>1
                            AND c.geo_commune IN ( %s )

                        )
                    '''
                    if sql:
                        sql += ' AND '
                    sql += subset % communeFilterText

            # Create vector layer
            alayerUri = self.dialog.db.uri()
            alayerUri.setDataSource(schema, source, geomCol, sql, uniqueCol)

            vlayer = QgsVectorLayer(alayerUri.uri(), item['label'],
                                    providerName)

            # apply style
            qmlPath = os.path.join(
                self.qc.plugin_dir,
                "styles/%s/%s.qml" % (self.themeDir, item['name']))
            if os.path.exists(qmlPath):
                vlayer.loadNamedStyle(qmlPath)

            # append vector layer to the list
            qgisCadastreLayers.append(vlayer)

        self.updateTimer()

        # Get canvas and disable rendering
        from qgis.utils import iface
        canvas = iface.mapCanvas()
        canvas.freeze(True)

        # Add all layers to QGIS registry
        self.qc.updateLog(u'Ajout des couches dans le registre de QGIS')
        QgsMapLayerRegistry.instance().addMapLayers(qgisCadastreLayers)
        self.updateTimer()

        # Create a group "Cadastre" and move all layers into it
        self.qc.updateLog(u'Ajout des couches dans le groupe Cadastre')
        li = self.dialog.iface.legendInterface()
        groups = []
        for group in li.groupLayerRelationship():
            if group[0]:
                groups.append(group[0])
        if u"Cadastre" in groups:
            g1 = self.getGroupIndex(u"Cadastre")
            if not u'Fond' in groups:
                gf = li.addGroup(u'Fond', True, g1)
            else:
                gf = self.getGroupIndex(u'Fond')

            if not u'Étiquettes cadastre' in groups:
                ge = li.addGroup(u'Étiquettes cadastre', True, gf)
            else:
                ge = self.getGroupIndex(u'Étiquettes cadastre')

            if not u'Données cadastre' in groups:
                gd = li.addGroup(u'Données cadastre', True, gf)
            else:
                gd = self.getGroupIndex(u"Données cadastre")
        else:
            g1 = li.addGroup("Cadastre")
            gf = li.addGroup("Fond", True, g1)
            ge = li.addGroup(u'Étiquettes cadastre', True, gf)
            gd = li.addGroup(u'Données cadastre', True, gf)

        for layer in qgisCadastreLayers:
            #~ layer.updateExtents()
            # Get layer options
            qlayer = [
                a for a in self.qgisCadastreLayerList
                if a['label'] == layer.name()
            ]
            if qlayer:
                qlayer = qlayer[0]

                # Enable/Disable layer
                if not qlayer['active']:
                    li.setLayerVisible(layer, False)

                # Move layer to proper group
                if qlayer['group'] == 'E':
                    li.moveLayer(layer, ge)
                elif qlayer['group'] == 'D':
                    li.moveLayer(layer, gd)
                else:
                    li.moveLayer(layer, g1)
            else:
                # Move layer to Cadastre group
                li.moveLayer(layer, g1)

            # Do not expand layer legend
            li.setLayerExpanded(layer, False)

        # Close Cadastre group
        # li.setGroupExpanded(g1, False)

        self.updateTimer()

        # Zoom to full extent
        self.qc.updateLog(u'Zoom sur les couches')
        canvas.zoomToFullExtent()
        canvas.freeze(False)
        canvas.refresh()
        self.updateTimer()

        # progress bar
        self.dialog.step += 1
        self.qc.updateProgressBar()

        # Emit signal
        self.qc.updateLog(u'Mise à jour des outils cadastre')
        self.cadastreLoadingFinished.emit()
        self.updateTimer()

        # Final message
        QApplication.restoreOverrideCursor()
        QMessageBox.information(
            self.dialog, u"Cadastre",
            u"Les données ont bien été chargées dans QGIS")
        self.dialog.pbProcess.setValue(0)

        QApplication.restoreOverrideCursor()
Exemplo n.º 54
0
 def closeEvent(self, evt):
     QgsMapLayerRegistry.instance().layerWasAdded.disconnect(self.mainWidget.layerAdded)
     QgsMapLayerRegistry.instance().layersWillBeRemoved.disconnect(self.mainWidget.layersWillBeRemoved)
     super(AlgorithmDialog, self).closeEvent(evt)
Exemplo n.º 55
0
def run(item, action, mainwindow):
        db = item.database()
        uri = db.uri()
        iface = mainwindow.iface

        quoteId = db.connector.quoteId
        quoteStr = db.connector.quoteString

        # check if the selected item is a topology schema
        isTopoSchema = False

        if not hasattr(item, 'schema'):
            mainwindow.infoBar.pushMessage("Invalid topology", u'Select a topology schema to continue.', QgsMessageBar.INFO, mainwindow.iface.messageTimeout())
            return False

        if item.schema() is not None:
            sql = u"SELECT srid FROM topology.topology WHERE name = %s" % quoteStr(item.schema().name)
            c = db.connector._get_cursor()
            db.connector._execute( c, sql )
            res = db.connector._fetchone( c )
            isTopoSchema = res is not None

        if not isTopoSchema:
            mainwindow.infoBar.pushMessage("Invalid topology", u'Schema "{0}" is not registered in topology.topology.'.format(item.schema().name), QgsMessageBar.WARNING, mainwindow.iface.messageTimeout())
            return False

        if ( res[0] < 0 ):
          mainwindow.infoBar.pushMessage("WARNING", u'Topology "{0}" is registered as having a srid of {1} in topology.topology, we will assume 0 (for unknown)'.format(item.schema().name, res[0]), QgsMessageBar.WARNING, mainwindow.iface.messageTimeout())
          toposrid = '0'
        else:
          toposrid = str(res[0])

        # load layers into the current project
        toponame = item.schema().name
        template_dir = os.path.join(current_path, 'templates')
        registry = QgsMapLayerRegistry.instance()
        legend = iface.legendInterface()

        # do not refresh the canvas until all the layers are added
        prevRenderFlagState = iface.mapCanvas().renderFlag()
        iface.mapCanvas().setRenderFlag( False )
        try:
                supergroup = legend.addGroup(u'Topology "%s"' % toponame, False)
                provider = db.dbplugin().providerName()
                uri = db.uri()

                # FACES
                group = legend.addGroup(u'Faces', False, supergroup)

          # face mbr
                uri.setDataSource(toponame, 'face', 'mbr', '', 'face_id')
                uri.setSrid( toposrid )
                uri.setWkbType( QGis.WKBPolygon )
                layer = QgsVectorLayer(uri.uri(), u'%s.face_mbr' % toponame, provider)
                layer.loadNamedStyle(os.path.join(template_dir, 'face_mbr.qml'))
                registry.addMapLayers([layer])
                legend.moveLayer(layer, group)
                legend.setLayerVisible(layer, False)
                legend.setLayerExpanded(layer, False)
                face_extent = layer.extent()

          # face geometry
                sql = u'SELECT face_id, topology.ST_GetFaceGeometry(%s, face_id) as geom ' \
                      'FROM %s.face WHERE face_id > 0' % (quoteStr(toponame), quoteId(toponame))
                uri.setDataSource('', u'(%s\n)' % sql, 'geom', '', 'face_id')
                uri.setSrid( toposrid )
                uri.setWkbType( QGis.WKBPolygon )
                layer = QgsVectorLayer(uri.uri(), u'%s.face' % toponame, provider)
                layer.setExtent(face_extent)
                layer.loadNamedStyle(os.path.join(template_dir, 'face.qml'))
                registry.addMapLayers([layer])
                legend.moveLayer(layer, group)
                legend.setLayerVisible(layer, False)
                legend.setLayerExpanded(layer, False)

          # face_seed
                sql = u'SELECT face_id, ST_PointOnSurface(topology.ST_GetFaceGeometry(%s, face_id)) as geom ' \
                      'FROM %s.face WHERE face_id > 0' % (quoteStr(toponame), quoteId(toponame))
                uri.setDataSource('', u'(%s)' % sql, 'geom', '', 'face_id')
                uri.setSrid( toposrid )
                uri.setWkbType( QGis.WKBPoint )
                layer = QgsVectorLayer(uri.uri(), u'%s.face_seed' % toponame, provider)
                layer.setExtent(face_extent)
                layer.loadNamedStyle(os.path.join(template_dir, 'face_seed.qml'))
                registry.addMapLayers([layer])
                legend.moveLayer(layer, group)
                legend.setLayerVisible(layer, False)
                legend.setLayerExpanded(layer, False)

          # TODO: add polygon0, polygon1 and polygon2 ?


                # NODES
                group = legend.addGroup(u'Nodes', False, supergroup)

          # node
                uri.setDataSource(toponame, 'node', 'geom', '', 'node_id')
                uri.setSrid( toposrid )
                uri.setWkbType( QGis.WKBPoint )
                layer = QgsVectorLayer(uri.uri(), u'%s.node' % toponame, provider)
                layer.loadNamedStyle(os.path.join(template_dir, 'node.qml'))
                registry.addMapLayers([layer])
                legend.moveLayer(layer, group)
                legend.setLayerVisible(layer, False)
                legend.setLayerExpanded(layer, False)
                node_extent = layer.extent()

          # node labels
                uri.setDataSource(toponame, 'node', 'geom', '', 'node_id')
                uri.setSrid( toposrid )
                uri.setWkbType( QGis.WKBPoint )
                layer = QgsVectorLayer(uri.uri(), u'%s.node_id' % toponame, provider)
                layer.setExtent(node_extent)
                layer.loadNamedStyle(os.path.join(template_dir, 'node_label.qml'))
                registry.addMapLayers([layer])
                legend.moveLayer(layer, group)
                legend.setLayerVisible(layer, False)
                legend.setLayerExpanded(layer, False)

                # EDGES
                group = legend.addGroup(u'Edges', False, supergroup)

          # edge
                uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id')
                uri.setSrid( toposrid )
                uri.setWkbType( QGis.WKBLineString )
                layer = QgsVectorLayer(uri.uri(), u'%s.edge' % toponame, provider)
                registry.addMapLayers([layer])
                legend.moveLayer(layer, group)
                legend.setLayerVisible(layer, False)
                legend.setLayerExpanded(layer, False)
                edge_extent = layer.extent()

          # directed edge
                uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id')
                uri.setSrid( toposrid )
                uri.setWkbType( QGis.WKBLineString )
                layer = QgsVectorLayer(uri.uri(), u'%s.directed_edge' % toponame, provider)
                layer.setExtent(edge_extent)
                layer.loadNamedStyle(os.path.join(template_dir, 'edge.qml'))
                registry.addMapLayers([layer])
                legend.moveLayer(layer, group)
                legend.setLayerVisible(layer, False)
                legend.setLayerExpanded(layer, False)


          # edge labels
                uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id')
                uri.setSrid( toposrid )
                uri.setWkbType( QGis.WKBLineString )
                layer = QgsVectorLayer(uri.uri(), u'%s.edge_id' % toponame, provider)
                layer.setExtent(edge_extent)
                layer.loadNamedStyle(os.path.join(template_dir, 'edge_label.qml'))
                registry.addMapLayers([layer])
                legend.moveLayer(layer, group)
                legend.setLayerVisible(layer, False)
                legend.setLayerExpanded(layer, False)

          # face_left
                uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id')
                uri.setSrid( toposrid )
                uri.setWkbType( QGis.WKBLineString )
                layer = QgsVectorLayer(uri.uri(), u'%s.face_left' % toponame, provider)
                layer.setExtent(edge_extent)
                layer.loadNamedStyle(os.path.join(template_dir, 'face_left.qml'))
                registry.addMapLayers([layer])
                legend.moveLayer(layer, group)
                legend.setLayerVisible(layer, False)
                legend.setLayerExpanded(layer, False)

          # face_right
                uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id')
                uri.setSrid( toposrid )
                uri.setWkbType( QGis.WKBLineString )
                layer = QgsVectorLayer(uri.uri(), u'%s.face_right' % toponame, provider)
                layer.setExtent(edge_extent)
                layer.loadNamedStyle(os.path.join(template_dir, 'face_right.qml'))
                registry.addMapLayers([layer])
                legend.moveLayer(layer, group)
                legend.setLayerVisible(layer, False)
                legend.setLayerExpanded(layer, False)

          # next_left
                uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id')
                uri.setSrid( toposrid )
                uri.setWkbType( QGis.WKBLineString )
                layer = QgsVectorLayer(uri.uri(), u'%s.next_left' % toponame, provider)
                layer.setExtent(edge_extent)
                layer.loadNamedStyle(os.path.join(template_dir, 'next_left.qml'))
                registry.addMapLayers([layer])
                legend.moveLayer(layer, group)
                legend.setLayerVisible(layer, False)
                legend.setLayerExpanded(layer, False)

          # next_right
                uri.setDataSource(toponame, 'edge_data', 'geom', '', 'edge_id')
                uri.setSrid( toposrid )
                uri.setWkbType( QGis.WKBLineString )
                layer = QgsVectorLayer(uri.uri(), u'%s.next_right' % toponame, provider)
                layer.setExtent(edge_extent)
                layer.loadNamedStyle(os.path.join(template_dir, 'next_right.qml'))
                registry.addMapLayers([layer])
                legend.moveLayer(layer, group)
                legend.setLayerVisible(layer, False)
                legend.setLayerExpanded(layer, False)

        finally:

                # Set canvas extent to topology extent, if not yet initialized
                canvas = iface.mapCanvas()
                if ( canvas.fullExtent().isNull() ):
                  ext = node_extent
                  ext.combineExtentWith(edge_extent)
                  # Grow by 1/20 of largest side
                  ext = ext.buffer(max(ext.width(),ext.height())/20)
                  canvas.setExtent(ext)

                # restore canvas render flag
                iface.mapCanvas().setRenderFlag( prevRenderFlagState )

        return True
Exemplo n.º 56
0
 def newProject(self):
     """Create new project."""
     # noinspection PyArgumentList
     QgsMapLayerRegistry.instance().removeAllMapLayers()
Exemplo n.º 57
0
    def test_signalConnection(self):
        # remove all layers
        QgsMapLayerRegistry.instance().removeAllMapLayers()
        # set dependencies and add back layers
        self.pointsLayer = QgsVectorLayer(
            "dbname='%s' table=\"node\" (geom) sql=" % self.fn, "points",
            "spatialite")
        assert (self.pointsLayer.isValid())
        self.linesLayer = QgsVectorLayer(
            "dbname='%s' table=\"section\" (geom) sql=" % self.fn, "lines",
            "spatialite")
        assert (self.linesLayer.isValid())
        self.pointsLayer2 = QgsVectorLayer(
            "dbname='%s' table=\"node2\" (geom) sql=" % self.fn, "_points2",
            "spatialite")
        assert (self.pointsLayer2.isValid())
        self.pointsLayer.setDependencies(
            [QgsMapLayerDependency(self.linesLayer.id())])
        self.pointsLayer2.setDependencies(
            [QgsMapLayerDependency(self.pointsLayer.id())])
        # this should update connections between layers
        QgsMapLayerRegistry.instance().addMapLayers([self.pointsLayer])
        QgsMapLayerRegistry.instance().addMapLayers([self.linesLayer])
        QgsMapLayerRegistry.instance().addMapLayers([self.pointsLayer2])

        ms = QgsMapSettings()
        ms.setOutputSize(QSize(100, 100))
        ms.setExtent(QgsRectangle(0, 0, 1, 1))
        self.assertTrue(ms.hasValidSettings())

        u = QgsSnappingUtils()
        u.setMapSettings(ms)
        cfg = u.config()
        cfg.setMode(QgsSnappingConfig.AdvancedConfiguration)
        cfg.setIndividualLayerSettings(
            self.pointsLayer,
            QgsSnappingConfig.IndividualLayerSettings(True,
                                                      QgsSnappingConfig.Vertex,
                                                      20, QgsTolerance.Pixels))
        cfg.setIndividualLayerSettings(
            self.pointsLayer2,
            QgsSnappingConfig.IndividualLayerSettings(True,
                                                      QgsSnappingConfig.Vertex,
                                                      20, QgsTolerance.Pixels))
        u.setConfig(cfg)
        # add another line
        f = QgsFeature(self.linesLayer.fields())
        f.setFeatureId(4)
        geom = QgsGeometry.fromWkt("LINESTRING(0.5 0.2,0.6 0)")
        f.setGeometry(geom)
        self.linesLayer.startEditing()
        self.linesLayer.addFeatures([f])
        self.linesLayer.commitChanges()
        # check the second snapped point is ok
        m = u.snapToMap(QPoint(75, 100 - 0))
        self.assertTrue(m.isValid())
        self.assertTrue(m.hasVertex())
        self.assertEqual(m.point(), QgsPoint(0.8, 0.0))

        self.pointsLayer.setDependencies([])
        self.pointsLayer2.setDependencies([])
Exemplo n.º 58
0
 def CheckLayer(self,layerpath):
     for lyr in QgsMapLayerRegistry.instance().mapLayers().values():
         if lyr.dataProvider().dataSourceUri() == layerpath:
             return False
     return True
Exemplo n.º 59
0
    def setup_and_run_analysis(self):
        """Execute analysis after the tab is displayed.

        Please check the code in dock.py accept(). It should follow
        approximately the same code.
        """
        self.show_busy()
        # Read user's settings
        self.read_settings()
        # Prepare impact function from wizard dialog user input
        self.impact_function = self.prepare_impact_function()

        # Prepare impact function
        status, message = self.impact_function.prepare()
        # Check status
        if status == PREPARE_FAILED_BAD_INPUT:
            self.hide_busy()
            LOGGER.info(
                tr('The impact function will not be able to run because of the '
                   'inputs.'))
            LOGGER.info(message.to_text())
            send_error_message(self, message)
            return status, message
        if status == PREPARE_FAILED_BAD_CODE:
            self.hide_busy()
            LOGGER.exception(
                tr('The impact function was not able to be prepared because of a '
                   'bug.'))
            LOGGER.info(message.to_text())
            send_error_message(self, message)
            return status, message

        # Start the analysis
        status, message = self.impact_function.run()
        # Check status
        if status == ANALYSIS_FAILED_BAD_INPUT:
            self.hide_busy()
            LOGGER.info(
                tr('The impact function could not run because of the inputs.'))
            LOGGER.info(message.to_text())
            send_error_message(self, message)
            return status, message
        elif status == ANALYSIS_FAILED_BAD_CODE:
            self.hide_busy()
            LOGGER.exception(
                tr('The impact function could not run because of a bug.'))
            LOGGER.exception(message.to_text())
            send_error_message(self, message)
            return status, message

        LOGGER.info(tr('The impact function could run without errors.'))

        # Add result layer to QGIS
        add_impact_layers_to_canvas(self.impact_function, self.parent.iface)

        # Some if-s i.e. zoom, debug, hide exposure
        if self.zoom_to_impact_flag:
            self.iface.zoomToActiveLayer()

        qgis_exposure = (QgsMapLayerRegistry.instance().mapLayer(
            self.parent.exposure_layer.id()))
        if self.hide_exposure_flag:
            legend = self.iface.legendInterface()
            legend.setLayerVisible(qgis_exposure, False)

        # Generate impact report
        error_code, message = generate_impact_report(self.impact_function,
                                                     self.parent.iface)

        if error_code == ImpactReport.REPORT_GENERATION_FAILED:
            self.hide_busy()
            LOGGER.info(tr('The impact report could not be generated.'))
            send_error_message(self, message)
            LOGGER.info(message.to_text())
            return ANALYSIS_FAILED_BAD_CODE, message

        # Generate Impact Map Report
        error_code, message = generate_impact_map_report(
            self.impact_function, self.iface)

        if error_code == ImpactReport.REPORT_GENERATION_FAILED:
            self.hide_busy()
            LOGGER.info(tr('The impact report could not be generated.'))
            send_error_message(self, message)
            LOGGER.info(message.to_text())
            return ANALYSIS_FAILED_BAD_CODE, message

        self.extent.set_last_analysis_extent(
            self.impact_function.analysis_extent, qgis_exposure.crs())

        # Hide busy
        self.hide_busy()
        # Setup gui if analysis is done
        self.setup_gui_analysis_done()
        return ANALYSIS_SUCCESS, None
    def test(self):

        # Skip if GDAL python bindings are not available
        try:
            from osgeo import gdal, ogr
        except:
            return

        version_num = int(gdal.VersionInfo('VERSION_NUM'))
        if version_num < GDAL_COMPUTE_VERSION(1, 11, 0):
            return

        dialog = QgsNewGeoPackageLayerDialog()
        dialog.setProperty("hideDialogs", True)

        mDatabaseEdit = dialog.findChild(QLineEdit, "mDatabaseEdit")
        buttonBox = dialog.findChild(QDialogButtonBox, "buttonBox")
        ok_button = buttonBox.button(QDialogButtonBox.Ok)
        mTableNameEdit = dialog.findChild(QLineEdit, "mTableNameEdit")
        mLayerIdentifierEdit = dialog.findChild(QLineEdit,
                                                "mLayerIdentifierEdit")
        mLayerDescriptionEdit = dialog.findChild(QLineEdit,
                                                 "mLayerDescriptionEdit")
        mFeatureIdColumnEdit = dialog.findChild(QLineEdit,
                                                "mFeatureIdColumnEdit")
        mGeometryTypeBox = dialog.findChild(QComboBox, "mGeometryTypeBox")
        mGeometryColumnEdit = dialog.findChild(QLineEdit,
                                               "mGeometryColumnEdit")
        mFieldNameEdit = dialog.findChild(QLineEdit, "mFieldNameEdit")
        mFieldTypeBox = dialog.findChild(QComboBox, "mFieldTypeBox")
        mFieldLengthEdit = dialog.findChild(QLineEdit, "mFieldLengthEdit")
        mAddAttributeButton = dialog.findChild(QToolButton,
                                               "mAddAttributeButton")
        mRemoveAttributeButton = dialog.findChild(QToolButton,
                                                  "mRemoveAttributeButton")
        mAttributeView = dialog.findChild(QTreeWidget, "mAttributeView")
        dialog.accepted.connect(self.accepted_slot)

        mGeometryTypeBox.setCurrentIndex(
            mGeometryTypeBox.findData(ogr.wkbPoint))
        self.assertEqual(mGeometryTypeBox.currentText(), "Point")

        self.assertFalse(ok_button.isEnabled())

        dbname = os.path.join(self.basetestpath, 'test.gpkg')
        mDatabaseEdit.setText(dbname)
        self.assertEqual(mTableNameEdit.text(), 'test')
        self.assertEqual(mLayerIdentifierEdit.text(), 'test')
        self.assertTrue(ok_button.isEnabled())

        mGeometryColumnEdit.setText('my_geom')
        mFeatureIdColumnEdit.setText('my_fid')

        self.assertFalse(mAddAttributeButton.isEnabled())
        self.assertFalse(mRemoveAttributeButton.isEnabled())

        mFieldNameEdit.setText('strfield')
        self.assertTrue(mAddAttributeButton.isEnabled())
        mFieldLengthEdit.setText('10')
        QTest.mouseClick(mAddAttributeButton, Qt.LeftButton)

        mFieldNameEdit.setText('intfield')
        mFieldTypeBox.setCurrentIndex(mFieldTypeBox.findData('integer'))
        self.assertFalse(mFieldLengthEdit.isEnabled())
        QTest.mouseClick(mAddAttributeButton, Qt.LeftButton)

        mFieldNameEdit.setText('realfield')
        mFieldTypeBox.setCurrentIndex(mFieldTypeBox.findData('real'))
        self.assertFalse(mFieldLengthEdit.isEnabled())
        QTest.mouseClick(mAddAttributeButton, Qt.LeftButton)

        mFieldNameEdit.setText('datefield')
        mFieldTypeBox.setCurrentIndex(mFieldTypeBox.findData('date'))
        self.assertFalse(mFieldLengthEdit.isEnabled())
        QTest.mouseClick(mAddAttributeButton, Qt.LeftButton)

        mFieldNameEdit.setText('datetimefield')
        mFieldTypeBox.setCurrentIndex(mFieldTypeBox.findData('datetime'))
        self.assertFalse(mFieldLengthEdit.isEnabled())
        QTest.mouseClick(mAddAttributeButton, Qt.LeftButton)

        if version_num >= GDAL_COMPUTE_VERSION(2, 0, 0):
            mFieldNameEdit.setText('int64field')
            mFieldTypeBox.setCurrentIndex(mFieldTypeBox.findData('integer64'))
            self.assertFalse(mFieldLengthEdit.isEnabled())
            QTest.mouseClick(mAddAttributeButton, Qt.LeftButton)

        # Add and remove field
        mFieldNameEdit.setText('dummy')
        self.assertFalse(mFieldLengthEdit.isEnabled())
        QTest.mouseClick(mAddAttributeButton, Qt.LeftButton)

        index = mAttributeView.model().index(
            mAttributeView.model().rowCount() - 1, 0)
        mAttributeView.setCurrentIndex(index)

        QTest.mouseClick(mRemoveAttributeButton, Qt.LeftButton)

        self.accepted = False
        QTest.mouseClick(ok_button, Qt.LeftButton)
        self.assertTrue(self.accepted)

        layers = QgsMapLayerRegistry.instance().mapLayers()
        self.assertEqual(len(layers), 1)
        layer = layers[list(layers.keys())[0]]
        self.assertEqual(layer.name(), 'test')
        self.assertEqual(layer.geometryType(), QGis.Point)
        QgsMapLayerRegistry.instance().removeAllMapLayers()

        ds = ogr.Open(dbname)
        lyr = ds.GetLayer(0)
        self.assertEqual(lyr.GetFIDColumn(), 'my_fid')
        self.assertEqual(lyr.GetGeometryColumn(), 'my_geom')
        self.assertEqual(lyr.GetGeomType(), ogr.wkbPoint)
        if version_num >= GDAL_COMPUTE_VERSION(2, 0, 0):
            self.assertEqual(lyr.GetLayerDefn().GetFieldCount(), 6)
        else:
            self.assertEqual(lyr.GetLayerDefn().GetFieldCount(), 5)
        self.assertEqual(lyr.GetLayerDefn().GetFieldDefn(0).GetNameRef(),
                         'strfield')
        self.assertEqual(lyr.GetLayerDefn().GetFieldDefn(0).GetType(),
                         ogr.OFTString)
        # Only GDAL 2.0 recognizes string field width
        if version_num >= GDAL_COMPUTE_VERSION(2, 0, 0):
            self.assertEqual(lyr.GetLayerDefn().GetFieldDefn(0).GetWidth(), 10)
        self.assertEqual(lyr.GetLayerDefn().GetFieldDefn(1).GetNameRef(),
                         'intfield')
        self.assertEqual(lyr.GetLayerDefn().GetFieldDefn(1).GetType(),
                         ogr.OFTInteger)
        self.assertEqual(lyr.GetLayerDefn().GetFieldDefn(1).GetWidth(), 0)
        self.assertEqual(lyr.GetLayerDefn().GetFieldDefn(2).GetNameRef(),
                         'realfield')
        self.assertEqual(lyr.GetLayerDefn().GetFieldDefn(2).GetType(),
                         ogr.OFTReal)
        self.assertEqual(lyr.GetLayerDefn().GetFieldDefn(2).GetWidth(), 0)
        self.assertEqual(lyr.GetLayerDefn().GetFieldDefn(3).GetNameRef(),
                         'datefield')
        self.assertEqual(lyr.GetLayerDefn().GetFieldDefn(3).GetType(),
                         ogr.OFTDate)
        self.assertEqual(lyr.GetLayerDefn().GetFieldDefn(3).GetWidth(), 0)
        self.assertEqual(lyr.GetLayerDefn().GetFieldDefn(4).GetNameRef(),
                         'datetimefield')
        if version_num >= GDAL_COMPUTE_VERSION(2, 0, 0):
            self.assertEqual(lyr.GetLayerDefn().GetFieldDefn(4).GetType(),
                             ogr.OFTDateTime)
        else:
            # There's a bug in OGR 1.11. The field is probably declared as DATETIME in SQL
            # but OGR detects it as OFTDate
            self.assertEqual(lyr.GetLayerDefn().GetFieldDefn(4).GetType(),
                             ogr.OFTDate)
        self.assertEqual(lyr.GetLayerDefn().GetFieldDefn(4).GetWidth(), 0)
        if version_num >= GDAL_COMPUTE_VERSION(2, 0, 0):
            self.assertEqual(lyr.GetLayerDefn().GetFieldDefn(5).GetNameRef(),
                             'int64field')
            self.assertEqual(lyr.GetLayerDefn().GetFieldDefn(5).GetType(),
                             ogr.OFTInteger64)
            self.assertEqual(lyr.GetLayerDefn().GetFieldDefn(5).GetWidth(), 0)
        ds = None

        # Try re-adding with different table. It should ask if we want to
        # overwrite the DB, and we'll implicitly answer cancel, hence failure
        mTableNameEdit.setText('table2')

        self.accepted = False
        QTest.mouseClick(ok_button, Qt.LeftButton)
        self.assertFalse(self.accepted)

        # Retry, and ask to keep the DB
        self.accepted = False
        dialog.setProperty('question_existing_db_answer_add_new_layer', True)
        QTest.mouseClick(ok_button, Qt.LeftButton)
        dialog.setProperty('question_existing_db_answer_add_new_layer', None)
        self.assertTrue(self.accepted)

        QgsMapLayerRegistry.instance().removeAllMapLayers()
        ds = ogr.Open(dbname)
        self.assertEqual(ds.GetLayerCount(), 2)
        ds = None

        # Retry, and ask to overwrite the DB
        self.accepted = False
        dialog.setProperty('question_existing_db_answer_overwrite', True)
        QTest.mouseClick(ok_button, Qt.LeftButton)
        dialog.setProperty('question_existing_db_answer_overwrite', None)
        self.assertTrue(self.accepted)

        QgsMapLayerRegistry.instance().removeAllMapLayers()
        ds = ogr.Open(dbname)
        self.assertEqual(ds.GetLayerCount(), 1)
        ds = None

        # Try re-adding with same parameters. It should ask if we want to
        # overwrite the layer, and we'll implicitly answer no, hence failure
        # since it already exists with that name
        self.accepted = False
        dialog.setProperty('question_existing_db_answer_add_new_layer', True)
        QTest.mouseClick(ok_button, Qt.LeftButton)
        dialog.setProperty('question_existing_db_answer_add_new_layer', None)
        self.assertFalse(self.accepted)

        # Now answer yes, and change a few things
        mLayerIdentifierEdit.setText('my_identifier')
        mLayerDescriptionEdit.setText('my_description')
        dialog.setProperty('question_existing_db_answer_add_new_layer', True)
        dialog.setProperty('question_existing_layer_answer_overwrite', True)
        self.accepted = False
        QTest.mouseClick(ok_button, Qt.LeftButton)
        dialog.setProperty('question_existing_db_answer_add_new_layer', None)
        dialog.setProperty('question_existing_layer_answer_overwrite', None)
        self.assertTrue(self.accepted)

        # Only check with OGR 2.0 since the IDENTIFIER and DESCRIPTION creation options don't exist in OGR 1.11
        if version_num >= GDAL_COMPUTE_VERSION(2, 0, 0):
            layers = QgsMapLayerRegistry.instance().mapLayers()
            self.assertEqual(len(layers), 1)
            layer = layers[list(layers.keys())[0]]
            self.assertEqual(layer.name(), 'my_identifier')
            QgsMapLayerRegistry.instance().removeAllMapLayers()

            ds = ogr.Open(dbname)
            sql_lyr = ds.ExecuteSQL('SELECT * FROM gpkg_contents')
            self.assertEqual(sql_lyr.GetFeatureCount(), 1)
            f = sql_lyr.GetNextFeature()
            identifier = f.GetField('identifier')
            description = f.GetField('description')
            f = None
            ds.ReleaseResultSet(sql_lyr)
            ds = None
            self.assertEqual(identifier, 'my_identifier')
            self.assertEqual(description, 'my_description')
        else:
            QgsMapLayerRegistry.instance().removeAllMapLayers()

        # Try invalid path
        mDatabaseEdit.setText('/this/is/invalid/test.gpkg')
        self.accepted = False
        QTest.mouseClick(ok_button, Qt.LeftButton)
        self.assertFalse(self.accepted)