Exemplo n.º 1
0
    def draw_impact_title(self, top_offset):
        """Draw the map subtitle - obtained from the impact layer keywords.

        :param top_offset: Vertical offset at which the logo should be drawn.
        :type top_offset: int

        :returns: The height of the label as rendered.
        :rtype: float
        """
        LOGGER.debug('InaSAFE Map drawImpactTitle called')
        title = self.map_title()
        if title is None:
            title = ''
        font_size = 20
        font_weight = QtGui.QFont.Bold
        italics_flag = False
        font = QtGui.QFont(
            'verdana', font_size, font_weight, italics_flag)
        label = QgsComposerLabel(self.composition)
        label.setFont(font)
        heading = title
        label.setText(heading)
        label_width = self.page_width - (self.page_margin * 2)
        label_height = 12
        label.setItemPosition(
            self.page_margin, top_offset, label_width, label_height)
        label.setFrameEnabled(self.show_frames)
        self.composition.addItem(label)
        return label_height
Exemplo n.º 2
0
    def draw_impact_title(self, top_offset):
        """Draw the map subtitle - obtained from the impact layer keywords.

        :param top_offset: Vertical offset at which the logo should be drawn.
        :type top_offset: int

        :returns: The height of the label as rendered.
        :rtype: float
        """
        LOGGER.debug('InaSAFE Map drawImpactTitle called')
        myTitle = self.map_title()
        if myTitle is None:
            myTitle = ''
        myFontSize = 20
        myFontWeight = QtGui.QFont.Bold
        myItalicsFlag = False
        myFont = QtGui.QFont(
            'verdana', myFontSize, myFontWeight, myItalicsFlag)
        myLabel = QgsComposerLabel(self.composition)
        myLabel.setFont(myFont)
        myHeading = myTitle
        myLabel.setText(myHeading)
        myLabelWidth = self.pageWidth - (self.pageMargin * 2)
        myLabelHeight = 12
        myLabel.setItemPosition(
            self.pageMargin, top_offset, myLabelWidth, myLabelHeight)
        myLabel.setFrameEnabled(self.showFramesFlag)
        self.composition.addItem(myLabel)
        return myLabelHeight
Exemplo n.º 3
0
    def drawImpactTitle(self, theTopOffset):
        """Draw the map subtitle - obtained from the impact layer keywords.

        Args:
            theTopOffset - vertical offset at which to begin drawing
        Returns:
            float - the height of the label as rendered
        Raises:
            None
        """
        LOGGER.debug("InaSAFE Map drawImpactTitle called")
        myTitle = self.getMapTitle()
        if myTitle is None:
            myTitle = ""
        myFontSize = 20
        myFontWeight = QtGui.QFont.Bold
        myItalicsFlag = False
        myFont = QtGui.QFont("verdana", myFontSize, myFontWeight, myItalicsFlag)
        myLabel = QgsComposerLabel(self.composition)
        myLabel.setFont(myFont)
        myHeading = myTitle
        myLabel.setText(myHeading)
        myLabelWidth = self.pageWidth - (self.pageMargin * 2)
        myLabelHeight = 12
        myLabel.setItemPosition(self.pageMargin, theTopOffset, myLabelWidth, myLabelHeight)
        myLabel.setFrame(self.showFramesFlag)
        self.composition.addItem(myLabel)
        return myLabelHeight
Exemplo n.º 4
0
    def testCase(self):
        self.TEST_DATA_DIR = unitTestDataPath()
        vectorFileInfo = QFileInfo( self.TEST_DATA_DIR + "/france_parts.shp")
        mVectorLayer = QgsVectorLayer( vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr" )

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

        # create composition with composer map
        mMapRenderer = QgsMapRenderer()
        layerStringList = []
        layerStringList.append( mVectorLayer.id() )
        mMapRenderer.setLayerSet( layerStringList )
        mMapRenderer.setProjectionsEnabled( True )
        mMapRenderer.setMapUnits( QGis.Meters )

        # select epsg:2154
        crs = QgsCoordinateReferenceSystem()
        crs.createFromSrid( 2154 )
        mMapRenderer.setDestinationCrs( crs )

        self.mComposition = QgsComposition( mMapRenderer )
        self.mComposition.setPaperSize( 297, 210 )

        # fix the renderer, fill with green
        props = { "color": "0,127,0" }
        fillSymbol = QgsFillSymbolV2.createSimple( props )
        renderer = QgsSingleSymbolRendererV2( fillSymbol )
        mVectorLayer.setRendererV2( renderer )

        # the atlas map
        self.mAtlasMap = QgsComposerMap( self.mComposition, 20, 20, 130, 130 )
        self.mAtlasMap.setFrameEnabled( True )
        self.mComposition.addComposerMap( self.mAtlasMap )

        # the atlas
        self.mAtlas = self.mComposition.atlasComposition()
        self.mAtlas.setCoverageLayer( mVectorLayer )
        self.mAtlas.setEnabled( True )
        self.mComposition.setAtlasMode( QgsComposition.ExportAtlas )

        # an overview
        mOverview = QgsComposerMap( self.mComposition, 180, 20, 50, 50 )
        mOverview.setFrameEnabled( True )
        mOverview.setOverviewFrameMap( self.mAtlasMap.id() )
        self.mComposition.addComposerMap( mOverview )
        nextent = QgsRectangle( 49670.718, 6415139.086, 699672.519, 7065140.887 )
        mOverview.setNewExtent( nextent )

        # set the fill symbol of the overview map
        props2 = { "color": "127,0,0,127" }
        fillSymbol2 = QgsFillSymbolV2.createSimple( props2 )
        mOverview.setOverviewFrameMapSymbol( fillSymbol2 )

        # header label
        self.mLabel1 = QgsComposerLabel( self.mComposition )
        self.mComposition.addComposerLabel( self.mLabel1 )
        self.mLabel1.setText( "[% \"NAME_1\" %] area" )
        self.mLabel1.setFont( QgsFontUtils.getStandardTestFont() )
        self.mLabel1.adjustSizeToText()
        self.mLabel1.setSceneRect( QRectF( 150, 5, 60, 15 ) )

        qWarning( "header label font: %s exactMatch:%s" % ( self.mLabel1.font().toString(), self.mLabel1.font().exactMatch() ) )

        # feature number label
        self.mLabel2 = QgsComposerLabel( self.mComposition )
        self.mComposition.addComposerLabel( self.mLabel2 )
        self.mLabel2.setText( "# [%$feature || ' / ' || $numfeatures%]" )
        self.mLabel2.setFont( QgsFontUtils.getStandardTestFont() )
        self.mLabel2.adjustSizeToText()
        self.mLabel2.setSceneRect( QRectF( 150, 200, 60, 15 ) )

        qWarning( "feature number label font: %s exactMatch:%s" % ( self.mLabel2.font().toString(), self.mLabel2.font().exactMatch() ) )

        self.filename_test()
        self.autoscale_render_test()
        self.autoscale_render_test_old_api()
        self.fixedscale_render_test()
        self.predefinedscales_render_test()
        self.hidden_render_test()
Exemplo n.º 5
0
class TestQgsAtlasComposition(unittest.TestCase):

    def testCase(self):
        self.TEST_DATA_DIR = unitTestDataPath()
        tmppath = tempfile.mkdtemp()
        for file in glob.glob(os.path.join(self.TEST_DATA_DIR, 'france_parts.*')):
            shutil.copy(os.path.join(self.TEST_DATA_DIR, file), tmppath)
        vectorFileInfo = QFileInfo(tmppath + "/france_parts.shp")
        mVectorLayer = QgsVectorLayer(vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr")

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

        # create composition with composer map
        self.mapSettings = QgsMapSettings()
        layerStringList = []
        layerStringList.append(mVectorLayer.id())
        self.mapSettings.setLayers(layerStringList)
        self.mapSettings.setCrsTransformEnabled(True)
        self.mapSettings.setMapUnits(QGis.Meters)

        # select epsg:2154
        crs = QgsCoordinateReferenceSystem()
        crs.createFromSrid(2154)
        self.mapSettings.setDestinationCrs(crs)

        self.mComposition = QgsComposition(self.mapSettings)
        self.mComposition.setPaperSize(297, 210)

        # fix the renderer, fill with green
        props = {"color": "0,127,0"}
        fillSymbol = QgsFillSymbolV2.createSimple(props)
        renderer = QgsSingleSymbolRendererV2(fillSymbol)
        mVectorLayer.setRendererV2(renderer)

        # the atlas map
        self.mAtlasMap = QgsComposerMap(self.mComposition, 20, 20, 130, 130)
        self.mAtlasMap.setFrameEnabled(True)
        self.mComposition.addComposerMap(self.mAtlasMap)

        # the atlas
        self.mAtlas = self.mComposition.atlasComposition()
        self.mAtlas.setCoverageLayer(mVectorLayer)
        self.mAtlas.setEnabled(True)
        self.mComposition.setAtlasMode(QgsComposition.ExportAtlas)

        # an overview
        mOverview = QgsComposerMap(self.mComposition, 180, 20, 50, 50)
        mOverview.setFrameEnabled(True)
        mOverview.setOverviewFrameMap(self.mAtlasMap.id())
        self.mComposition.addComposerMap(mOverview)
        nextent = QgsRectangle(49670.718, 6415139.086, 699672.519, 7065140.887)
        mOverview.setNewExtent(nextent)

        # set the fill symbol of the overview map
        props2 = {"color": "127,0,0,127"}
        fillSymbol2 = QgsFillSymbolV2.createSimple(props2)
        mOverview.setOverviewFrameMapSymbol(fillSymbol2)

        # header label
        self.mLabel1 = QgsComposerLabel(self.mComposition)
        self.mComposition.addComposerLabel(self.mLabel1)
        self.mLabel1.setText("[% \"NAME_1\" %] area")
        self.mLabel1.setFont(QgsFontUtils.getStandardTestFont())
        self.mLabel1.adjustSizeToText()
        self.mLabel1.setSceneRect(QRectF(150, 5, 60, 15))

        qWarning(
            "header label font: %s exactMatch:%s" % (self.mLabel1.font().toString(), self.mLabel1.font().exactMatch()))

        # feature number label
        self.mLabel2 = QgsComposerLabel(self.mComposition)
        self.mComposition.addComposerLabel(self.mLabel2)
        self.mLabel2.setText("# [%$feature || ' / ' || $numfeatures%]")
        self.mLabel2.setFont(QgsFontUtils.getStandardTestFont())
        self.mLabel2.adjustSizeToText()
        self.mLabel2.setSceneRect(QRectF(150, 200, 60, 15))

        qWarning("feature number label font: %s exactMatch:%s" % (
                 self.mLabel2.font().toString(), self.mLabel2.font().exactMatch()))

        self.filename_test()
        self.autoscale_render_test()
        self.autoscale_render_test_old_api()
        self.fixedscale_render_test()
        self.predefinedscales_render_test()
        self.hidden_render_test()
        self.legend_test()

        shutil.rmtree(tmppath, True)

    def filename_test(self):
        self.mAtlas.setFilenamePattern("'output_' || $feature")
        self.mAtlas.beginRender()
        for i in range(0, self.mAtlas.numFeatures()):
            self.mAtlas.prepareForFeature(i)
            expected = "output_%d" % (i + 1)
            assert self.mAtlas.currentFilename() == expected
        self.mAtlas.endRender()

    def autoscale_render_test(self):
        self.mAtlasMap.setAtlasDriven(True)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Auto)
        self.mAtlasMap.setAtlasMargin(0.10)

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_autoscale%d' % (i + 1), self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

        self.mAtlasMap.setAtlasDriven(False)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
        self.mAtlasMap.setAtlasMargin(0)

    def autoscale_render_test_old_api(self):
        self.mAtlas.setComposerMap(self.mAtlasMap)
        self.mAtlas.setFixedScale(False)
        self.mAtlas.setMargin(0.10)

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_autoscale_old_api%d' % (i + 1), self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

        self.mAtlas.setFixedScale(True)
        self.mAtlas.setMargin(0)
        self.mAtlas.setComposerMap(None)
        self.mAtlasMap.setAtlasDriven(False)

    def fixedscale_render_test(self):
        self.mAtlasMap.setNewExtent(QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
        self.mAtlasMap.setAtlasDriven(True)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_fixedscale%d' % (i + 1), self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

    def predefinedscales_render_test(self):
        self.mAtlasMap.setNewExtent(QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
        self.mAtlasMap.setAtlasDriven(True)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Predefined)

        scales = [1800000, 5000000]
        self.mAtlas.setPredefinedScales(scales)
        for i, s in enumerate(self.mAtlas.predefinedScales()):
            assert s == scales[i]

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_predefinedscales%d' % (i + 1), self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

    def hidden_render_test(self):
        self.mAtlasMap.setNewExtent(QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
        self.mAtlas.setHideCoverage(True)

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_hiding%d' % (i + 1), self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

        self.mAtlas.setHideCoverage(False)

    def sorting_render_test(self):
        self.mAtlasMap.setNewExtent(QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
        self.mAtlas.setHideCoverage(False)

        self.mAtlas.setSortFeatures(True)
        self.mAtlas.setSortKeyAttributeIndex(4)  # departement name
        self.mAtlas.setSortAscending(False)

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_sorting%d' % (i + 1), self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

    def filtering_render_test(self):
        self.mAtlasMap.setNewExtent(QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
        self.mAtlas.setHideCoverage(False)

        self.mAtlas.setSortFeatures(False)

        self.mAtlas.setFilterFeatures(True)
        self.mAtlas.setFeatureFilter("substr(NAME_1,1,1)='P'")  # select only 'Pays de la loire'

        self.mAtlas.beginRender()

        for i in range(0, 1):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_filtering%d' % (i + 1), self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

    def legend_test(self):
        self.mAtlasMap.setAtlasDriven(True)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Auto)
        self.mAtlasMap.setAtlasMargin(0.10)

        # add a point layer
        ptLayer = QgsVectorLayer("Point?crs=epsg:4326&field=attr:int(1)&field=label:string(20)", "points", "memory")

        pr = ptLayer.dataProvider()
        f1 = QgsFeature(1)
        f1.initAttributes(2)
        f1.setAttribute(0, 1)
        f1.setAttribute(1, "Test label 1")
        f1.setGeometry(QgsGeometry.fromPoint(QgsPoint(-0.638, 48.954)))
        f2 = QgsFeature(2)
        f2.initAttributes(2)
        f2.setAttribute(0, 2)
        f2.setAttribute(1, "Test label 2")
        f2.setGeometry(QgsGeometry.fromPoint(QgsPoint(-1.682, 48.550)))
        pr.addFeatures([f1, f2])

        # categorized symbology
        r = QgsCategorizedSymbolRendererV2("attr", [QgsRendererCategoryV2(1, QgsMarkerSymbolV2.createSimple({"color": "255,0,0"}), "red"),
                                                    QgsRendererCategoryV2(2, QgsMarkerSymbolV2.createSimple({"color": "0,0,255"}), "blue")])
        ptLayer.setRendererV2(r)

        QgsMapLayerRegistry.instance().addMapLayer(ptLayer)

        # add the point layer to the map settings
        layers = self.mapSettings.layers()
        layers = [ptLayer.id()] + layers
        self.mapSettings.setLayers(layers)

        # add a legend
        legend = QgsComposerLegend(self.mComposition)
        legend.moveBy(200, 100)
        # sets the legend filter parameter
        legend.setComposerMap(self.mAtlasMap)
        legend.setLegendFilterOutAtlas(True)
        self.mComposition.addComposerLegend(legend)

        self.mAtlas.beginRender()

        self.mAtlas.prepareForFeature(0)
        self.mLabel1.adjustSizeToText()

        checker = QgsCompositionChecker('atlas_legend', self.mComposition)
        myTestResult, myMessage = checker.testComposition()
        assert myTestResult

        self.mAtlas.endRender()

        # restore state
        self.mapSettings.setLayers([layers[1]])
        self.mComposition.removeComposerItem(legend)
        QgsMapLayerRegistry.instance().removeMapLayer(ptLayer.id())
Exemplo n.º 6
0
    def testCase(self):
        self.TEST_DATA_DIR = unitTestDataPath()
        tmppath = tempfile.mkdtemp()
        for file in glob.glob(os.path.join(self.TEST_DATA_DIR, 'france_parts.*')):
            shutil.copy(os.path.join(self.TEST_DATA_DIR, file), tmppath)
        vectorFileInfo = QFileInfo(tmppath + "/france_parts.shp")
        mVectorLayer = QgsVectorLayer(vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr")

        QgsProject.instance().addMapLayers([mVectorLayer])
        self.layers = [mVectorLayer]

        # create composition with composer map

        # select epsg:2154
        crs = QgsCoordinateReferenceSystem()
        crs.createFromSrid(2154)
        QgsProject.instance().setCrs(crs)

        self.mComposition = QgsComposition(QgsProject.instance())
        self.mComposition.setPaperSize(297, 210)

        # fix the renderer, fill with green
        props = {"color": "0,127,0"}
        fillSymbol = QgsFillSymbol.createSimple(props)
        renderer = QgsSingleSymbolRenderer(fillSymbol)
        mVectorLayer.setRenderer(renderer)

        # the atlas map
        self.mAtlasMap = QgsComposerMap(self.mComposition, 20, 20, 130, 130)
        self.mAtlasMap.setFrameEnabled(True)
        self.mAtlasMap.setLayers([mVectorLayer])
        self.mComposition.addComposerMap(self.mAtlasMap)

        # the atlas
        self.mAtlas = self.mComposition.atlasComposition()
        self.mAtlas.setCoverageLayer(mVectorLayer)
        self.mAtlas.setEnabled(True)
        self.mComposition.setAtlasMode(QgsComposition.ExportAtlas)

        # an overview
        self.mOverview = QgsComposerMap(self.mComposition, 180, 20, 50, 50)
        self.mOverview.setFrameEnabled(True)
        self.mOverview.overview().setFrameMap(self.mAtlasMap.id())
        self.mOverview.setLayers([mVectorLayer])
        self.mComposition.addComposerMap(self.mOverview)
        nextent = QgsRectangle(49670.718, 6415139.086, 699672.519, 7065140.887)
        self.mOverview.setNewExtent(nextent)

        # set the fill symbol of the overview map
        props2 = {"color": "127,0,0,127"}
        fillSymbol2 = QgsFillSymbol.createSimple(props2)
        self.mOverview.overview().setFrameSymbol(fillSymbol2)

        # header label
        self.mLabel1 = QgsComposerLabel(self.mComposition)
        self.mComposition.addComposerLabel(self.mLabel1)
        self.mLabel1.setText("[% \"NAME_1\" %] area")
        self.mLabel1.setFont(QgsFontUtils.getStandardTestFont())
        self.mLabel1.adjustSizeToText()
        self.mLabel1.setSceneRect(QRectF(150, 5, 60, 15))

        qWarning(
            "header label font: %s exactMatch:%s" % (self.mLabel1.font().toString(), self.mLabel1.font().exactMatch()))

        # feature number label
        self.mLabel2 = QgsComposerLabel(self.mComposition)
        self.mComposition.addComposerLabel(self.mLabel2)
        self.mLabel2.setText("# [%@atlas_featurenumber || ' / ' || @atlas_totalfeatures%]")
        self.mLabel2.setFont(QgsFontUtils.getStandardTestFont())
        self.mLabel2.adjustSizeToText()
        self.mLabel2.setSceneRect(QRectF(150, 200, 60, 15))

        qWarning("feature number label font: %s exactMatch:%s" % (
                 self.mLabel2.font().toString(), self.mLabel2.font().exactMatch()))

        self.filename_test()
        self.autoscale_render_test()
        self.fixedscale_render_test()
        self.predefinedscales_render_test()
        self.hidden_render_test()
        self.legend_test()

        shutil.rmtree(tmppath, True)
Exemplo n.º 7
0
    def testCase(self):
        self.TEST_DATA_DIR = unitTestDataPath()
        tmppath = tempfile.mkdtemp()
        for file in glob.glob(
                os.path.join(self.TEST_DATA_DIR, 'france_parts.*')):
            shutil.copy(os.path.join(self.TEST_DATA_DIR, file), tmppath)
        vectorFileInfo = QFileInfo(tmppath + "/france_parts.shp")
        mVectorLayer = QgsVectorLayer(vectorFileInfo.filePath(),
                                      vectorFileInfo.completeBaseName(), "ogr")

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

        # create composition with composer map
        self.mapSettings = QgsMapSettings()
        layerStringList = []
        layerStringList.append(mVectorLayer.id())
        self.mapSettings.setLayers(layerStringList)
        self.mapSettings.setCrsTransformEnabled(True)
        self.mapSettings.setMapUnits(QgsUnitTypes.DistanceMeters)

        # select epsg:2154
        crs = QgsCoordinateReferenceSystem()
        crs.createFromSrid(2154)
        self.mapSettings.setDestinationCrs(crs)

        self.mComposition = QgsComposition(self.mapSettings)
        self.mComposition.setPaperSize(297, 210)

        # fix the renderer, fill with green
        props = {"color": "0,127,0"}
        fillSymbol = QgsFillSymbol.createSimple(props)
        renderer = QgsSingleSymbolRenderer(fillSymbol)
        mVectorLayer.setRenderer(renderer)

        # the atlas map
        self.mAtlasMap = QgsComposerMap(self.mComposition, 20, 20, 130, 130)
        self.mAtlasMap.setFrameEnabled(True)
        self.mComposition.addComposerMap(self.mAtlasMap)

        # the atlas
        self.mAtlas = self.mComposition.atlasComposition()
        self.mAtlas.setCoverageLayer(mVectorLayer)
        self.mAtlas.setEnabled(True)
        self.mComposition.setAtlasMode(QgsComposition.ExportAtlas)

        # an overview
        mOverview = QgsComposerMap(self.mComposition, 180, 20, 50, 50)
        mOverview.setFrameEnabled(True)
        mOverview.overview().setFrameMap(self.mAtlasMap.id())
        self.mComposition.addComposerMap(mOverview)
        nextent = QgsRectangle(49670.718, 6415139.086, 699672.519, 7065140.887)
        mOverview.setNewExtent(nextent)

        # set the fill symbol of the overview map
        props2 = {"color": "127,0,0,127"}
        fillSymbol2 = QgsFillSymbol.createSimple(props2)
        mOverview.overview().setFrameSymbol(fillSymbol2)

        # header label
        self.mLabel1 = QgsComposerLabel(self.mComposition)
        self.mComposition.addComposerLabel(self.mLabel1)
        self.mLabel1.setText("[% \"NAME_1\" %] area")
        self.mLabel1.setFont(QgsFontUtils.getStandardTestFont())
        self.mLabel1.adjustSizeToText()
        self.mLabel1.setSceneRect(QRectF(150, 5, 60, 15))

        qWarning(
            "header label font: %s exactMatch:%s" %
            (self.mLabel1.font().toString(), self.mLabel1.font().exactMatch()))

        # feature number label
        self.mLabel2 = QgsComposerLabel(self.mComposition)
        self.mComposition.addComposerLabel(self.mLabel2)
        self.mLabel2.setText(
            "# [%@atlas_featurenumber || ' / ' || @atlas_totalfeatures%]")
        self.mLabel2.setFont(QgsFontUtils.getStandardTestFont())
        self.mLabel2.adjustSizeToText()
        self.mLabel2.setSceneRect(QRectF(150, 200, 60, 15))

        qWarning(
            "feature number label font: %s exactMatch:%s" %
            (self.mLabel2.font().toString(), self.mLabel2.font().exactMatch()))

        self.filename_test()
        self.autoscale_render_test()
        self.fixedscale_render_test()
        self.predefinedscales_render_test()
        self.hidden_render_test()
        self.legend_test()

        shutil.rmtree(tmppath, True)
Exemplo n.º 8
0
    def drawHostAndTime(self, theTopOffset):
        """Add a disclaimer to the composition.

        Args:
            theTopOffset - vertical offset at which to begin drawing
        Returns:
            None
        Raises:
            None
        """
        LOGGER.debug("InaSAFE Map drawDisclaimer called")
        # elapsed_time: 11.612545
        # user: timlinux
        # host_name: ultrabook
        # time_stamp: 2012-10-13_23:10:31
        # myUser = self.keywordIO.readKeywords(self.layer, 'user')
        # myHost = self.keywordIO.readKeywords(self.layer, 'host_name')
        myDateTime = self.keywordIO.readKeywords(self.layer, "time_stamp")
        myTokens = myDateTime.split("_")
        myDate = myTokens[0]
        myTime = myTokens[1]
        # myElapsedTime = self.keywordIO.readKeywords(self.layer,
        #                                            'elapsed_time')
        # myElapsedTime = humaniseSeconds(myElapsedTime)
        myLongVersion = get_version()
        myTokens = myLongVersion.split(".")
        myVersion = "%s.%s.%s" % (myTokens[0], myTokens[1], myTokens[2])
        myLabelText = (
            self.tr(
                "Date and time of assessment: %1 %2\n"
                "Special note: This assessment is a guide - we strongly recommend "
                "that you ground truth the results shown here before deploying "
                "resources and / or personnel.\n"
                "Assessment carried out using InaSAFE release %3 (QGIS "
                "plugin version)."
            )
            .arg(myDate)
            .arg(myTime)
            .arg(myVersion)
        )
        myFontSize = 6
        myFontWeight = QtGui.QFont.Normal
        myItalicsFlag = True
        myFont = QtGui.QFont("verdana", myFontSize, myFontWeight, myItalicsFlag)
        myLabel = QgsComposerLabel(self.composition)
        myLabel.setFont(myFont)
        myLabel.setText(myLabelText)
        myLabel.adjustSizeToText()
        myLabelHeight = 50.0  # mm determined using qgis map composer
        myLabelWidth = (self.pageWidth / 2) - self.pageMargin
        myLeftOffset = self.pageWidth / 2  # put in right half of page
        myLabel.setItemPosition(myLeftOffset, theTopOffset, myLabelWidth, myLabelHeight)
        myLabel.setFrame(self.showFramesFlag)
        self.composition.addItem(myLabel)
Exemplo n.º 9
0
    def drawTitle(self, theTopOffset):
        """Add a title to the composition.

        Args:
            theTopOffset - vertical offset at which the map should be drawn
        Returns:
            float - the height of the label as rendered
        Raises:
            None
        """
        LOGGER.debug("InaSAFE Map drawTitle called")
        myFontSize = 14
        myFontWeight = QtGui.QFont.Bold
        myItalicsFlag = False
        myFont = QtGui.QFont("verdana", myFontSize, myFontWeight, myItalicsFlag)
        myLabel = QgsComposerLabel(self.composition)
        myLabel.setFont(myFont)
        myHeading = self.tr("InaSAFE - Indonesia Scenario Assessment" " for Emergencies")
        myLabel.setText(myHeading)
        myLabel.adjustSizeToText()
        myLabelHeight = 10.0  # determined using qgis map composer
        myLabelWidth = 170.0  # item - position and size...option
        myLeftOffset = self.pageWidth - self.pageMargin - myLabelWidth
        myLabel.setItemPosition(
            myLeftOffset, theTopOffset - 2, myLabelWidth, myLabelHeight  # -2 to push it up a little
        )
        myLabel.setFrame(self.showFramesFlag)
        self.composition.addItem(myLabel)
        return myLabelHeight
Exemplo n.º 10
0
 def draw_disclaimer(self):
     """Add a disclaimer to the composition."""
     LOGGER.debug('InaSAFE Map drawDisclaimer called')
     font_size = 10
     font_weight = QtGui.QFont.Normal
     italics_flag = True
     font = QtGui.QFont(
         'verdana',
         font_size,
         font_weight,
         italics_flag)
     label = QgsComposerLabel(self.composition)
     label.setFont(font)
     label.setText(self.disclaimer)
     label.adjustSizeToText()
     label_height = 7.0  # mm determined using qgis map composer
     label_width = self.page_width   # item - position and size...option
     left_offset = self.page_margin
     top_offset = self.page_height - self.page_margin
     label.setItemPosition(
         left_offset,
         top_offset,
         label_width,
         label_height,)
     label.setFrameEnabled(self.show_frames)
     self.composition.addItem(label)
Exemplo n.º 11
0
    def composer(self, setData, flag=True):
        paperWidth = setData["Width"]
        paperHeight = setData["Height"]
        mapRenderer = define._canvas.mapRenderer()
        #         comp = None
        comp = QgsComposition(mapRenderer)
        comp.setPlotStyle(QgsComposition.Print)

        comp.setPaperSize(paperWidth, paperHeight)
        # rectangleAll = QgsComposerShape(comp)
        # rectangleAll.setItemPosition(3, 3, paperWidth - 3, paperHeight - 3)
        # rectangleAll.setShapeType(1)
        # comp.addItem(rectangleAll)

        self.txt1 = QgsComposerLabel(comp)
        self.txt1.setItemPosition(20, 20)
        self.txt1.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt1.setFont(font)
        self.txt1.setText(setData["TextData"][0])
        self.txt1.adjustSizeToText()
        comp.addItem(self.txt1)

        self.txt2 = QgsComposerLabel(comp)
        self.txt2.setItemPosition(int(paperWidth / 2) + 10, 20)
        self.txt2.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt2.setFont(font)
        self.txt2.setText(setData["TextData"][1])
        self.txt2.adjustSizeToText()
        comp.addItem(self.txt2)

        self.txt3 = QgsComposerLabel(comp)
        self.txt3.setItemPosition(paperWidth - 40, 20)
        self.txt3.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt3.setFont(font)
        self.txt3.setText(setData["TextData"][2])
        self.txt3.adjustSizeToText()
        comp.addItem(self.txt3)

        w = int((paperWidth - 40) / 4)

        self.txt4 = QgsComposerLabel(comp)
        self.txt4.setItemPosition(20, 35)
        self.txt4.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt4.setFont(font)
        self.txt4.setText(setData["TextData"][3])
        self.txt4.adjustSizeToText()
        comp.addItem(self.txt4)

        self.txt5 = QgsComposerLabel(comp)
        self.txt5.setItemPosition(20 + w, 35)
        self.txt5.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt5.setFont(font)
        self.txt5.setText(setData["TextData"][4])
        self.txt5.adjustSizeToText()
        comp.addItem(self.txt5)

        self.txt6 = QgsComposerLabel(comp)
        self.txt6.setItemPosition(20 + w * 2, 35)
        self.txt6.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt6.setFont(font)
        self.txt6.setText(setData["TextData"][5])
        self.txt6.adjustSizeToText()
        comp.addItem(self.txt6)

        self.txt7 = QgsComposerLabel(comp)
        self.txt7.setItemPosition(20 + w * 3, 35)
        self.txt7.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt7.setFont(font)
        self.txt7.setText(setData["TextData"][6])
        self.txt7.adjustSizeToText()
        comp.addItem(self.txt7)

        # if flag:
        x, y = 20, 45
        composerMap = QgsComposerMap(comp, x, y, paperWidth - 40, 150)
        #         composerMap.setPreviewMode(QgsComposerMap.Render)
        #         composerMap.setGridEnabled(False)

        #rect = composerMap.currentMapExtent ()
        renderer = composerMap.mapRenderer()
        newExtent = renderer.extent()

        #Make sure the width/height ratio is the same as in current composer map extent.
        #This is to keep the map item frame and the page layout fixed
        currentMapExtent = composerMap.currentMapExtent()
        currentWidthHeightRatio = currentMapExtent.width(
        ) / currentMapExtent.height()
        newWidthHeightRatio = newExtent.width() / newExtent.height()

        if currentWidthHeightRatio < newWidthHeightRatio:
            #enlarge height of new extent, ensuring the map center stays the same
            newHeight = newExtent.width() / currentWidthHeightRatio
            deltaHeight = newHeight - newExtent.height()
            newExtent.setYMinimum(newExtent.yMinimum() - deltaHeight / 2)
            newExtent.setYMaximum(newExtent.yMaximum() + deltaHeight / 2)

        else:
            #enlarge width of new extent, ensuring the map center stays the same
            newWidth = currentWidthHeightRatio * newExtent.height()
            deltaWidth = newWidth - newExtent.width()
            newExtent.setXMinimum(newExtent.xMinimum() - deltaWidth / 2)
            newExtent.setXMaximum(newExtent.xMaximum() + deltaWidth / 2)

        composerMap.beginCommand("Map extent changed")
        composerMap.setNewExtent(newExtent)
        composerMap.endCommand()
        # composerMap.setNewScale(3500)

        composerMap.setFrameEnabled(True)
        composerMap.setFrameOutlineWidth(1.0)
        composerMap.setPreviewMode(QgsComposerMap.Render)
        composerMap.updateCachedImage()

        composerMap.setGridEnabled(True)
        composerMap.setGridPenColor(QColor(255, 255, 255, 0))
        composerMap.setGridPenWidth(0.0)
        #composerMap.setGridStyle(QgsComposerMap.FrameAnnotationsOnly)
        composerMap.setGridIntervalX(1.0)
        composerMap.setGridIntervalY(1.0)
        #         mySymbol1 = composerMap.gridLineSymbol ()
        #         mySymbol1.setAlpha(0)
        #composerMap.setGridLineSymbol(mySymbol1)
        composerMap.setShowGridAnnotation(True)
        composerMap.setGridAnnotationFormat(1)
        composerMap.setGridAnnotationPrecision(0)
        composerMap.setGridAnnotationDirection(1, 0)
        composerMap.setGridAnnotationDirection(1, 1)

        comp.addItem(composerMap)

        w = int((paperWidth - 40) / 3)

        self.txt8 = QgsComposerLabel(comp)
        self.txt8.setItemPosition(20, 225)
        self.txt8.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt8.setFont(font)
        self.txt8.setText(setData["TextData"][7])
        self.txt8.adjustSizeToText()
        comp.addItem(self.txt8)

        self.txt9 = QgsComposerLabel(comp)
        self.txt9.setItemPosition(20 + w, 225)
        self.txt9.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt9.setFont(font)
        self.txt9.setText(setData["TextData"][8])
        self.txt9.adjustSizeToText()
        comp.addItem(self.txt9)

        self.txt10 = QgsComposerLabel(comp)
        self.txt10.setItemPosition(20 + w * 2, 225)
        self.txt10.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt10.setFont(font)
        self.txt10.setText(setData["TextData"][9])
        self.txt10.adjustSizeToText()
        comp.addItem(self.txt10)

        # profileRect = QgsComposerPicture(comp)
        # profileRect.setItemPosition(20, 200, paperWidth - 40, 50)
        # comp.addItem(profileRect)

        self.txt11 = QgsComposerLabel(comp)
        self.txt11.setItemPosition(20, paperHeight - 30)
        self.txt11.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt11.setFont(font)
        self.txt11.setText(setData["TextData"][10])
        self.txt11.adjustSizeToText()
        comp.addItem(self.txt11)

        self.txt12 = QgsComposerLabel(comp)
        self.txt12.setItemPosition(20 + w, paperHeight - 30)
        self.txt12.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt12.setFont(font)
        self.txt12.setText(setData["TextData"][11])
        self.txt12.adjustSizeToText()
        comp.addItem(self.txt12)

        self.txt13 = QgsComposerLabel(comp)
        self.txt13.setItemPosition(20 + w * 2, paperHeight - 30)
        self.txt13.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt13.setFont(font)
        self.txt13.setText(setData["TextData"][12])
        self.txt13.adjustSizeToText()
        comp.addItem(self.txt13)

        # gpw = QGraphicsProxyWidget()
        self.tblView = QTableView()
        tableHeight = None
        tableWidth = None
        if self.tableChangedValue == None:
            self.tblView.setFixedWidth(paperWidth - 40)
            tableHeight = 50
            tableWidth = paperWidth - 40
            self.tblView.setFixedHeight(tableHeight)
        else:
            self.tblView.setFixedWidth(self.tableChangedValue["Width"])
            self.tblView.setFixedHeight(self.tableChangedValue["Height"])
            tableHeight = self.tableChangedValue["Height"]
            tableWidth = self.tableChangedValue["Width"]
        self.tblView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.tblView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        hHeder = self.tblView.horizontalHeader()
        hHeder.setVisible(False)
        vHeder = self.tblView.verticalHeader()
        vHeder.setVisible(False)

        # if flag:
        self.stdModel = QStandardItemModel()
        self.data.__setitem__("TableWidth", tableWidth)
        self.data.__setitem__("TableHeight", tableHeight)
        self.setTableView(self.tblView, self.stdModel, self.data)

        self.calcALT()
        self.calcTimeRate()

        self.gpw = QGraphicsProxyWidget()
        self.gpw.setWidget(self.tblView)
        # gpw.setWidget(tblView)
        if self.tableChangedValue == None:
            self.gpw.setPos(20, 210)
            font = QFont()
            font.setPixelSize(2)
            self.gpw.setFont(font)
        else:
            self.gpw.setPos(self.tableChangedValue["X"],
                            self.tableChangedValue["Y"])
            font = QFont()
            font.setPixelSize(self.tableChangedValue["FontSize"])
            self.gpw.setFont(font)

        # tblView.setFrameRect(QRect(20, 210, paperWidth - 40, 50))
        comp.addItem(self.gpw)

        self.connect(self.stdModel, SIGNAL("itemChanged(QStandardItem *)"),
                     self.stdModel_itemChanged)
        return comp
Exemplo n.º 12
0
    def drawDisclaimer(self):
        """Add a disclaimer to the composition.

        Args:
            None
        Returns:
            None
        Raises:
            None
        """
        LOGGER.debug('InaSAFE Map drawDisclaimer called')
        myFontSize = 10
        myFontWeight = QtGui.QFont.Normal
        myItalicsFlag = True
        myFont = QtGui.QFont('verdana', myFontSize, myFontWeight,
                             myItalicsFlag)
        myLabel = QgsComposerLabel(self.composition)
        myLabel.setFont(myFont)
        myLabel.setText(self.disclaimer)
        myLabel.adjustSizeToText()
        myLabelHeight = 7.0  # mm determined using qgis map composer
        myLabelWidth = self.pageWidth  # item - position and size...option
        myLeftOffset = self.pageMargin
        myTopOffset = self.pageHeight - self.pageMargin
        myLabel.setItemPosition(
            myLeftOffset,
            myTopOffset,
            myLabelWidth,
            myLabelHeight,
        )
        myLabel.setFrame(self.showFramesFlag)
        self.composition.addItem(myLabel)
Exemplo n.º 13
0
    def drawHostAndTime(self, theTopOffset):
        """Add a disclaimer to the composition.

        Args:
            theTopOffset - vertical offset at which to begin drawing
        Returns:
            None
        Raises:
            None
        """
        LOGGER.debug('InaSAFE Map drawDisclaimer called')
        #elapsed_time: 11.612545
        #user: timlinux
        #host_name: ultrabook
        #time_stamp: 2012-10-13_23:10:31
        #myUser = self.keywordIO.readKeywords(self.layer, 'user')
        #myHost = self.keywordIO.readKeywords(self.layer, 'host_name')
        myDateTime = self.keywordIO.readKeywords(self.layer, 'time_stamp')
        myTokens = myDateTime.split('_')
        myDate = myTokens[0]
        myTime = myTokens[1]
        #myElapsedTime = self.keywordIO.readKeywords(self.layer,
        #                                            'elapsed_time')
        #myElapsedTime = humaniseSeconds(myElapsedTime)
        myLongVersion = get_version()
        myTokens = myLongVersion.split('.')
        myVersion = '%s.%s.%s' % (myTokens[0], myTokens[1], myTokens[2])
        myLabelText = self.tr(
            'Date and time of assessment: %1 %2\n'
            'Special note: This assessment is a guide - we strongly recommend '
            'that you ground truth the results shown here before deploying '
            'resources and / or personnel.\n'
            'Assessment carried out using InaSAFE release %3 (QGIS '
            'plugin version).').arg(myDate).arg(myTime).arg(myVersion)
        myFontSize = 6
        myFontWeight = QtGui.QFont.Normal
        myItalicsFlag = True
        myFont = QtGui.QFont('verdana', myFontSize, myFontWeight,
                             myItalicsFlag)
        myLabel = QgsComposerLabel(self.composition)
        myLabel.setFont(myFont)
        myLabel.setText(myLabelText)
        myLabel.adjustSizeToText()
        myLabelHeight = 50.0  # mm determined using qgis map composer
        myLabelWidth = (self.pageWidth / 2) - self.pageMargin
        myLeftOffset = self.pageWidth / 2  # put in right half of page
        myLabel.setItemPosition(
            myLeftOffset,
            theTopOffset,
            myLabelWidth,
            myLabelHeight,
        )
        myLabel.setFrame(self.showFramesFlag)
        self.composition.addItem(myLabel)
Exemplo n.º 14
0
    def drawScaleBar(self, theComposerMap, theTopOffset):
        """Add a numeric scale to the bottom left of the map

        We draw the scale bar manually because QGIS does not yet support
        rendering a scalebar for a geographic map in km.

        .. seealso:: :meth:`drawNativeScaleBar`

        Args:
            * theComposerMap - QgsComposerMap instance used as the basis
              scale calculations.
            * theTopOffset - vertical offset at which the map should be drawn
        Returns:
            None
        Raises:
            Any exceptions raised by the InaSAFE library will be propagated.
        """
        LOGGER.debug('InaSAFE Map drawScaleBar called')
        myCanvas = self.iface.mapCanvas()
        myRenderer = myCanvas.mapRenderer()
        #
        # Add a linear map scale
        #
        myDistanceArea = QgsDistanceArea()
        myDistanceArea.setSourceCrs(myRenderer.destinationCrs().srsid())
        myDistanceArea.setProjectionsEnabled(True)
        # Determine how wide our map is in km/m
        # Starting point at BL corner
        myComposerExtent = theComposerMap.extent()
        myStartPoint = QgsPoint(myComposerExtent.xMinimum(),
                                myComposerExtent.yMinimum())
        # Ending point at BR corner
        myEndPoint = QgsPoint(myComposerExtent.xMaximum(),
                              myComposerExtent.yMinimum())
        myGroundDistance = myDistanceArea.measureLine(myStartPoint, myEndPoint)
        # Get the equivalent map distance per page mm
        myMapWidth = self.mapWidth
        # How far is 1mm on map on the ground in meters?
        myMMToGroundDistance = myGroundDistance / myMapWidth
        #print 'MM:', myMMDistance
        # How long we want the scale bar to be in relation to the map
        myScaleBarToMapRatio = 0.5
        # How many divisions the scale bar should have
        myTickCount = 5
        myScaleBarWidthMM = myMapWidth * myScaleBarToMapRatio
        myPrintSegmentWidthMM = myScaleBarWidthMM / myTickCount
        # Segment width in real world (m)
        # We apply some logic here so that segments are displayed in meters
        # if each segment is less that 1000m otherwise km. Also the segment
        # lengths are rounded down to human looking numbers e.g. 1km not 1.1km
        myUnits = ''
        myGroundSegmentWidth = myPrintSegmentWidthMM * myMMToGroundDistance
        if myGroundSegmentWidth < 1000:
            myUnits = 'm'
            myGroundSegmentWidth = round(myGroundSegmentWidth)
            # adjust the segment width now to account for rounding
            myPrintSegmentWidthMM = myGroundSegmentWidth / myMMToGroundDistance
        else:
            myUnits = 'km'
            # Segment with in real world (km)
            myGroundSegmentWidth = round(myGroundSegmentWidth / 1000)
            myPrintSegmentWidthMM = ((myGroundSegmentWidth * 1000) /
                                     myMMToGroundDistance)
        # Now adjust the scalebar width to account for rounding
        myScaleBarWidthMM = myTickCount * myPrintSegmentWidthMM

        #print "SBWMM:", myScaleBarWidthMM
        #print "SWMM:", myPrintSegmentWidthMM
        #print "SWM:", myGroundSegmentWidthM
        #print "SWKM:", myGroundSegmentWidthKM
        # start drawing in line segments
        myScaleBarHeight = 5  # mm
        myLineWidth = 0.3  # mm
        myInsetDistance = 7  # how much to inset the scalebar into the map by
        myScaleBarX = self.pageMargin + myInsetDistance
        myScaleBarY = (theTopOffset + self.mapHeight - myInsetDistance -
                       myScaleBarHeight)  # mm

        # Draw an outer background box - shamelessly hardcoded buffer
        myRect = QgsComposerShape(
            myScaleBarX - 4,  # left edge
            myScaleBarY - 3,  # top edge
            myScaleBarWidthMM + 13,  # right edge
            myScaleBarHeight + 6,  # bottom edge
            self.composition)

        myRect.setShapeType(QgsComposerShape.Rectangle)
        myRect.setLineWidth(myLineWidth)
        myRect.setFrame(False)
        myBrush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        # workaround for missing setTransparentFill missing from python api
        myRect.setBrush(myBrush)
        self.composition.addItem(myRect)
        # Set up the tick label font
        myFontWeight = QtGui.QFont.Normal
        myFontSize = 6
        myItalicsFlag = False
        myFont = QtGui.QFont('verdana', myFontSize, myFontWeight,
                             myItalicsFlag)
        # Draw the bottom line
        myUpshift = 0.3  # shift the bottom line up for better rendering
        myRect = QgsComposerShape(myScaleBarX,
                                  myScaleBarY + myScaleBarHeight - myUpshift,
                                  myScaleBarWidthMM, 0.1, self.composition)

        myRect.setShapeType(QgsComposerShape.Rectangle)
        myRect.setLineWidth(myLineWidth)
        myRect.setFrame(False)
        self.composition.addItem(myRect)

        # Now draw the scalebar ticks
        for myTickCountIterator in range(0, myTickCount + 1):
            myDistanceSuffix = ''
            if myTickCountIterator == myTickCount:
                myDistanceSuffix = ' ' + myUnits
            myRealWorldDistance = (
                '%.0f%s' %
                (myTickCountIterator * myGroundSegmentWidth, myDistanceSuffix))
            #print 'RW:', myRealWorldDistance
            myMMOffset = myScaleBarX + (myTickCountIterator *
                                        myPrintSegmentWidthMM)
            #print 'MM:', myMMOffset
            myTickHeight = myScaleBarHeight / 2
            # Lines are not exposed by the api yet so we
            # bodge drawing lines using rectangles with 1px height or width
            myTickWidth = 0.1  # width or rectangle to be drawn
            myUpTickLine = QgsComposerShape(
                myMMOffset, myScaleBarY + myScaleBarHeight - myTickHeight,
                myTickWidth, myTickHeight, self.composition)

            myUpTickLine.setShapeType(QgsComposerShape.Rectangle)
            myUpTickLine.setLineWidth(myLineWidth)
            myUpTickLine.setFrame(False)
            self.composition.addItem(myUpTickLine)
            #
            # Add a tick label
            #
            myLabel = QgsComposerLabel(self.composition)
            myLabel.setFont(myFont)
            myLabel.setText(myRealWorldDistance)
            myLabel.adjustSizeToText()
            myLabel.setItemPosition(myMMOffset - 3, myScaleBarY - myTickHeight)
            myLabel.setFrame(self.showFramesFlag)
            self.composition.addItem(myLabel)
Exemplo n.º 15
0
    def drawTitle(self, theTopOffset):
        """Add a title to the composition.

        Args:
            theTopOffset - vertical offset at which the map should be drawn
        Returns:
            float - the height of the label as rendered
        Raises:
            None
        """
        LOGGER.debug('InaSAFE Map drawTitle called')
        myFontSize = 14
        myFontWeight = QtGui.QFont.Bold
        myItalicsFlag = False
        myFont = QtGui.QFont('verdana', myFontSize, myFontWeight,
                             myItalicsFlag)
        myLabel = QgsComposerLabel(self.composition)
        myLabel.setFont(myFont)
        myHeading = self.tr('InaSAFE - Indonesia Scenario Assessment'
                            ' for Emergencies')
        myLabel.setText(myHeading)
        myLabel.adjustSizeToText()
        myLabelHeight = 10.0  # determined using qgis map composer
        myLabelWidth = 170.0  # item - position and size...option
        myLeftOffset = self.pageWidth - self.pageMargin - myLabelWidth
        myLabel.setItemPosition(
            myLeftOffset,
            theTopOffset - 2,  # -2 to push it up a little
            myLabelWidth,
            myLabelHeight,
        )
        myLabel.setFrame(self.showFramesFlag)
        self.composition.addItem(myLabel)
        return myLabelHeight
Exemplo n.º 16
0
    def layerRenderByComposer(self, layer, outName):
        self.hideOtherLayers(layer)
        mapRenderer = self.iface.mapCanvas().mapRenderer()
        mapRenderer.setLayerSet([layer.id()])
        c = QgsComposition(mapRenderer)
        c.setPlotStyle(QgsComposition.Print)
        c.setPaperSize(297, 210)
        c.setPrintResolution(300)

        x, y = 0, 0
        w, h = c.paperWidth(), c.paperHeight()
        composerMap = QgsComposerMap(c, x, y, w, h)
        composerMap.setMapCanvas(self.iface.mapCanvas())
        c.addItem(composerMap)

        legend = QgsComposerLegend(c)
        root = QgsProject.instance().layerTreeRoot().clone()
        root = self.buildLegendLayerTree(root, [layer])
        legend.modelV2().setRootGroup(root)
        legend.setItemPosition(250, 20)
        legend.setResizeToContents(True)
        c.addItem(legend)

        label = QgsComposerLabel(c)
        label.setMarginX(125)
        label.setMarginY(10)
        label.setText(layer.name())
        label.setFont(QFont('PMinliu', 20, QFont.Bold))
        label.adjustSizeToText()
        c.addItem(label)

        item = QgsComposerScaleBar(c)
        item.setStyle('Double Box')  # optionally modify the style
        item.setComposerMap(composerMap)
        item.applyDefaultSize()
        item.setItemPosition(10, 190)
        c.addItem(item)

        dpmm = 300 / 25.4
        width = int(dpmm * c.paperWidth())
        width = int(width / 2) * 2
        height = int(dpmm * c.paperHeight())
        height = int(height / 2) * 2
        Dots = int(dpmm * 1000 / 2) * 2

        # create output image and initialize it
        image = QImage(QSize(width, height), QImage.Format_ARGB32)
        image.setDotsPerMeterX(Dots)
        image.setDotsPerMeterY(Dots)
        image.fill(0)

        # render the composition
        imagePainter = QPainter(image)
        c.renderPage(imagePainter, 0)
        imagePainter.end()

        outName = os.path.join(self.workingFolder, outName + '.png')
        image.save(outName, "png")

        return outName
Exemplo n.º 17
0
 def draw_disclaimer(self):
     """Add a disclaimer to the composition."""
     LOGGER.debug('InaSAFE Map drawDisclaimer called')
     font_size = 10
     font_weight = QtGui.QFont.Normal
     italics_flag = True
     font = QtGui.QFont('verdana', font_size, font_weight, italics_flag)
     label = QgsComposerLabel(self.composition)
     label.setFont(font)
     label.setText(self.disclaimer)
     label.adjustSizeToText()
     label_height = 7.0  # mm determined using qgis map composer
     label_width = self.page_width  # item - position and size...option
     left_offset = self.page_margin
     top_offset = self.page_height - self.page_margin
     label.setItemPosition(
         left_offset,
         top_offset,
         label_width,
         label_height,
     )
     label.setFrameEnabled(self.show_frames)
     self.composition.addItem(label)
Exemplo n.º 18
0
    def draw_scalebar(self, composer_map, top_offset):
        """Add a numeric scale to the bottom left of the map.

        We draw the scale bar manually because QGIS does not yet support
        rendering a scale bar for a geographic map in km.

        .. seealso:: :meth:`drawNativeScaleBar`

        :param composer_map: Composer map on which to draw the scalebar.
        :type composer_map: QgsComposerMap

        :param top_offset: Vertical offset at which the logo should be drawn.
        :type top_offset: int
        """
        LOGGER.debug('InaSAFE Map drawScaleBar called')
        myCanvas = self.iface.mapCanvas()
        myRenderer = myCanvas.mapRenderer()
        #
        # Add a linear map scale
        #
        myDistanceArea = QgsDistanceArea()
        myDistanceArea.setSourceCrs(myRenderer.destinationCrs().srsid())
        myDistanceArea.setEllipsoidalMode(True)
        # Determine how wide our map is in km/m
        # Starting point at BL corner
        myComposerExtent = composer_map.extent()
        myStartPoint = QgsPoint(myComposerExtent.xMinimum(),
                                myComposerExtent.yMinimum())
        # Ending point at BR corner
        myEndPoint = QgsPoint(myComposerExtent.xMaximum(),
                              myComposerExtent.yMinimum())
        myGroundDistance = myDistanceArea.measureLine(myStartPoint, myEndPoint)
        # Get the equivalent map distance per page mm
        myMapWidth = self.mapWidth
        # How far is 1mm on map on the ground in meters?
        myMMToGroundDistance = myGroundDistance / myMapWidth
        #print 'MM:', myMMDistance
        # How long we want the scale bar to be in relation to the map
        myScaleBarToMapRatio = 0.5
        # How many divisions the scale bar should have
        myTickCount = 5
        myScaleBarWidthMM = myMapWidth * myScaleBarToMapRatio
        myPrintSegmentWidthMM = myScaleBarWidthMM / myTickCount
        # Segment width in real world (m)
        # We apply some logic here so that segments are displayed in meters
        # if each segment is less that 1000m otherwise km. Also the segment
        # lengths are rounded down to human looking numbers e.g. 1km not 1.1km
        myUnits = ''
        myGroundSegmentWidth = myPrintSegmentWidthMM * myMMToGroundDistance
        if myGroundSegmentWidth < 1000:
            myUnits = 'm'
            myGroundSegmentWidth = round(myGroundSegmentWidth)
            # adjust the segment width now to account for rounding
            myPrintSegmentWidthMM = myGroundSegmentWidth / myMMToGroundDistance
        else:
            myUnits = 'km'
            # Segment with in real world (km)
            myGroundSegmentWidth = round(myGroundSegmentWidth / 1000)
            myPrintSegmentWidthMM = ((myGroundSegmentWidth * 1000) /
                                     myMMToGroundDistance)
        # Now adjust the scalebar width to account for rounding
        myScaleBarWidthMM = myTickCount * myPrintSegmentWidthMM

        #print "SBWMM:", myScaleBarWidthMM
        #print "SWMM:", myPrintSegmentWidthMM
        #print "SWM:", myGroundSegmentWidthM
        #print "SWKM:", myGroundSegmentWidthKM
        # start drawing in line segments
        myScaleBarHeight = 5  # mm
        myLineWidth = 0.3  # mm
        myInsetDistance = 7  # how much to inset the scalebar into the map by
        myScaleBarX = self.pageMargin + myInsetDistance
        myScaleBarY = (
            top_offset + self.mapHeight - myInsetDistance -
            myScaleBarHeight)  # mm

        # Draw an outer background box - shamelessly hardcoded buffer
        myRect = QgsComposerShape(myScaleBarX - 4,  # left edge
                                  myScaleBarY - 3,  # top edge
                                  myScaleBarWidthMM + 13,  # right edge
                                  myScaleBarHeight + 6,  # bottom edge
                                  self.composition)

        myRect.setShapeType(QgsComposerShape.Rectangle)
        myPen = QtGui.QPen()
        myPen.setColor(QtGui.QColor(255, 255, 255))
        myPen.setWidthF(myLineWidth)
        myRect.setPen(myPen)
        #myRect.setLineWidth(myLineWidth)
        myRect.setFrameEnabled(False)
        myBrush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        # workaround for missing setTransparentFill missing from python api
        myRect.setBrush(myBrush)
        self.composition.addItem(myRect)
        # Set up the tick label font
        myFontWeight = QtGui.QFont.Normal
        myFontSize = 6
        myItalicsFlag = False
        myFont = QtGui.QFont('verdana',
                             myFontSize,
                             myFontWeight,
                             myItalicsFlag)
        # Draw the bottom line
        myUpshift = 0.3  # shift the bottom line up for better rendering
        myRect = QgsComposerShape(myScaleBarX,
                                  myScaleBarY + myScaleBarHeight - myUpshift,
                                  myScaleBarWidthMM,
                                  0.1,
                                  self.composition)

        myRect.setShapeType(QgsComposerShape.Rectangle)
        myPen = QtGui.QPen()
        myPen.setColor(QtGui.QColor(255, 255, 255))
        myPen.setWidthF(myLineWidth)
        myRect.setPen(myPen)
        #myRect.setLineWidth(myLineWidth)
        myRect.setFrameEnabled(False)
        self.composition.addItem(myRect)

        # Now draw the scalebar ticks
        for myTickCountIterator in range(0, myTickCount + 1):
            myDistanceSuffix = ''
            if myTickCountIterator == myTickCount:
                myDistanceSuffix = ' ' + myUnits
            myRealWorldDistance = ('%.0f%s' %
                                   (myTickCountIterator *
                                    myGroundSegmentWidth,
                                    myDistanceSuffix))
            #print 'RW:', myRealWorldDistance
            myMMOffset = myScaleBarX + (myTickCountIterator *
                                        myPrintSegmentWidthMM)
            #print 'MM:', myMMOffset
            myTickHeight = myScaleBarHeight / 2
            # Lines are not exposed by the api yet so we
            # bodge drawing lines using rectangles with 1px height or width
            myTickWidth = 0.1  # width or rectangle to be drawn
            myUpTickLine = QgsComposerShape(
                myMMOffset,
                myScaleBarY + myScaleBarHeight - myTickHeight,
                myTickWidth,
                myTickHeight,
                self.composition)

            myUpTickLine.setShapeType(QgsComposerShape.Rectangle)
            myPen = QtGui.QPen()
            myPen.setWidthF(myLineWidth)
            myUpTickLine.setPen(myPen)
            #myUpTickLine.setLineWidth(myLineWidth)
            myUpTickLine.setFrameEnabled(False)
            self.composition.addItem(myUpTickLine)
            #
            # Add a tick label
            #
            myLabel = QgsComposerLabel(self.composition)
            myLabel.setFont(myFont)
            myLabel.setText(myRealWorldDistance)
            myLabel.adjustSizeToText()
            myLabel.setItemPosition(
                myMMOffset - 3,
                myScaleBarY - myTickHeight)
            myLabel.setFrameEnabled(self.showFramesFlag)
            self.composition.addItem(myLabel)
Exemplo n.º 19
0
    def draw_host_and_time(self, top_offset):
        """Add a note with hostname and time to the composition.

        :param top_offset: Vertical offset at which the logo should be drawn.
        :type top_offset: int
        """
        LOGGER.debug('InaSAFE Map drawDisclaimer called')
        #elapsed_time: 11.612545
        #user: timlinux
        #host_name: ultrabook
        #time_stamp: 2012-10-13_23:10:31
        #myUser = self.keyword_io.readKeywords(self.layer, 'user')
        #myHost = self.keyword_io.readKeywords(self.layer, 'host_name')
        date_time = self.keyword_io.read_keywords(self.layer, 'time_stamp')
        tokens = date_time.split('_')
        date = tokens[0]
        time = tokens[1]
        #myElapsedTime = self.keyword_io.readKeywords(self.layer,
        #                                            'elapsed_time')
        #myElapsedTime = humaniseSeconds(myElapsedTime)
        long_version = get_version()
        tokens = long_version.split('.')
        version = '%s.%s.%s' % (tokens[0], tokens[1], tokens[2])
        label_text = self.tr(
            'Date and time of assessment: %s %s\n'
            'Special note: This assessment is a guide - we strongly recommend '
            'that you ground truth the results shown here before deploying '
            'resources and / or personnel.\n'
            'Assessment carried out using InaSAFE release %s (QGIS '
            'plugin version).') % (date, time, version)
        font_size = 6
        font_weight = QtGui.QFont.Normal
        italics_flag = True
        font = QtGui.QFont('verdana', font_size, font_weight, italics_flag)
        label = QgsComposerLabel(self.composition)
        label.setFont(font)
        label.setText(label_text)
        label.adjustSizeToText()
        label_height = 50.0  # mm determined using qgis map composer
        label_width = (self.page_width / 2) - self.page_margin
        left_offset = self.page_width / 2  # put in right half of page
        label.setItemPosition(
            left_offset,
            top_offset,
            label_width,
            label_height,
        )
        label.setFrameEnabled(self.show_frames)
        self.composition.addItem(label)
Exemplo n.º 20
0
class DlgCharting(QDialog):
    def __init__(self, parent, data):
        QDialog.__init__(self, parent)
        self.ui = Ui_ChartingBase()
        self.ui.setupUi(self)

        self.setWindowTitle("Charting Tool 2")

        # self.ui.btnNext.clicked.connect(self.btnNext_clicked)
        self.ui.btnPrevious.clicked.connect(self.btnPrevious_clicked)
        self.ui.btnExit.clicked.connect(self.btnExit_clicked)

        self.ui.txtText1.textChanged.connect(self.txtText1_textChanged)
        self.ui.txtText2.textChanged.connect(self.txtText2_textChanged)
        self.ui.txtText3.textChanged.connect(self.txtText3_textChanged)
        self.ui.txtText4.textChanged.connect(self.txtText4_textChanged)
        self.ui.txtText5.textChanged.connect(self.txtText5_textChanged)
        self.ui.txtText6.textChanged.connect(self.txtText6_textChanged)
        self.ui.txtText7.textChanged.connect(self.txtText7_textChanged)
        self.ui.txtText8.textChanged.connect(self.txtText8_textChanged)
        self.ui.txtText9.textChanged.connect(self.txtText9_textChanged)
        self.ui.txtText10.textChanged.connect(self.txtText10_textChanged)
        self.ui.txtText11.textChanged.connect(self.txtText11_textChanged)
        self.ui.txtText12.textChanged.connect(self.txtText12_textChanged)
        self.ui.txtText13.textChanged.connect(self.txtText13_textChanged)

        # self.btnNextAndbtnPreviewSetEnabled()
        self.setDataDict = None
        self.parentDlg = parent
        self.pw = None
        self.stdModel = None
        self.data = data
        self.renderFlag = False
        self.changedComposerMap = None
        self.tableChangedValue = None
        self.straightCount = self.data["StraightCount"]
        self.catOfAcftCount = self.data["CatOfAcftCount"][0]

        self.rejected.connect(self.dlgRejected)

    def dlgRejected(self):
        self.parentDlg.show()

    def refreshData(self, data):
        self.data = data

    def txtText1_textChanged(self):
        self.txt1.setText(self.ui.txtText1.text())

    def txtText2_textChanged(self):
        self.txt2.setText(self.ui.txtText2.text())

    def txtText3_textChanged(self):
        self.txt3.setText(self.ui.txtText3.text())

    def txtText4_textChanged(self):
        self.txt4.setText(self.ui.txtText4.toPlainText())

    def txtText5_textChanged(self):
        self.txt5.setText(self.ui.txtText5.toPlainText())

    def txtText6_textChanged(self):
        self.txt6.setText(self.ui.txtText6.toPlainText())

    def txtText7_textChanged(self):
        try:
            self.txt7.setText(self.ui.txtText7.toPlainText())
        except:
            pass

    def txtText8_textChanged(self):
        self.txt8.setText(self.ui.txtText8.text())

    def txtText9_textChanged(self):
        self.txt9.setText(self.ui.txtText9.text())

    def txtText10_textChanged(self):
        self.txt10.setText(self.ui.txtText10.text())

    def txtText11_textChanged(self):
        self.txt11.setText(self.ui.txtText11.text())

    def txtText12_textChanged(self):
        self.txt12.setText(self.ui.txtText12.text())

    def txtText13_textChanged(self):
        self.txt13.setText(self.ui.txtText13.text())

    # def btnNextAndbtnPreviewSetEnabled(self):
    #     if self.ui.stackedWidget.currentIndex() == 0:
    #         self.ui.btnPrevious.setEnabled(False)
    #         self.ui.frame_2.setVisible(False)
    #         self.resize(100, 100)
    #
    #     else:
    #         self.ui.frame_2.setVisible(True)
    #         self.ui.btnPrevious.setEnabled(True)
    #     if self.ui.stackedWidget.currentIndex() == self.ui.stackedWidget.count() - 1:
    #         self.ui.btnNext.setEnabled(False)
    #     else:
    #         self.ui.btnNext.setEnabled(True)
    def btnExit_clicked(self):
        # comp = QgsComposer(self, define._canvas)
        # comp.show()
        self.setDataDict = dict()
        for key, val in self.data.iteritems():
            self.setDataDict.__setitem__(key, val)
        self.setDataDict.__setitem__("TextData", [
            self.ui.txtText1.text(),
            self.ui.txtText2.text(),
            self.ui.txtText3.text(),
            self.ui.txtText4.toPlainText(),
            self.ui.txtText5.toPlainText(),
            self.ui.txtText6.toPlainText(),
            self.ui.txtText7.toPlainText(),
            self.ui.txtText8.text(),
            self.ui.txtText9.text(),
            self.ui.txtText10.text(),
            self.ui.txtText11.text(),
            self.ui.txtText12.text(),
            self.ui.txtText13.text()
        ])
        # self.setDataDict.__setitem__("StraightCount", self.straightCount)
        # self.setDataDict.__setitem__("CatOfAcftCount", self.catOfAcftCount)
        comp = None
        if self.pw == None or not isinstance(self.pw, ComposerDlg):
            comp = self.composer(self.setDataDict)
        else:
            comp = self.composer(self.setDataDict, False)
        pwFlag = False

        if self.pw == None or not isinstance(self.pw, ComposerDlg):
            self.pw = ComposerDlg(self, comp, self.stdModel, self.setDataDict)
            pwFlag = True
        if not self.renderFlag:
            self.pw.show()
        if not pwFlag:
            self.pw.rePresent(comp, self.stdModel, self.setDataDict)
        self.renderFlag = False

    def showDlg(self):
        self.pw.hide()
        self.show()
        self.ui.txtText1.setText(self.txt1.text())
        self.ui.txtText2.setText(self.txt2.text())
        self.ui.txtText3.setText(self.txt3.text())
        self.ui.txtText4.setText(self.txt4.text())
        self.ui.txtText5.setText(self.txt5.text())
        self.ui.txtText6.setText(self.txt6.text())
        self.ui.txtText7.setText(self.txt7.text())
        self.ui.txtText8.setText(self.txt8.text())
        self.ui.txtText9.setText(self.txt9.text())
        self.ui.txtText10.setText(self.txt10.text())
        self.ui.txtText11.setText(self.txt11.text())
        self.ui.txtText12.setText(self.txt12.text())
        self.ui.txtText13.setText(self.txt13.text())

    # def btnNext_clicked(self):
    #     if self.ui.stackedWidget.currentIndex() + 1 < self.ui.stackedWidget.count():
    #         self.ui.stackedWidget.setCurrentIndex(self.ui.stackedWidget.currentIndex() + 1)
    #     self.btnNextAndbtnPreviewSetEnabled()
    def btnPrevious_clicked(self):
        self.setVisible(False)
        self.parent().show()
        # if self.ui.stackedWidget.currentIndex() > 0:
        #     self.ui.stackedWidget.setCurrentIndex(self.ui.stackedWidget.currentIndex() - 1)
        # self.btnNextAndbtnPreviewSetEnabled()

    def composer(self, setData, flag=True):
        paperWidth = setData["Width"]
        paperHeight = setData["Height"]
        mapRenderer = define._canvas.mapRenderer()
        #         comp = None
        comp = QgsComposition(mapRenderer)
        comp.setPlotStyle(QgsComposition.Print)

        comp.setPaperSize(paperWidth, paperHeight)
        # rectangleAll = QgsComposerShape(comp)
        # rectangleAll.setItemPosition(3, 3, paperWidth - 3, paperHeight - 3)
        # rectangleAll.setShapeType(1)
        # comp.addItem(rectangleAll)

        self.txt1 = QgsComposerLabel(comp)
        self.txt1.setItemPosition(20, 20)
        self.txt1.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt1.setFont(font)
        self.txt1.setText(setData["TextData"][0])
        self.txt1.adjustSizeToText()
        comp.addItem(self.txt1)

        self.txt2 = QgsComposerLabel(comp)
        self.txt2.setItemPosition(int(paperWidth / 2) + 10, 20)
        self.txt2.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt2.setFont(font)
        self.txt2.setText(setData["TextData"][1])
        self.txt2.adjustSizeToText()
        comp.addItem(self.txt2)

        self.txt3 = QgsComposerLabel(comp)
        self.txt3.setItemPosition(paperWidth - 40, 20)
        self.txt3.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt3.setFont(font)
        self.txt3.setText(setData["TextData"][2])
        self.txt3.adjustSizeToText()
        comp.addItem(self.txt3)

        w = int((paperWidth - 40) / 4)

        self.txt4 = QgsComposerLabel(comp)
        self.txt4.setItemPosition(20, 35)
        self.txt4.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt4.setFont(font)
        self.txt4.setText(setData["TextData"][3])
        self.txt4.adjustSizeToText()
        comp.addItem(self.txt4)

        self.txt5 = QgsComposerLabel(comp)
        self.txt5.setItemPosition(20 + w, 35)
        self.txt5.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt5.setFont(font)
        self.txt5.setText(setData["TextData"][4])
        self.txt5.adjustSizeToText()
        comp.addItem(self.txt5)

        self.txt6 = QgsComposerLabel(comp)
        self.txt6.setItemPosition(20 + w * 2, 35)
        self.txt6.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt6.setFont(font)
        self.txt6.setText(setData["TextData"][5])
        self.txt6.adjustSizeToText()
        comp.addItem(self.txt6)

        self.txt7 = QgsComposerLabel(comp)
        self.txt7.setItemPosition(20 + w * 3, 35)
        self.txt7.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt7.setFont(font)
        self.txt7.setText(setData["TextData"][6])
        self.txt7.adjustSizeToText()
        comp.addItem(self.txt7)

        # if flag:
        x, y = 20, 45
        composerMap = QgsComposerMap(comp, x, y, paperWidth - 40, 150)
        #         composerMap.setPreviewMode(QgsComposerMap.Render)
        #         composerMap.setGridEnabled(False)

        #rect = composerMap.currentMapExtent ()
        renderer = composerMap.mapRenderer()
        newExtent = renderer.extent()

        #Make sure the width/height ratio is the same as in current composer map extent.
        #This is to keep the map item frame and the page layout fixed
        currentMapExtent = composerMap.currentMapExtent()
        currentWidthHeightRatio = currentMapExtent.width(
        ) / currentMapExtent.height()
        newWidthHeightRatio = newExtent.width() / newExtent.height()

        if currentWidthHeightRatio < newWidthHeightRatio:
            #enlarge height of new extent, ensuring the map center stays the same
            newHeight = newExtent.width() / currentWidthHeightRatio
            deltaHeight = newHeight - newExtent.height()
            newExtent.setYMinimum(newExtent.yMinimum() - deltaHeight / 2)
            newExtent.setYMaximum(newExtent.yMaximum() + deltaHeight / 2)

        else:
            #enlarge width of new extent, ensuring the map center stays the same
            newWidth = currentWidthHeightRatio * newExtent.height()
            deltaWidth = newWidth - newExtent.width()
            newExtent.setXMinimum(newExtent.xMinimum() - deltaWidth / 2)
            newExtent.setXMaximum(newExtent.xMaximum() + deltaWidth / 2)

        composerMap.beginCommand("Map extent changed")
        composerMap.setNewExtent(newExtent)
        composerMap.endCommand()
        # composerMap.setNewScale(3500)

        composerMap.setFrameEnabled(True)
        composerMap.setFrameOutlineWidth(1.0)
        composerMap.setPreviewMode(QgsComposerMap.Render)
        composerMap.updateCachedImage()

        composerMap.setGridEnabled(True)
        composerMap.setGridPenColor(QColor(255, 255, 255, 0))
        composerMap.setGridPenWidth(0.0)
        #composerMap.setGridStyle(QgsComposerMap.FrameAnnotationsOnly)
        composerMap.setGridIntervalX(1.0)
        composerMap.setGridIntervalY(1.0)
        #         mySymbol1 = composerMap.gridLineSymbol ()
        #         mySymbol1.setAlpha(0)
        #composerMap.setGridLineSymbol(mySymbol1)
        composerMap.setShowGridAnnotation(True)
        composerMap.setGridAnnotationFormat(1)
        composerMap.setGridAnnotationPrecision(0)
        composerMap.setGridAnnotationDirection(1, 0)
        composerMap.setGridAnnotationDirection(1, 1)

        comp.addItem(composerMap)

        w = int((paperWidth - 40) / 3)

        self.txt8 = QgsComposerLabel(comp)
        self.txt8.setItemPosition(20, 225)
        self.txt8.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt8.setFont(font)
        self.txt8.setText(setData["TextData"][7])
        self.txt8.adjustSizeToText()
        comp.addItem(self.txt8)

        self.txt9 = QgsComposerLabel(comp)
        self.txt9.setItemPosition(20 + w, 225)
        self.txt9.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt9.setFont(font)
        self.txt9.setText(setData["TextData"][8])
        self.txt9.adjustSizeToText()
        comp.addItem(self.txt9)

        self.txt10 = QgsComposerLabel(comp)
        self.txt10.setItemPosition(20 + w * 2, 225)
        self.txt10.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt10.setFont(font)
        self.txt10.setText(setData["TextData"][9])
        self.txt10.adjustSizeToText()
        comp.addItem(self.txt10)

        # profileRect = QgsComposerPicture(comp)
        # profileRect.setItemPosition(20, 200, paperWidth - 40, 50)
        # comp.addItem(profileRect)

        self.txt11 = QgsComposerLabel(comp)
        self.txt11.setItemPosition(20, paperHeight - 30)
        self.txt11.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt11.setFont(font)
        self.txt11.setText(setData["TextData"][10])
        self.txt11.adjustSizeToText()
        comp.addItem(self.txt11)

        self.txt12 = QgsComposerLabel(comp)
        self.txt12.setItemPosition(20 + w, paperHeight - 30)
        self.txt12.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt12.setFont(font)
        self.txt12.setText(setData["TextData"][11])
        self.txt12.adjustSizeToText()
        comp.addItem(self.txt12)

        self.txt13 = QgsComposerLabel(comp)
        self.txt13.setItemPosition(20 + w * 2, paperHeight - 30)
        self.txt13.setFrameEnabled(False)
        font = QFont("Arial", 10)
        self.txt13.setFont(font)
        self.txt13.setText(setData["TextData"][12])
        self.txt13.adjustSizeToText()
        comp.addItem(self.txt13)

        # gpw = QGraphicsProxyWidget()
        self.tblView = QTableView()
        tableHeight = None
        tableWidth = None
        if self.tableChangedValue == None:
            self.tblView.setFixedWidth(paperWidth - 40)
            tableHeight = 50
            tableWidth = paperWidth - 40
            self.tblView.setFixedHeight(tableHeight)
        else:
            self.tblView.setFixedWidth(self.tableChangedValue["Width"])
            self.tblView.setFixedHeight(self.tableChangedValue["Height"])
            tableHeight = self.tableChangedValue["Height"]
            tableWidth = self.tableChangedValue["Width"]
        self.tblView.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.tblView.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        hHeder = self.tblView.horizontalHeader()
        hHeder.setVisible(False)
        vHeder = self.tblView.verticalHeader()
        vHeder.setVisible(False)

        # if flag:
        self.stdModel = QStandardItemModel()
        self.data.__setitem__("TableWidth", tableWidth)
        self.data.__setitem__("TableHeight", tableHeight)
        self.setTableView(self.tblView, self.stdModel, self.data)

        self.calcALT()
        self.calcTimeRate()

        self.gpw = QGraphicsProxyWidget()
        self.gpw.setWidget(self.tblView)
        # gpw.setWidget(tblView)
        if self.tableChangedValue == None:
            self.gpw.setPos(20, 210)
            font = QFont()
            font.setPixelSize(2)
            self.gpw.setFont(font)
        else:
            self.gpw.setPos(self.tableChangedValue["X"],
                            self.tableChangedValue["Y"])
            font = QFont()
            font.setPixelSize(self.tableChangedValue["FontSize"])
            self.gpw.setFont(font)

        # tblView.setFrameRect(QRect(20, 210, paperWidth - 40, 50))
        comp.addItem(self.gpw)

        self.connect(self.stdModel, SIGNAL("itemChanged(QStandardItem *)"),
                     self.stdModel_itemChanged)
        return comp

    def setTableView(self, tblView, stdModel, data):
        for i in range(7):
            for j in range(12 + data["CatOfAcftCount"][0]):
                item = QStandardItem("")
                item.setEditable(True)
                item.setTextAlignment(Qt.AlignCenter)
                stdModel.setItem(i, j, item)
        item = QStandardItem("O C A ( H )")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(0, 0, item)

        item = QStandardItem("C a t  of  A C F T")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(1, 0, item)

        item = QStandardItem("S t r a i g h t-I n  A p p r o a c h")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(2, 0, item)

        if data["Template"][0] >= 0 and data["Template"][0] <= 4:
            item = QStandardItem("C i r c l i n g")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(4, 0, item)

            item = QStandardItem(
                "F i n a l  A p p r o a c h  L O C  D i s t a n c e  F A F-M A P t"
            )
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(0, data["CatOfAcftCount"][0] + 3, item)
        else:
            item = QStandardItem("F i n a l  A p p r o a c h  F A F-M A P t")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(0, data["CatOfAcftCount"][0] + 3, item)
        if data["Template"][0] == 5:
            item = QStandardItem("LPV")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(2, 0, item)

            item = QStandardItem("LNAV / VNAV")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(3, 0, item)

            item = QStandardItem("LNAV")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(4, 0, item)

            item = QStandardItem("C i r c l i n g")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(5, 0, item)
        elif data["Template"][0] == 6:
            item = QStandardItem("LNAV / VNAV")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(2, 0, item)

            item = QStandardItem("LNAV")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(3, 0, item)

            item = QStandardItem("C i r c l i n g")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(4, 0, item)
        elif data["Template"][0] == 7:
            item = QStandardItem("LPV")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(2, 0, item)

            item = QStandardItem("LNAV")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(3, 0, item)

            item = QStandardItem("C i r c l i n g")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(4, 0, item)
        elif data["Template"][0] == 8:
            item = QStandardItem("LNAV")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(2, 0, item)

            item = QStandardItem("C i r c l i n g")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(3, 0, item)
        elif data["Template"][0] == 9:
            item = QStandardItem("RNP 0.3")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(2, 0, item)

            item = QStandardItem("C i r c l i n g")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(3, 0, item)

        if data["CatOfAcftCount"][0] == 1:
            item = QStandardItem("A")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(1, 3, item)
        elif data["CatOfAcftCount"][0] == 2:
            item = QStandardItem("A")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(1, 3, item)

            item = QStandardItem("B")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(1, 4, item)
        elif data["CatOfAcftCount"][0] == 3:
            item = QStandardItem("A")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(1, 3, item)

            item = QStandardItem("B")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(1, 4, item)

            item = QStandardItem("C")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(1, 5, item)
        elif data["CatOfAcftCount"][0] == 4:
            item = QStandardItem("A")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(1, 3, item)

            item = QStandardItem("B")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(1, 4, item)

            item = QStandardItem("C")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(1, 5, item)

            item = QStandardItem("D")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(1, 6, item)
        elif data["CatOfAcftCount"][0] == 5:
            if data["CatOfAcftCount"][1] == 4:
                item = QStandardItem("A")
                item.setTextAlignment(Qt.AlignCenter)
                stdModel.setItem(1, 3, item)

                item = QStandardItem("B")
                item.setTextAlignment(Qt.AlignCenter)
                stdModel.setItem(1, 4, item)

                item = QStandardItem("C")
                item.setTextAlignment(Qt.AlignCenter)
                stdModel.setItem(1, 5, item)

                item = QStandardItem("D")
                item.setTextAlignment(Qt.AlignCenter)
                stdModel.setItem(1, 6, item)

                item = QStandardItem("DL")
                item.setTextAlignment(Qt.AlignCenter)
                stdModel.setItem(1, 7, item)
            else:
                item = QStandardItem("A")
                item.setTextAlignment(Qt.AlignCenter)
                stdModel.setItem(1, 3, item)

                item = QStandardItem("B")
                item.setTextAlignment(Qt.AlignCenter)
                stdModel.setItem(1, 4, item)

                item = QStandardItem("C")
                item.setTextAlignment(Qt.AlignCenter)
                stdModel.setItem(1, 5, item)

                item = QStandardItem("D")
                item.setTextAlignment(Qt.AlignCenter)
                stdModel.setItem(1, 6, item)

                item = QStandardItem("E")
                item.setTextAlignment(Qt.AlignCenter)
                stdModel.setItem(1, 7, item)
        elif data["CatOfAcftCount"][0] == 6:
            item = QStandardItem("A")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(1, 3, item)

            item = QStandardItem("B")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(1, 4, item)

            item = QStandardItem("C")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(1, 5, item)

            item = QStandardItem("D")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(1, 6, item)

            item = QStandardItem("DL")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(1, 7, item)

            item = QStandardItem("E")
            item.setTextAlignment(Qt.AlignCenter)
            stdModel.setItem(1, 8, item)

        # item = QStandardItem("DME MX NM")
        # item.setTextAlignment(Qt.AlignCenter)
        # stdModel.setItem(1, 6, item)

        item = QStandardItem("DME SSA")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(1, data["CatOfAcftCount"][0] + 3, item)

        item = QStandardItem("6")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(1, data["CatOfAcftCount"][0] + 5, item)

        item = QStandardItem("5")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(1, data["CatOfAcftCount"][0] + 6, item)

        item = QStandardItem("4")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(1, data["CatOfAcftCount"][0] + 7, item)

        item = QStandardItem("3")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(1, data["CatOfAcftCount"][0] + 8, item)

        item = QStandardItem("2")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(1, data["CatOfAcftCount"][0] + 9, item)

        item = QStandardItem("1")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(1, data["CatOfAcftCount"][0] + 10, item)

        item = QStandardItem("A L T(HGT)")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(2, data["CatOfAcftCount"][0] + 3, item)

        item = QStandardItem("G S")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(3, data["CatOfAcftCount"][0] + 3, item)

        item = QStandardItem("kt")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(3, data["CatOfAcftCount"][0] + 5, item)

        item = QStandardItem("80")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(3, data["CatOfAcftCount"][0] + 6, item)

        item = QStandardItem("100")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(3, data["CatOfAcftCount"][0] + 7, item)

        item = QStandardItem("120")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(3, data["CatOfAcftCount"][0] + 8, item)

        item = QStandardItem("140")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(3, data["CatOfAcftCount"][0] + 9, item)

        item = QStandardItem("160")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(3, data["CatOfAcftCount"][0] + 10, item)

        item = QStandardItem("180")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(3, data["CatOfAcftCount"][0] + 11, item)

        item = QStandardItem("T i me")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(4, data["CatOfAcftCount"][0] + 3, item)

        item = QStandardItem("mi n:s")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(4, data["CatOfAcftCount"][0] + 5, item)

        item = QStandardItem("Rate  Of  D e s c e n t")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(5, data["CatOfAcftCount"][0] + 3, item)

        item = QStandardItem("ft/mi n")
        item.setTextAlignment(Qt.AlignCenter)
        stdModel.setItem(5, data["CatOfAcftCount"][0] + 5, item)

        tblView.setModel(stdModel)
        for i in range(7):
            tblView.setRowHeight(i, int(data["TableHeight"] / 7))
        for j in range(12 + data["CatOfAcftCount"][0]):
            tblView.setColumnWidth(
                j,
                int(data["TableWidth"] /
                    float(12 + data["CatOfAcftCount"][0])))
        # tblView.setColumnWidth(0, 25)
        # tblView.setColumnWidth(6, 20)
        tblView.setSpan(0, 0, 1, data["CatOfAcftCount"][0] + 3)
        tblView.setSpan(1, 0, 1, 3)
        if data["Template"][0] >= 0 and data["Template"][0] <= 4:
            tblView.setSpan(2, 0, 1, 3)
            tblView.setSpan(2, 3, 1, data["CatOfAcftCount"][0])
            tblView.setSpan(3, 0, 1, data["CatOfAcftCount"][0] + 3)
            tblView.setSpan(4, 0, 1, 3)
            tblView.setSpan(5, 0, 1, 3)
            tblView.setSpan(6, 0, 1, 3)
        else:
            tblView.setSpan(2, 0, 1, 3)
            tblView.setSpan(3, 0, 1, 3)
            tblView.setSpan(4, 0, 1, 3)
            tblView.setSpan(5, 0, 1, 3)
            tblView.setSpan(6, 0, 1, 3)

        # tblView.setSpan(data["StraightCount"] + 2, 0, 1, 3)

        tblView.setSpan(0, data["CatOfAcftCount"][0] + 3, 1, 9)
        # tblView.setSpan(1, data["CatOfAcftCount"][0] + 4, 1, 5)
        # tblView.setSpan(1, data["CatOfAcftCount"][0] + 9, 1, 3)
        # tblView.setSpan(2, data["CatOfAcftCount"][0] + 5, 1, 4)
        # tblView.setSpan(2, data["CatOfAcftCount"][0] + 9, 1, 3)

        tblView.setSpan(1, data["CatOfAcftCount"][0] + 3, 1, 2)
        tblView.setSpan(2, data["CatOfAcftCount"][0] + 3, 1, 2)
        tblView.setSpan(3, data["CatOfAcftCount"][0] + 3, 1, 2)
        tblView.setSpan(4, data["CatOfAcftCount"][0] + 3, 1, 2)
        tblView.setSpan(5, data["CatOfAcftCount"][0] + 3, 1, 2)
        tblView.setSpan(6, data["CatOfAcftCount"][0] + 3, 1, 2)

    def stdModel_itemChanged(self, item):
        if item.row() != 1 and item.row() != 3:
            return
        self.calcTimeRate()
        self.calcALT()

    def calcALT(self):
        thrAlt = Unit.ConvertFeetToMeter(self.data["ThrAltitude"])
        rdhAlt = Unit.ConvertFeetToMeter(self.data["RDHAltitude"])
        gradient = self.data["DescentGradient"]
        dx = self.data["dX"]

        for i in range(7):
            item = self.stdModel.item(1,
                                      self.data["CatOfAcftCount"][0] + 5 + i)
            val = 0.0
            try:
                val = float(item.text())
            except:
                continue
            dist = val * 1852
            valueHgt = Unit.ConvertFeetToMeter(
                (dist - dx) * math.tan(Unit.ConvertDegToRad(gradient)))
            valueAlt = valueHgt + thrAlt + rdhAlt
            if valueAlt > int(valueAlt):
                valueAlt = int(valueAlt) + 1
            if valueHgt > int(valueHgt):
                valueHgt = int(valueHgt) + 1

            itemTemp = QStandardItem(
                str(valueAlt) + "\n(" + str(valueHgt) + ")")
            itemTemp.setTextAlignment(Qt.AlignCenter)
            self.stdModel.setItem(2, self.data["CatOfAcftCount"][0] + 5 + i,
                                  itemTemp)

    def calcTimeRate(self):
        for i in range(6):
            item = self.stdModel.item(3,
                                      self.data["CatOfAcftCount"][0] + 6 + i)
            val = 0.0
            try:
                val = float(item.text())
            except:
                continue
            time = (3600 * self.data["Distance"]) / val
            minute = int(time / 60)
            second = int(time % 60)

            timeStr = str(minute) + " : " + str(second)
            if second == 0:
                timeStr = str(minute) + " : " + "00"
            elif second < 10:
                timeStr = str(minute) + " : 0" + str(second)
            itemTemp = QStandardItem(timeStr)
            itemTemp.setTextAlignment(Qt.AlignCenter)
            self.stdModel.setItem(4, self.data["CatOfAcftCount"][0] + 6 + i,
                                  itemTemp)

            rate = int(
                (val * 6076.1 *
                 (AngleGradientSlope(self.data["DescentGradient"]).Percent /
                  float(100))) / float(60))
            itemTemp = QStandardItem(str(rate))
            itemTemp.setTextAlignment(Qt.AlignCenter)
            self.stdModel.setItem(5, self.data["CatOfAcftCount"][0] + 6 + i,
                                  itemTemp)
Exemplo n.º 21
0
class TestQgsAtlasComposition(unittest.TestCase):
    def testCase(self):
        self.TEST_DATA_DIR = unitTestDataPath()
        tmppath = tempfile.mkdtemp()
        for file in glob.glob(
                os.path.join(self.TEST_DATA_DIR, 'france_parts.*')):
            shutil.copy(os.path.join(self.TEST_DATA_DIR, file), tmppath)
        vectorFileInfo = QFileInfo(tmppath + "/france_parts.shp")
        mVectorLayer = QgsVectorLayer(vectorFileInfo.filePath(),
                                      vectorFileInfo.completeBaseName(), "ogr")

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

        # create composition with composer map
        mMapRenderer = QgsMapRenderer()
        layerStringList = []
        layerStringList.append(mVectorLayer.id())
        mMapRenderer.setLayerSet(layerStringList)
        mMapRenderer.setProjectionsEnabled(True)
        mMapRenderer.setMapUnits(QGis.Meters)

        # select epsg:2154
        crs = QgsCoordinateReferenceSystem()
        crs.createFromSrid(2154)
        mMapRenderer.setDestinationCrs(crs)

        self.mComposition = QgsComposition(mMapRenderer)
        self.mComposition.setPaperSize(297, 210)

        # fix the renderer, fill with green
        props = {"color": "0,127,0"}
        fillSymbol = QgsFillSymbolV2.createSimple(props)
        renderer = QgsSingleSymbolRendererV2(fillSymbol)
        mVectorLayer.setRendererV2(renderer)

        # the atlas map
        self.mAtlasMap = QgsComposerMap(self.mComposition, 20, 20, 130, 130)
        self.mAtlasMap.setFrameEnabled(True)
        self.mComposition.addComposerMap(self.mAtlasMap)

        # the atlas
        self.mAtlas = self.mComposition.atlasComposition()
        self.mAtlas.setCoverageLayer(mVectorLayer)
        self.mAtlas.setEnabled(True)
        self.mComposition.setAtlasMode(QgsComposition.ExportAtlas)

        # an overview
        mOverview = QgsComposerMap(self.mComposition, 180, 20, 50, 50)
        mOverview.setFrameEnabled(True)
        mOverview.setOverviewFrameMap(self.mAtlasMap.id())
        self.mComposition.addComposerMap(mOverview)
        nextent = QgsRectangle(49670.718, 6415139.086, 699672.519, 7065140.887)
        mOverview.setNewExtent(nextent)

        # set the fill symbol of the overview map
        props2 = {"color": "127,0,0,127"}
        fillSymbol2 = QgsFillSymbolV2.createSimple(props2)
        mOverview.setOverviewFrameMapSymbol(fillSymbol2)

        # header label
        self.mLabel1 = QgsComposerLabel(self.mComposition)
        self.mComposition.addComposerLabel(self.mLabel1)
        self.mLabel1.setText("[% \"NAME_1\" %] area")
        self.mLabel1.setFont(QgsFontUtils.getStandardTestFont())
        self.mLabel1.adjustSizeToText()
        self.mLabel1.setSceneRect(QRectF(150, 5, 60, 15))

        qWarning(
            "header label font: %s exactMatch:%s" %
            (self.mLabel1.font().toString(), self.mLabel1.font().exactMatch()))

        # feature number label
        self.mLabel2 = QgsComposerLabel(self.mComposition)
        self.mComposition.addComposerLabel(self.mLabel2)
        self.mLabel2.setText("# [%$feature || ' / ' || $numfeatures%]")
        self.mLabel2.setFont(QgsFontUtils.getStandardTestFont())
        self.mLabel2.adjustSizeToText()
        self.mLabel2.setSceneRect(QRectF(150, 200, 60, 15))

        qWarning(
            "feature number label font: %s exactMatch:%s" %
            (self.mLabel2.font().toString(), self.mLabel2.font().exactMatch()))

        self.filename_test()
        self.autoscale_render_test()
        self.autoscale_render_test_old_api()
        self.fixedscale_render_test()
        self.predefinedscales_render_test()
        self.hidden_render_test()

        shutil.rmtree(tmppath, True)

    def filename_test(self):
        self.mAtlas.setFilenamePattern("'output_' || $feature")
        self.mAtlas.beginRender()
        for i in range(0, self.mAtlas.numFeatures()):
            self.mAtlas.prepareForFeature(i)
            expected = "output_%d" % (i + 1)
            assert self.mAtlas.currentFilename() == expected
        self.mAtlas.endRender()

    def autoscale_render_test(self):
        self.mAtlasMap.setAtlasDriven(True)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Auto)
        self.mAtlasMap.setAtlasMargin(0.10)

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_autoscale%d' % (i + 1),
                                            self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

        self.mAtlasMap.setAtlasDriven(False)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
        self.mAtlasMap.setAtlasMargin(0)

    def autoscale_render_test_old_api(self):
        self.mAtlas.setComposerMap(self.mAtlasMap)
        self.mAtlas.setFixedScale(False)
        self.mAtlas.setMargin(0.10)

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker(
                'atlas_autoscale_old_api%d' % (i + 1), self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

        self.mAtlas.setFixedScale(True)
        self.mAtlas.setMargin(0)
        self.mAtlas.setComposerMap(None)
        self.mAtlasMap.setAtlasDriven(False)

    def fixedscale_render_test(self):
        self.mAtlasMap.setNewExtent(
            QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
        self.mAtlasMap.setAtlasDriven(True)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_fixedscale%d' % (i + 1),
                                            self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

    def predefinedscales_render_test(self):
        self.mAtlasMap.setNewExtent(
            QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
        self.mAtlasMap.setAtlasDriven(True)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Predefined)

        scales = [1800000, 5000000]
        self.mAtlas.setPredefinedScales(scales)
        for i, s in enumerate(self.mAtlas.predefinedScales()):
            assert s == scales[i]

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker(
                'atlas_predefinedscales%d' % (i + 1), self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

    def hidden_render_test(self):
        self.mAtlasMap.setNewExtent(
            QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
        self.mAtlas.setHideCoverage(True)

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_hiding%d' % (i + 1),
                                            self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

    def sorting_render_test(self):
        self.mAtlasMap.setNewExtent(
            QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
        self.mAtlas.setHideCoverage(False)

        self.mAtlas.setSortFeatures(True)
        self.mAtlas.setSortKeyAttributeIndex(4)  # departement name
        self.mAtlas.setSortAscending(False)

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_sorting%d' % (i + 1),
                                            self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

    def filtering_render_test(self):
        self.mAtlasMap.setNewExtent(
            QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
        self.mAtlas.setHideCoverage(False)

        self.mAtlas.setSortFeatures(False)

        self.mAtlas.setFilterFeatures(True)
        self.mAtlas.setFeatureFilter(
            "substr(NAME_1,1,1)='P'")  # select only 'Pays de la loire'

        self.mAtlas.beginRender()

        for i in range(0, 1):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_filtering%d' % (i + 1),
                                            self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()
Exemplo n.º 22
0
class previewDlg(QMainWindow):
    '''
    classdocs
    '''
    def __init__(self, parent, comp, basePMCheck, model):
        '''
        Constructor
        '''

        QMainWindow.__init__(self, parent)

        self.basePMCheck = basePMCheck
        #         self.ui = Ui_Previewself.grbPageProperty()
        #         self.ui.setupUi(self)
        self.resize(1000, 700)
        self.setWindowTitle("Preview Dialog")
        self.view = QgsComposerView(self)
        viewLayout = QGridLayout()
        viewLayout.setSpacing(0)
        viewLayout.setMargin(0)
        mHorizontalRuler = QgsComposerRuler(QgsComposerRuler.Horizontal)
        mVerticalRuler = QgsComposerRuler(QgsComposerRuler.Vertical)
        mRulerLayoutFix = QWidget()
        mRulerLayoutFix.setAttribute(Qt.WA_NoMousePropagation)
        mRulerLayoutFix.setBackgroundRole(QPalette.Window)
        mRulerLayoutFix.setFixedSize(mVerticalRuler.rulerSize(),
                                     mHorizontalRuler.rulerSize())
        viewLayout.addWidget(mRulerLayoutFix, 0, 0)
        viewLayout.addWidget(mHorizontalRuler, 0, 1)
        viewLayout.addWidget(mVerticalRuler, 1, 0)

        self.view.setContentsMargins(0, 0, 0, 0)
        self.view.setHorizontalRuler(mHorizontalRuler)
        self.view.setVerticalRuler(mVerticalRuler)
        viewLayout.addWidget(self.view, 1, 1)

        #         self.scene = comp

        self.view.setZoomLevel(1.0)
        self.view.setComposition(comp)
        self.scene = self.view.composition()
        layout = QVBoxLayout()
        hLayout = QHBoxLayout()
        hLayout.addLayout(viewLayout)

        self.mapItem = self.scene.getComposerMapById(0)

        self.view.scale(2.8, 2.8)
        self.view.setPreviewModeEnabled(True)

        self.toolBarAction = self.addToolBar("composer action")
        self.actionMapRefresh = QAction(self)
        self.actionMapRefresh.setObjectName("actionMapRefresh")
        icon3 = QIcon("Resource/Refresh.png")
        self.actionMapRefresh.setIcon(icon3)
        self.actionMapRefresh.setToolTip("Refresh")
        # self.textItemAction.setCheckable(True)
        self.connect(self.actionMapRefresh, SIGNAL("triggered()"),
                     self.actionMapRefresh_triggered)
        self.toolBarAction.addAction(self.actionMapRefresh)

        # # self.templeteCreateAction = QAction(self)
        # # self.templeteCreateAction.setObjectName("createTempleteAction")
        # # icon4 = QIcon("Resource\\templetepointer.png")
        # # self.templeteCreateAction.setIcon(icon4)
        # # self.templeteCreateAction.setToolTip("Create Templete")
        # # self.templeteCreateAction.setCheckable(True)
        # # self.connect(self.templeteCreateAction, SIGNAL("triggered()"), self.createTempleteAction)
        # # self.toolBar.addAction(self.templeteCreateAction)
        # layout.insertWidget(0, self.toolBar)

        #         self.scene.selectedItemChanged.connect(self.selectedItemDisplay)
        self.view.selectedItemChanged.connect(self.selectedItemDisplay)

        self.view.cursorPosChanged.connect(self.cursorPosChangedEvent)
        #         self.connect(self.view, SIGNAL("selectedItemChanged(QgsComposerItem)"),self, SLOT("selectedItemDisplay(QgsComposerItem)"))
        #         self.scene.composerLabelAdded.connect(self.composerLabelAddedEvent)
        self.view.itemRemoved.connect(self.deleteItem)
        # self.connect( self.view, SIGNAL( "actionFinished()" ), self.setSelectionTool)

        #listen out for position updates from the QgsComposerView
        self.propertyWidget = QWidget(self)
        hLayout.addWidget(self.propertyWidget)
        self.propertyWidget.setObjectName("propertyWidget")
        self.propertyWidget.resize(222, 302)
        self.vLayout_3 = QVBoxLayout(self.propertyWidget)
        self.vLayout_3.setObjectName("vLayout_3")
        self.groupBox = QGroupBox(self.propertyWidget)
        self.groupBox.setObjectName("groupBox")
        self.horizontalLayout_2 = QHBoxLayout(self.groupBox)
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.frame = QFrame(self.groupBox)
        self.frame.setFrameShape(QFrame.StyledPanel)
        self.frame.setFrameShadow(QFrame.Raised)
        self.frame.setObjectName("frame")
        self.verticalLayout = QVBoxLayout(self.frame)
        self.verticalLayout.setObjectName("verticalLayout")
        self.label = QLabel(self.frame)
        self.label.setObjectName("label")
        self.verticalLayout.addWidget(self.label)
        self.labelText = QPlainTextEdit(self.frame)
        self.labelText.setObjectName("labelText")
        self.verticalLayout.addWidget(self.labelText)
        self.btnLabelFont = QPushButton(self.frame)
        self.btnLabelFont.setObjectName("btnLabelFont")
        self.verticalLayout.addWidget(self.btnLabelFont)
        self.btnLabelColor = QPushButton(self.frame)
        self.btnLabelColor.setObjectName("btnLabelColor")
        self.verticalLayout.addWidget(self.btnLabelColor)
        self.frame_2 = QFrame(self.frame)
        self.frame_2.setFrameShape(QFrame.StyledPanel)
        self.frame_2.setFrameShadow(QFrame.Raised)
        self.frame_2.setObjectName("frame_2")
        self.horizontalLayout = QHBoxLayout(self.frame_2)
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.label_2 = QLabel(self.frame_2)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout.addWidget(self.label_2)
        self.spinLabelRotation = QSpinBox(self.frame_2)
        self.spinLabelRotation.setObjectName("spinLabelRotation")
        self.spinLabelRotation.setMinimum(-360)
        self.spinLabelRotation.setMaximum(360)
        self.horizontalLayout.addWidget(self.spinLabelRotation)
        self.verticalLayout.addWidget(self.frame_2)
        self.chbBackgroundEnable = QCheckBox(self.frame)
        self.chbBackgroundEnable.setChecked(True)
        self.chbBackgroundEnable.setObjectName("chbBackgroundEnable")
        self.verticalLayout.addWidget(self.chbBackgroundEnable)
        self.horizontalLayout_2.addWidget(self.frame)
        self.vLayout_3.addWidget(self.groupBox)

        self.resolutionFrame = QFrame(self.frame)
        self.resolutionFrame.setFrameShape(QFrame.StyledPanel)
        self.resolutionFrame.setFrameShadow(QFrame.Raised)
        self.resolutionFrame.setObjectName("resolutionFrame")
        self.horizontalLayout4 = QHBoxLayout(self.resolutionFrame)
        self.horizontalLayout4.setObjectName("horizontalLayout4")
        self.label_resolution = QLabel(self.resolutionFrame)
        self.label_resolution.setObjectName("label_resolution")
        self.label_resolution.setText("Print Resolution (dpi):")
        self.horizontalLayout4.addWidget(self.label_resolution)
        self.spinResolution = QSpinBox(self.resolutionFrame)
        self.spinResolution.setObjectName("spinResolution")
        self.spinResolution.setMinimum(0)
        self.spinResolution.setMaximum(1000)
        self.spinResolution.setValue(300)
        self.horizontalLayout4.addWidget(self.spinResolution)
        #         self.verticalLayout.addWidget(self.frame_2)
        self.vLayout_3.addWidget(self.resolutionFrame)

        self.gbTable = GroupBox(self.propertyWidget)
        self.gbTable.Caption = "Table"
        self.vLayout_3.addWidget(self.gbTable)

        self.mTableView = QTableView(self.gbTable)
        self.gbTable.Add = self.mTableView
        hHeder = self.mTableView.horizontalHeader()
        hHeder.setVisible(False)
        vHeder = self.mTableView.verticalHeader()
        vHeder.setVisible(False)
        # self.mTableView.setFixedHeight(70)
        # self.mTableView.setFixedWidth(comp.paperWidth() - 40)

        # self.stdItemModel = QStandardItemModel()
        # self.

        self.spaceItem = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                     QSizePolicy.Expanding)
        self.vLayout_3.addItem(self.spaceItem)

        self.groupBox.setTitle("Label Property")
        self.label.setText("Label Text:")
        self.btnLabelFont.setText("Label Font")
        self.btnLabelColor.setText("Label Color")
        self.label_2.setText("Label Rotation:")
        self.chbBackgroundEnable.setText("Background Enable")
        self.groupBox.setEnabled(False)
        self.connect(self.btnLabelFont, SIGNAL("clicked()"),
                     self.btnLabelFontClick)
        self.connect(self.btnLabelColor, SIGNAL("clicked()"),
                     self.btnLabelColorClick)
        self.connect(self.chbBackgroundEnable, SIGNAL("clicked()"),
                     self.chbBackgroundEnableClick)
        self.labelText.textChanged.connect(self.labelTextChanged)
        self.spinLabelRotation.valueChanged.connect(
            self.spinLabelRotationValueChanged)
        layout.addLayout(hLayout)
        #
        self.btnBack = QPushButton()
        self.btnBack.setText("back")
        footerLayout = QHBoxLayout()
        footerLayout.addWidget(self.btnBack)

        self.buttonBox = QDialogButtonBox(self)
        self.buttonBox.setOrientation(Qt.Horizontal)
        self.buttonBox.setStandardButtons(QDialogButtonBox.Cancel
                                          | QDialogButtonBox.Ok)
        self.buttonBox.setObjectName("buttonBox")
        footerLayout.addWidget(self.buttonBox)
        layout.addLayout(footerLayout)
        self.setLayout(layout)

        deleteItemKey = QShortcut(QKeySequence(Qt.Key_Delete), self)
        deleteItemKey.activated.connect(self.deleteItem)

        # self.btnBack.clicked.connect(self.back)
        self.connect(self.buttonBox, SIGNAL("accepted()"), self.acceptMethod)
        self.connect(self.buttonBox, SIGNAL("rejected()"), self.reject)
        self.btnCancel = self.buttonBox.button(QDialogButtonBox.Cancel)
        self.view.setCurrentTool(QgsComposerView.Select)

        self.btnLabelColor.setVisible(False)
        # self.btnBack.setVisible(False)
        self.chbBackgroundEnable.setVisible(False)
        #         self.view.emit(SIGNAL("actionFinished"))

        #         if self.scene.plotStyle() != QgsComposition.Preview:
        #         self.scene.setPlotStyle(QgsComposition.Preview)
        #         self.mapItem.setPreviewMode(QgsComposerMap.Render)
        #         self.mapItem.updateCachedImage()
        #         self.mapItem.setSelected(True)
        self.mComposition = comp
        self.composerMapItem = self.mComposition.composerMapItems()[0]
        self.composerMapItem.setUpdatesEnabled(True)
        self.mStdModel = model

        self.mTableView.setModel(self.mStdModel)
        self.mTableView.setSpan(0, 0, 1, 6)
        self.mTableView.setSpan(1, 0, 1, 2)
        self.mTableView.setSpan(2, 0, 2, 1)
        self.mTableView.setSpan(4, 0, 1, 2)
        self.mTableView.setSpan(5, 0, 1, 2)
        self.mTableView.setSpan(6, 0, 1, 2)

        self.mTableView.setSpan(0, 6, 1, 8)
        self.mTableView.setSpan(1, 7, 1, 4)
        self.mTableView.setSpan(1, 11, 1, 3)
        self.mTableView.setSpan(2, 7, 1, 4)
        self.mTableView.setSpan(2, 11, 1, 3)

    def acceptMethod(self):
        # self.mStdModel.setItem(0, QStandardItem("nnnnnnnn"))
        filePath = QFileDialog.getSaveFileName(
            self, "Save PDF File", QCoreApplication.applicationDirPath(),
            "pdf files(*.pdf )")
        if filePath == "":
            return
        self.mComposition.clearSelection()
        self.mComposition.setPrintResolution(self.spinResolution.value())
        resultPdf = self.mComposition.exportAsPDF(filePath)
        if resultPdf:
            message = QMessageBox.information(self, "Result",
                                              "Successful export PDF")
        else:
            message = QMessageBox.information(self, "Result",
                                              "Don't export PDF")

    def rePresent(self, comp, model):
        self.mComposition = comp
        self.mStdModel = model
        self.view.setComposition(comp)
        self.scene = self.view.composition()

    def back(self):
        self.done(2)

    def spinLabelRotationValueChanged(self, rotationValue):
        self.selectedLabelItem.setItemRotation(rotationValue)

    def cursorPosChangedEvent(self, scenePointF):
        self.scenePoint = scenePointF
#         i = 100

    def labelTextChanged(self):
        self.selectedLabelItem.beginCommand(
            "Label text changed", QgsComposerMergeCommand.ComposerLabelSetText)
        self.selectedLabelItem.blockSignals(True)
        self.selectedLabelItem.setText(self.labelText.toPlainText())
        self.selectedLabelItem.update()
        self.selectedLabelItem.blockSignals(False)
        self.selectedLabelItem.endCommand()

    def chbBackgroundEnableClick(self):
        if self.chbBackgroundEnable.isChecked():
            self.selectedLabelItem.setBackgroundEnabled(True)
            self.mapItem.updateCachedImage()
        else:
            self.selectedLabelItem.setBackgroundEnabled(False)
            self.mapItem.updateCachedImage()

    def btnLabelFontClick(self):
        dlgFont = QFontDialog(self)
        dlgFont.setCurrentFont(self.selectedLabelItem.font())
        result = dlgFont.exec_()
        if result == 1:
            self.labelFont = dlgFont.selectedFont()
        else:
            self.labelFont = QFont()

        self.selectedLabelItem.setFont(self.labelFont)

    def btnLabelColorClick(self):
        dlgColor = QColorDialog(self)
        dlgColor.setCurrentColor(self.selectedLabelItem.fontColor())
        result = dlgColor.exec_()
        if result == 1:
            self.labelColor = dlgColor.selectedColor()
            self.selectedLabelItem.setFontColor(self.labelColor)

    def createTempleteAction(self):
        if self.templeteCreateAction.isChecked() and self.basePMCheck:
            font = QFont("Arial", 13)
            font.setItalic(True)
            self.compLabel1 = QgsComposerLabel(self.scene)
            self.compLabel1.setFont(font)
            self.compLabel1.setText("South China Sea")
            self.compLabel1.setBackgroundEnabled(False)
            self.compLabel1.setItemPosition(156, 100)
            self.compLabel1.adjustSizeToText()
            self.compLabel1.setItemRotation(60)
            #             mapitem = self.scene.composerMapItems()
            #             mapitem[0].addItem(self.compLabel1)
            self.scene.addItem(self.compLabel1)

            self.compLabel2 = QgsComposerLabel(self.scene)
            self.compLabel2.setFont(font)
            self.compLabel2.setText("Straits Of Malacca")
            self.compLabel2.setBackgroundEnabled(False)
            self.compLabel2.setItemPosition(35, 100)
            self.compLabel2.adjustSizeToText()
            self.compLabel2.setItemRotation(60)
            self.scene.addItem(self.compLabel2)

            font.setItalic(False)
            self.compLabel3 = QgsComposerLabel(self.scene)
            self.compLabel3.setFont(font)
            self.compLabel3.setBackgroundEnabled(False)
            self.compLabel3.setText("THAILAND")
            self.compLabel3.setItemPosition(68, 60)
            self.compLabel3.adjustSizeToText()
            #             self.compLabel3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel3)
            #             self.templeteCreateAction.setChecked(False)

            self.compLabel4 = QgsComposerLabel(self.scene)
            self.compLabel4.setFont(font)
            self.compLabel4.setBackgroundEnabled(False)
            self.compLabel4.setText("SINGAPORE")
            self.compLabel4.setItemPosition(141, 218)
            self.compLabel4.adjustSizeToText()
            #             self.compLabel3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel4)
            self.templeteCreateAction.setChecked(False)
            self.compLabel4.setSelected(True)
        elif self.templeteCreateAction.isChecked(
        ) and self.basePMCheck == False:
            font = QFont("Arial", 14)
            font.setItalic(True)
            self.compLabel5 = QgsComposerLabel(self.scene)
            self.compLabel5.setFont(font)
            self.compLabel5.setText("South China Sea")
            self.compLabel5.setBackgroundEnabled(False)
            self.compLabel5.setItemPosition(108, 86)
            self.compLabel5.adjustSizeToText()
            self.compLabel5.setItemRotation(-45)
            #             mapitem = self.scene.composerMapItems()
            #             mapitem[0].addItem(self.compLabel1)
            self.scene.addItem(self.compLabel5)

            self.compLabel6 = QgsComposerLabel(self.scene)
            self.compLabel6.setFont(font)
            self.compLabel6.setText("Sulu Sea")
            self.compLabel6.setBackgroundEnabled(False)
            self.compLabel6.setItemPosition(236, 38)
            self.compLabel6.adjustSizeToText()
            self.compLabel6.setItemRotation(45)
            self.scene.addItem(self.compLabel6)

            font.setItalic(False)
            self.compLabel7 = QgsComposerLabel(self.scene)
            self.compLabel7.setFont(font)
            self.compLabel7.setBackgroundEnabled(False)
            self.compLabel7.setText("Celebes Sea")
            self.compLabel7.setItemPosition(242, 112)
            self.compLabel7.adjustSizeToText()
            self.compLabel7.setItemRotation(-45)
            #             self.compLabel3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel7)
            #             self.templeteCreateAction.setChecked(False)

            self.compLabel8 = QgsComposerLabel(self.scene)
            self.compLabel8.setFont(font)
            self.compLabel8.setBackgroundEnabled(False)
            self.compLabel8.setText("INDONESIA\n(Kalimantan)")
            self.compLabel8.setItemPosition(172, 148, 32, 16)
            #             self.compLabel8.setHAlign(Qt.AlignHCenter)
            #             self.compLabel8.setVAlign(Qt.AlignVCenter)
            #             self.compLabel8.setFrameEnabled(False)
            #             self.compLabel8.setItemPosition()
            #             self.compLabel8.adjustSizeToText()
            #             self.compLabl3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel8)

            self.compLabel9 = QgsComposerLabel(self.scene)
            self.compLabel9.setFont(font)
            self.compLabel9.setBackgroundEnabled(False)
            self.compLabel9.setText("BRUNEI")
            self.compLabel9.setItemPosition(136, 83)
            self.compLabel9.adjustSizeToText()
            #             self.compLabl3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel9)
            self.templeteCreateAction.setChecked(False)

        pass

    def actionMapRefresh_triggered(self):

        self.view.setCurrentTool(QgsComposerView.AddRectangle)

    def setSelectionTool(self):
        self.view.deleteSelectedItems()
        font = QFont("Arial", 14)
        newLabelItem = QgsComposerLabel(self.scene)
        newLabelItem.setText("QGIS")
        newLabelItem.setFont(font)

        newLabelItem.setItemPosition(self.scenePoint.x(), self.scenePoint.y())
        newLabelItem.adjustSizeToText()

        self.scene.addItem(newLabelItem)
        #         selectItemPoint = self.scene.composerItemAt(self.scenePoint)
        newLabelItem.setSelected(True)
        self.groupBox.setEnabled(True)
        self.selectedLabelItem = newLabelItem
        #         txt = self.selectedLabelItem.text()
        #         textDoc = QTextDocument(txt)
        self.labelText.setPlainText(self.selectedLabelItem.text())
        #         self.scene.setSelectedItem(self.newLabelItem)

        self.view.setCurrentTool(QgsComposerView.Select)
        #         self.selectedLabelItem = self.view.currentTool()
        self.textItemAction.setChecked(False)

    def selectedItemDisplay(self, item):

        if self.scene.plotStyle() != QgsComposition.Preview:
            self.scene.setPlotStyle(QgsComposition.Preview)
            self.mapItem.setPreviewMode(QgsComposerMap.Render)
            self.mapItem.updateCachedImage()
        item._class_ = QgsComposerLabel
        #         selectedItems = self.scene.selectedComposerItems(True)
        #         if isinstance(item, QgsComposerItem):
        #             self.selectedLabelItem = item
        #         if isinstance(item, QGraphicsRectItem):
        #             self.selectedLabelItem = item
        if isinstance(item, QgsComposerLabel):
            self.selectedLabelItem = item
            self.groupBox.setEnabled(True)
            self.labelText.setPlainText(self.selectedLabelItem.text())
            self.spinLabelRotation.setValue(self.selectedLabelItem.rotation())
        else:
            self.groupBox.setEnabled(False)
#         print "debug"
        itemName = self.view.currentTool()
        if itemName == 5:
            item.setText("label")
        pass

    def deleteItem(self):
        self.view.deleteSelectedItems()
Exemplo n.º 23
0
    def createTempleteAction(self):
        if self.templeteCreateAction.isChecked() and self.basePMCheck:
            font = QFont("Arial", 13)
            font.setItalic(True)
            self.compLabel1 = QgsComposerLabel(self.scene)
            self.compLabel1.setFont(font)
            self.compLabel1.setText("South China Sea")
            self.compLabel1.setBackgroundEnabled(False)
            self.compLabel1.setItemPosition(156, 100)
            self.compLabel1.adjustSizeToText()
            self.compLabel1.setItemRotation(60)
            #             mapitem = self.scene.composerMapItems()
            #             mapitem[0].addItem(self.compLabel1)
            self.scene.addItem(self.compLabel1)

            self.compLabel2 = QgsComposerLabel(self.scene)
            self.compLabel2.setFont(font)
            self.compLabel2.setText("Straits Of Malacca")
            self.compLabel2.setBackgroundEnabled(False)
            self.compLabel2.setItemPosition(35, 100)
            self.compLabel2.adjustSizeToText()
            self.compLabel2.setItemRotation(60)
            self.scene.addItem(self.compLabel2)

            font.setItalic(False)
            self.compLabel3 = QgsComposerLabel(self.scene)
            self.compLabel3.setFont(font)
            self.compLabel3.setBackgroundEnabled(False)
            self.compLabel3.setText("THAILAND")
            self.compLabel3.setItemPosition(68, 60)
            self.compLabel3.adjustSizeToText()
            #             self.compLabel3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel3)
            #             self.templeteCreateAction.setChecked(False)

            self.compLabel4 = QgsComposerLabel(self.scene)
            self.compLabel4.setFont(font)
            self.compLabel4.setBackgroundEnabled(False)
            self.compLabel4.setText("SINGAPORE")
            self.compLabel4.setItemPosition(141, 218)
            self.compLabel4.adjustSizeToText()
            #             self.compLabel3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel4)
            self.templeteCreateAction.setChecked(False)
            self.compLabel4.setSelected(True)
        elif self.templeteCreateAction.isChecked(
        ) and self.basePMCheck == False:
            font = QFont("Arial", 14)
            font.setItalic(True)
            self.compLabel5 = QgsComposerLabel(self.scene)
            self.compLabel5.setFont(font)
            self.compLabel5.setText("South China Sea")
            self.compLabel5.setBackgroundEnabled(False)
            self.compLabel5.setItemPosition(108, 86)
            self.compLabel5.adjustSizeToText()
            self.compLabel5.setItemRotation(-45)
            #             mapitem = self.scene.composerMapItems()
            #             mapitem[0].addItem(self.compLabel1)
            self.scene.addItem(self.compLabel5)

            self.compLabel6 = QgsComposerLabel(self.scene)
            self.compLabel6.setFont(font)
            self.compLabel6.setText("Sulu Sea")
            self.compLabel6.setBackgroundEnabled(False)
            self.compLabel6.setItemPosition(236, 38)
            self.compLabel6.adjustSizeToText()
            self.compLabel6.setItemRotation(45)
            self.scene.addItem(self.compLabel6)

            font.setItalic(False)
            self.compLabel7 = QgsComposerLabel(self.scene)
            self.compLabel7.setFont(font)
            self.compLabel7.setBackgroundEnabled(False)
            self.compLabel7.setText("Celebes Sea")
            self.compLabel7.setItemPosition(242, 112)
            self.compLabel7.adjustSizeToText()
            self.compLabel7.setItemRotation(-45)
            #             self.compLabel3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel7)
            #             self.templeteCreateAction.setChecked(False)

            self.compLabel8 = QgsComposerLabel(self.scene)
            self.compLabel8.setFont(font)
            self.compLabel8.setBackgroundEnabled(False)
            self.compLabel8.setText("INDONESIA\n(Kalimantan)")
            self.compLabel8.setItemPosition(172, 148, 32, 16)
            #             self.compLabel8.setHAlign(Qt.AlignHCenter)
            #             self.compLabel8.setVAlign(Qt.AlignVCenter)
            #             self.compLabel8.setFrameEnabled(False)
            #             self.compLabel8.setItemPosition()
            #             self.compLabel8.adjustSizeToText()
            #             self.compLabl3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel8)

            self.compLabel9 = QgsComposerLabel(self.scene)
            self.compLabel9.setFont(font)
            self.compLabel9.setBackgroundEnabled(False)
            self.compLabel9.setText("BRUNEI")
            self.compLabel9.setItemPosition(136, 83)
            self.compLabel9.adjustSizeToText()
            #             self.compLabl3.setItemRotation(0.5)
            self.scene.addItem(self.compLabel9)
            self.templeteCreateAction.setChecked(False)

        pass
Exemplo n.º 24
0
    def setSelectionTool(self):
        self.view.deleteSelectedItems()
        font = QFont("Arial", 14)
        newLabelItem = QgsComposerLabel(self.scene)
        newLabelItem.setText("QGIS")
        newLabelItem.setFont(font)

        newLabelItem.setItemPosition(self.scenePoint.x(), self.scenePoint.y())
        newLabelItem.adjustSizeToText()

        self.scene.addItem(newLabelItem)
        #         selectItemPoint = self.scene.composerItemAt(self.scenePoint)
        newLabelItem.setSelected(True)
        self.groupBox.setEnabled(True)
        self.selectedLabelItem = newLabelItem
        #         txt = self.selectedLabelItem.text()
        #         textDoc = QTextDocument(txt)
        self.labelText.setPlainText(self.selectedLabelItem.text())
        #         self.scene.setSelectedItem(self.newLabelItem)

        self.view.setCurrentTool(QgsComposerView.Select)
        #         self.selectedLabelItem = self.view.currentTool()
        self.textItemAction.setChecked(False)
Exemplo n.º 25
0
class TestQgsAtlasComposition(unittest.TestCase):
    def testCase(self):
        self.TEST_DATA_DIR = unitTestDataPath()
        tmppath = tempfile.mkdtemp()
        for file in glob.glob(
                os.path.join(self.TEST_DATA_DIR, 'france_parts.*')):
            shutil.copy(os.path.join(self.TEST_DATA_DIR, file), tmppath)
        vectorFileInfo = QFileInfo(tmppath + "/france_parts.shp")
        mVectorLayer = QgsVectorLayer(vectorFileInfo.filePath(),
                                      vectorFileInfo.completeBaseName(), "ogr")

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

        # create composition with composer map
        self.mapSettings = QgsMapSettings()
        layerStringList = []
        layerStringList.append(mVectorLayer.id())
        self.mapSettings.setLayers(layerStringList)
        self.mapSettings.setCrsTransformEnabled(True)
        self.mapSettings.setMapUnits(QgsUnitTypes.DistanceMeters)

        # select epsg:2154
        crs = QgsCoordinateReferenceSystem()
        crs.createFromSrid(2154)
        self.mapSettings.setDestinationCrs(crs)

        self.mComposition = QgsComposition(self.mapSettings)
        self.mComposition.setPaperSize(297, 210)

        # fix the renderer, fill with green
        props = {"color": "0,127,0"}
        fillSymbol = QgsFillSymbol.createSimple(props)
        renderer = QgsSingleSymbolRenderer(fillSymbol)
        mVectorLayer.setRenderer(renderer)

        # the atlas map
        self.mAtlasMap = QgsComposerMap(self.mComposition, 20, 20, 130, 130)
        self.mAtlasMap.setFrameEnabled(True)
        self.mComposition.addComposerMap(self.mAtlasMap)

        # the atlas
        self.mAtlas = self.mComposition.atlasComposition()
        self.mAtlas.setCoverageLayer(mVectorLayer)
        self.mAtlas.setEnabled(True)
        self.mComposition.setAtlasMode(QgsComposition.ExportAtlas)

        # an overview
        mOverview = QgsComposerMap(self.mComposition, 180, 20, 50, 50)
        mOverview.setFrameEnabled(True)
        mOverview.overview().setFrameMap(self.mAtlasMap.id())
        self.mComposition.addComposerMap(mOverview)
        nextent = QgsRectangle(49670.718, 6415139.086, 699672.519, 7065140.887)
        mOverview.setNewExtent(nextent)

        # set the fill symbol of the overview map
        props2 = {"color": "127,0,0,127"}
        fillSymbol2 = QgsFillSymbol.createSimple(props2)
        mOverview.overview().setFrameSymbol(fillSymbol2)

        # header label
        self.mLabel1 = QgsComposerLabel(self.mComposition)
        self.mComposition.addComposerLabel(self.mLabel1)
        self.mLabel1.setText("[% \"NAME_1\" %] area")
        self.mLabel1.setFont(QgsFontUtils.getStandardTestFont())
        self.mLabel1.adjustSizeToText()
        self.mLabel1.setSceneRect(QRectF(150, 5, 60, 15))

        qWarning(
            "header label font: %s exactMatch:%s" %
            (self.mLabel1.font().toString(), self.mLabel1.font().exactMatch()))

        # feature number label
        self.mLabel2 = QgsComposerLabel(self.mComposition)
        self.mComposition.addComposerLabel(self.mLabel2)
        self.mLabel2.setText(
            "# [%@atlas_featurenumber || ' / ' || @atlas_totalfeatures%]")
        self.mLabel2.setFont(QgsFontUtils.getStandardTestFont())
        self.mLabel2.adjustSizeToText()
        self.mLabel2.setSceneRect(QRectF(150, 200, 60, 15))

        qWarning(
            "feature number label font: %s exactMatch:%s" %
            (self.mLabel2.font().toString(), self.mLabel2.font().exactMatch()))

        self.filename_test()
        self.autoscale_render_test()
        self.fixedscale_render_test()
        self.predefinedscales_render_test()
        self.hidden_render_test()
        self.legend_test()

        shutil.rmtree(tmppath, True)

    def filename_test(self):
        self.mAtlas.setFilenamePattern("'output_' || @atlas_featurenumber")
        self.mAtlas.beginRender()
        for i in range(0, self.mAtlas.numFeatures()):
            self.mAtlas.prepareForFeature(i)
            expected = "output_%d" % (i + 1)
            assert self.mAtlas.currentFilename() == expected
        self.mAtlas.endRender()

    def autoscale_render_test(self):
        self.mAtlasMap.setAtlasDriven(True)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Auto)
        self.mAtlasMap.setAtlasMargin(0.10)

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_autoscale%d' % (i + 1),
                                            self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

        self.mAtlasMap.setAtlasDriven(False)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
        self.mAtlasMap.setAtlasMargin(0)

    def fixedscale_render_test(self):
        self.mAtlasMap.setNewExtent(
            QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
        self.mAtlasMap.setAtlasDriven(True)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_fixedscale%d' % (i + 1),
                                            self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

    def predefinedscales_render_test(self):
        self.mAtlasMap.setNewExtent(
            QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
        self.mAtlasMap.setAtlasDriven(True)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Predefined)

        scales = [1800000, 5000000]
        self.mAtlas.setPredefinedScales(scales)
        for i, s in enumerate(self.mAtlas.predefinedScales()):
            assert s == scales[i]

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker(
                'atlas_predefinedscales%d' % (i + 1), self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

    def hidden_render_test(self):
        self.mAtlasMap.setNewExtent(
            QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
        self.mAtlas.setHideCoverage(True)

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_hiding%d' % (i + 1),
                                            self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

        self.mAtlas.setHideCoverage(False)

    def sorting_render_test(self):
        self.mAtlasMap.setNewExtent(
            QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
        self.mAtlas.setHideCoverage(False)

        self.mAtlas.setSortFeatures(True)
        self.mAtlas.setSortKeyAttributeIndex(4)  # departement name
        self.mAtlas.setSortAscending(False)

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_sorting%d' % (i + 1),
                                            self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

    def filtering_render_test(self):
        self.mAtlasMap.setNewExtent(
            QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
        self.mAtlas.setHideCoverage(False)

        self.mAtlas.setSortFeatures(False)

        self.mAtlas.setFilterFeatures(True)
        self.mAtlas.setFeatureFilter(
            "substr(NAME_1,1,1)='P'")  # select only 'Pays de la loire'

        self.mAtlas.beginRender()

        for i in range(0, 1):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_filtering%d' % (i + 1),
                                            self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

    def legend_test(self):
        self.mAtlasMap.setAtlasDriven(True)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Auto)
        self.mAtlasMap.setAtlasMargin(0.10)

        # add a point layer
        ptLayer = QgsVectorLayer(
            "Point?crs=epsg:4326&field=attr:int(1)&field=label:string(20)",
            "points", "memory")

        pr = ptLayer.dataProvider()
        f1 = QgsFeature(1)
        f1.initAttributes(2)
        f1.setAttribute(0, 1)
        f1.setAttribute(1, "Test label 1")
        f1.setGeometry(QgsGeometry.fromPoint(QgsPoint(-0.638, 48.954)))
        f2 = QgsFeature(2)
        f2.initAttributes(2)
        f2.setAttribute(0, 2)
        f2.setAttribute(1, "Test label 2")
        f2.setGeometry(QgsGeometry.fromPoint(QgsPoint(-1.682, 48.550)))
        pr.addFeatures([f1, f2])

        # categorized symbology
        r = QgsCategorizedSymbolRenderer("attr", [
            QgsRendererCategory(
                1, QgsMarkerSymbol.createSimple({"color": "255,0,0"}), "red"),
            QgsRendererCategory(
                2, QgsMarkerSymbol.createSimple({"color": "0,0,255"}), "blue")
        ])
        ptLayer.setRenderer(r)

        QgsMapLayerRegistry.instance().addMapLayer(ptLayer)

        # add the point layer to the map settings
        layers = self.mapSettings.layers()
        layers = [ptLayer.id()] + layers
        self.mapSettings.setLayers(layers)

        # add a legend
        legend = QgsComposerLegend(self.mComposition)
        legend.moveBy(200, 100)
        # sets the legend filter parameter
        legend.setComposerMap(self.mAtlasMap)
        legend.setLegendFilterOutAtlas(True)
        self.mComposition.addComposerLegend(legend)

        self.mAtlas.beginRender()

        self.mAtlas.prepareForFeature(0)
        self.mLabel1.adjustSizeToText()

        checker = QgsCompositionChecker('atlas_legend', self.mComposition)
        myTestResult, myMessage = checker.testComposition()
        assert myTestResult

        self.mAtlas.endRender()

        # restore state
        self.mapSettings.setLayers([layers[1]])
        self.mComposition.removeComposerItem(legend)
        QgsMapLayerRegistry.instance().removeMapLayer(ptLayer.id())
Exemplo n.º 26
0
class TestQgsAtlasComposition(unittest.TestCase):

    def testCase(self):
        self.TEST_DATA_DIR = unitTestDataPath()
        tmppath = tempfile.mkdtemp()
        for file in glob.glob(os.path.join(self.TEST_DATA_DIR, 'france_parts.*')):
            shutil.copy(os.path.join(self.TEST_DATA_DIR, file), tmppath)
        vectorFileInfo = QFileInfo(tmppath + "/france_parts.shp")
        mVectorLayer = QgsVectorLayer(vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr")

        QgsProject.instance().addMapLayers([mVectorLayer])
        self.layers = [mVectorLayer]

        # create composition with composer map

        # select epsg:2154
        crs = QgsCoordinateReferenceSystem()
        crs.createFromSrid(2154)
        QgsProject.instance().setCrs(crs)

        self.mComposition = QgsComposition(QgsProject.instance())
        self.mComposition.setPaperSize(297, 210)

        # fix the renderer, fill with green
        props = {"color": "0,127,0"}
        fillSymbol = QgsFillSymbol.createSimple(props)
        renderer = QgsSingleSymbolRenderer(fillSymbol)
        mVectorLayer.setRenderer(renderer)

        # the atlas map
        self.mAtlasMap = QgsComposerMap(self.mComposition, 20, 20, 130, 130)
        self.mAtlasMap.setFrameEnabled(True)
        self.mAtlasMap.setLayers([mVectorLayer])
        self.mComposition.addComposerMap(self.mAtlasMap)

        # the atlas
        self.mAtlas = self.mComposition.atlasComposition()
        self.mAtlas.setCoverageLayer(mVectorLayer)
        self.mAtlas.setEnabled(True)
        self.mComposition.setAtlasMode(QgsComposition.ExportAtlas)

        # an overview
        self.mOverview = QgsComposerMap(self.mComposition, 180, 20, 50, 50)
        self.mOverview.setFrameEnabled(True)
        self.mOverview.overview().setFrameMap(self.mAtlasMap.id())
        self.mOverview.setLayers([mVectorLayer])
        self.mComposition.addComposerMap(self.mOverview)
        nextent = QgsRectangle(49670.718, 6415139.086, 699672.519, 7065140.887)
        self.mOverview.setNewExtent(nextent)

        # set the fill symbol of the overview map
        props2 = {"color": "127,0,0,127"}
        fillSymbol2 = QgsFillSymbol.createSimple(props2)
        self.mOverview.overview().setFrameSymbol(fillSymbol2)

        # header label
        self.mLabel1 = QgsComposerLabel(self.mComposition)
        self.mComposition.addComposerLabel(self.mLabel1)
        self.mLabel1.setText("[% \"NAME_1\" %] area")
        self.mLabel1.setFont(QgsFontUtils.getStandardTestFont())
        self.mLabel1.adjustSizeToText()
        self.mLabel1.setSceneRect(QRectF(150, 5, 60, 15))

        qWarning(
            "header label font: %s exactMatch:%s" % (self.mLabel1.font().toString(), self.mLabel1.font().exactMatch()))

        # feature number label
        self.mLabel2 = QgsComposerLabel(self.mComposition)
        self.mComposition.addComposerLabel(self.mLabel2)
        self.mLabel2.setText("# [%@atlas_featurenumber || ' / ' || @atlas_totalfeatures%]")
        self.mLabel2.setFont(QgsFontUtils.getStandardTestFont())
        self.mLabel2.adjustSizeToText()
        self.mLabel2.setSceneRect(QRectF(150, 200, 60, 15))

        qWarning("feature number label font: %s exactMatch:%s" % (
                 self.mLabel2.font().toString(), self.mLabel2.font().exactMatch()))

        self.filename_test()
        self.autoscale_render_test()
        self.fixedscale_render_test()
        self.predefinedscales_render_test()
        self.hidden_render_test()
        self.legend_test()
        self.rotation_test()

        shutil.rmtree(tmppath, True)

    def filename_test(self):
        self.mAtlas.setFilenamePattern("'output_' || @atlas_featurenumber")
        self.mAtlas.beginRender()
        for i in range(0, self.mAtlas.numFeatures()):
            self.mAtlas.prepareForFeature(i)
            expected = "output_%d" % (i + 1)
            self.assertEqual(self.mAtlas.currentFilename(), expected)
        self.mAtlas.endRender()

    def autoscale_render_test(self):
        self.mAtlasMap.setAtlasDriven(True)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Auto)
        self.mAtlasMap.setAtlasMargin(0.10)

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_autoscale%d' % (i + 1), self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

        self.mAtlasMap.setAtlasDriven(False)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
        self.mAtlasMap.setAtlasMargin(0)

    def fixedscale_render_test(self):
        self.mAtlasMap.setNewExtent(QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
        self.mAtlasMap.setAtlasDriven(True)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_fixedscale%d' % (i + 1), self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

    def predefinedscales_render_test(self):
        self.mAtlasMap.setNewExtent(QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
        self.mAtlasMap.setAtlasDriven(True)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Predefined)

        scales = [1800000, 5000000]
        self.mAtlas.setPredefinedScales(scales)
        for i, s in enumerate(self.mAtlas.predefinedScales()):
            assert s == scales[i]

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_predefinedscales%d' % (i + 1), self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

    def hidden_render_test(self):
        self.mAtlasMap.setNewExtent(QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
        self.mAtlas.setHideCoverage(True)

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_hiding%d' % (i + 1), self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

        self.mAtlas.setHideCoverage(False)

    def sorting_render_test(self):
        self.mAtlasMap.setNewExtent(QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
        self.mAtlas.setHideCoverage(False)

        self.mAtlas.setSortFeatures(True)
        self.mAtlas.setSortKeyAttributeIndex(4)  # departement name
        self.mAtlas.setSortAscending(False)

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_sorting%d' % (i + 1), self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

    def filtering_render_test(self):
        self.mAtlasMap.setNewExtent(QgsRectangle(209838.166, 6528781.020, 610491.166, 6920530.620))
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Fixed)
        self.mAtlas.setHideCoverage(False)

        self.mAtlas.setSortFeatures(False)

        self.mAtlas.setFilterFeatures(True)
        self.mAtlas.setFeatureFilter("substr(NAME_1,1,1)='P'")  # select only 'Pays de la loire'

        self.mAtlas.beginRender()

        for i in range(0, 1):
            self.mAtlas.prepareForFeature(i)
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_filtering%d' % (i + 1), self.mComposition)
            checker.setControlPathPrefix("atlas")
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

    def legend_test(self):
        self.mAtlasMap.setAtlasDriven(True)
        self.mAtlasMap.setAtlasScalingMode(QgsComposerMap.Auto)
        self.mAtlasMap.setAtlasMargin(0.10)

        # add a point layer
        ptLayer = QgsVectorLayer("Point?crs=epsg:4326&field=attr:int(1)&field=label:string(20)", "points", "memory")

        pr = ptLayer.dataProvider()
        f1 = QgsFeature(1)
        f1.initAttributes(2)
        f1.setAttribute(0, 1)
        f1.setAttribute(1, "Test label 1")
        f1.setGeometry(QgsGeometry.fromPoint(QgsPointXY(-0.638, 48.954)))
        f2 = QgsFeature(2)
        f2.initAttributes(2)
        f2.setAttribute(0, 2)
        f2.setAttribute(1, "Test label 2")
        f2.setGeometry(QgsGeometry.fromPoint(QgsPointXY(-1.682, 48.550)))
        pr.addFeatures([f1, f2])

        # categorized symbology
        r = QgsCategorizedSymbolRenderer("attr", [QgsRendererCategory(1, QgsMarkerSymbol.createSimple({"color": "255,0,0"}), "red"),
                                                  QgsRendererCategory(2, QgsMarkerSymbol.createSimple({"color": "0,0,255"}), "blue")])
        ptLayer.setRenderer(r)

        QgsProject.instance().addMapLayer(ptLayer)

        # add the point layer to the map settings
        layers = self.layers
        layers = [ptLayer] + layers
        self.mAtlasMap.setLayers(layers)
        self.mOverview.setLayers(layers)

        # add a legend
        legend = QgsComposerLegend(self.mComposition)
        legend.moveBy(200, 100)
        # sets the legend filter parameter
        legend.setComposerMap(self.mAtlasMap)
        legend.setLegendFilterOutAtlas(True)
        self.mComposition.addComposerLegend(legend)

        self.mAtlas.beginRender()

        self.mAtlas.prepareForFeature(0)
        self.mLabel1.adjustSizeToText()

        checker = QgsCompositionChecker('atlas_legend', self.mComposition)
        myTestResult, myMessage = checker.testComposition()
        assert myTestResult

        self.mAtlas.endRender()

        # restore state
        self.mAtlasMap.setLayers([layers[1]])
        self.mComposition.removeComposerItem(legend)
        QgsProject.instance().removeMapLayer(ptLayer.id())

    def rotation_test(self):
        # We will create a polygon layer with a rotated rectangle.
        # Then we will make it the object layer for the atlas,
        # rotate the map and test that the bounding rectangle
        # is smaller than the bounds without rotation.
        polygonLayer = QgsVectorLayer('Polygon', 'test_polygon', 'memory')
        poly = QgsFeature(polygonLayer.pendingFields())
        points = [(10, 15), (15, 10), (45, 40), (40, 45)]
        poly.setGeometry(QgsGeometry.fromPolygon([[QgsPointXY(x[0], x[1]) for x in points]]))
        polygonLayer.dataProvider().addFeatures([poly])
        QgsProject.instance().addMapLayer(polygonLayer)

        # Recreating the composer locally
        composition = QgsComposition(QgsProject.instance())
        composition.setPaperSize(297, 210)

        # the atlas map
        atlasMap = QgsComposerMap(composition, 20, 20, 130, 130)
        atlasMap.setFrameEnabled(True)
        atlasMap.setLayers([polygonLayer])
        atlasMap.setNewExtent(QgsRectangle(0, 0, 100, 50))
        composition.addComposerMap(atlasMap)

        # the atlas
        atlas = composition.atlasComposition()
        atlas.setCoverageLayer(polygonLayer)
        atlas.setEnabled(True)
        composition.setAtlasMode(QgsComposition.ExportAtlas)

        atlasMap.setAtlasDriven(True)
        atlasMap.setAtlasScalingMode(QgsComposerMap.Auto)
        atlasMap.setAtlasMargin(0.0)

        # Testing
        atlasMap.setMapRotation(0.0)
        atlas.firstFeature()
        nonRotatedExtent = QgsRectangle(atlasMap.currentMapExtent())

        atlasMap.setMapRotation(45.0)
        atlas.firstFeature()
        rotatedExtent = QgsRectangle(atlasMap.currentMapExtent())

        assert rotatedExtent.width() < nonRotatedExtent.width() * 0.9
        assert rotatedExtent.height() < nonRotatedExtent.height() * 0.9

        QgsProject.instance().removeMapLayer(polygonLayer)
Exemplo n.º 27
0
    def testDataDefinedFrameColor(self):
        mapSettings = QgsMapSettings()

        composition = QgsComposition(QgsProject.instance())
        composition.setPaperSize(297, 210)

        item = QgsComposerLabel(composition)
        composition.addComposerLabel(item)

        item.setFrameOutlineColor(QColor(255, 0, 0))
        self.assertEqual(item.frameOutlineColor(), QColor(255, 0, 0))
        self.assertEqual(item.pen().color().name(), QColor(255, 0, 0).name())

        item.dataDefinedProperties().setProperty(
            QgsComposerObject.FrameColor, QgsProperty.fromExpression("'blue'"))
        item.refreshDataDefinedProperty()
        self.assertEqual(item.frameOutlineColor(),
                         QColor(255, 0, 0))  # should not change
        self.assertEqual(item.pen().color().name(), QColor(0, 0, 255).name())
Exemplo n.º 28
0
    def draw_title(self, top_offset):
        """Add a title to the composition.

        :param top_offset: Vertical offset at which the logo should be drawn.
        :type top_offset: int

        :returns: The height of the label as rendered.
        :rtype: float
        """
        LOGGER.debug('InaSAFE Map drawTitle called')
        font_size = 14
        font_weight = QtGui.QFont.Bold
        italics_flag = False
        font = QtGui.QFont(
            'verdana',
            font_size,
            font_weight,
            italics_flag)
        label = QgsComposerLabel(self.composition)
        label.setFont(font)
        heading = self.tr(
            'InaSAFE - Indonesia Scenario Assessment for Emergencies')
        label.setText(heading)
        label.adjustSizeToText()
        label_height = 10.0  # determined using qgis map composer
        label_width = 170.0   # item - position and size...option
        left_offset = self.page_width - self.page_margin - label_width
        label.setItemPosition(
            left_offset,
            top_offset - 2,  # -2 to push it up a little
            label_width,
            label_height)
        label.setFrameEnabled(self.show_frames)
        self.composition.addItem(label)
        return label_height
Exemplo n.º 29
0
    def testDataDefinedBackgroundColor(self):
        mapSettings = QgsMapSettings()  # NOQA

        composition = QgsComposition(QgsProject.instance())
        composition.setPaperSize(297, 210)

        item = QgsComposerLabel(composition)
        composition.addComposerLabel(item)

        item.setBackgroundColor(QColor(255, 0, 0))
        self.assertEqual(item.backgroundColor(), QColor(255, 0, 0))
        self.assertEqual(item.brush().color().name(), QColor(255, 0, 0).name())

        item.dataDefinedProperties().setProperty(QgsComposerObject.BackgroundColor, QgsProperty.fromExpression("'blue'"))
        item.refreshDataDefinedProperty()
        self.assertEqual(item.backgroundColor(), QColor(255, 0, 0))  # should not change
        self.assertEqual(item.brush().color().name(), QColor(0, 0, 255).name())
Exemplo n.º 30
0
    def draw_scalebar(self, composer_map, top_offset):
        """Add a numeric scale to the bottom left of the map.

        We draw the scale bar manually because QGIS does not yet support
        rendering a scale bar for a geographic map in km.

        .. seealso:: :meth:`drawNativeScaleBar`

        :param composer_map: Composer map on which to draw the scalebar.
        :type composer_map: QgsComposerMap

        :param top_offset: Vertical offset at which the logo should be drawn.
        :type top_offset: int
        """
        LOGGER.debug('InaSAFE Map drawScaleBar called')
        canvas = self.iface.mapCanvas()
        renderer = canvas.mapRenderer()
        #
        # Add a linear map scale
        #
        distance_area = QgsDistanceArea()
        distance_area.setSourceCrs(renderer.destinationCrs().srsid())
        distance_area.setEllipsoidalMode(True)
        # Determine how wide our map is in km/m
        # Starting point at BL corner
        composer_extent = composer_map.extent()
        start_point = QgsPoint(
            composer_extent.xMinimum(),
            composer_extent.yMinimum())
        # Ending point at BR corner
        end_point = QgsPoint(
            composer_extent.xMaximum(),
            composer_extent.yMinimum())
        ground_distance = distance_area.measureLine(start_point, end_point)
        # Get the equivalent map distance per page mm
        map_width = self.mapWidth
        # How far is 1mm on map on the ground in meters?
        mm_to_ground = ground_distance / map_width
        #print 'MM:', myMMDistance
        # How long we want the scale bar to be in relation to the map
        scalebar_to_map_ratio = 0.5
        # How many divisions the scale bar should have
        tick_count = 5
        scale_bar_width_mm = map_width * scalebar_to_map_ratio
        print_segment_width_mm = scale_bar_width_mm / tick_count
        # Segment width in real world (m)
        # We apply some logic here so that segments are displayed in meters
        # if each segment is less that 1000m otherwise km. Also the segment
        # lengths are rounded down to human looking numbers e.g. 1km not 1.1km
        units = ''
        ground_segment_width = print_segment_width_mm * mm_to_ground
        if ground_segment_width < 1000:
            units = 'm'
            ground_segment_width = round(ground_segment_width)
            # adjust the segment width now to account for rounding
            print_segment_width_mm = ground_segment_width / mm_to_ground
        else:
            units = 'km'
            # Segment with in real world (km)
            ground_segment_width = round(ground_segment_width / 1000)
            print_segment_width_mm = (
                (ground_segment_width * 1000) / mm_to_ground)
        # Now adjust the scalebar width to account for rounding
        scale_bar_width_mm = tick_count * print_segment_width_mm

        #print "SBWMM:", scale_bar_width_mm
        #print "SWMM:", print_segment_width_mm
        #print "SWM:", myGroundSegmentWidthM
        #print "SWKM:", myGroundSegmentWidthKM
        # start drawing in line segments
        scalebar_height = 5  # mm
        line_width = 0.3  # mm
        inset_distance = 7  # how much to inset the scalebar into the map by
        scalebar_x = self.page_margin + inset_distance
        scalebar_y = (
            top_offset + self.map_height - inset_distance -
            scalebar_height)  # mm

        # Draw an outer background box - shamelessly hardcoded buffer
        rectangle = QgsComposerShape(
            scalebar_x - 4,  # left edge
            scalebar_y - 3,  # top edge
            scale_bar_width_mm + 13,  # right edge
            scalebar_height + 6,  # bottom edge
            self.composition)

        rectangle.setShapeType(QgsComposerShape.Rectangle)
        pen = QtGui.QPen()
        pen.setColor(QtGui.QColor(255, 255, 255))
        pen.setWidthF(line_width)
        rectangle.setPen(pen)
        #rectangle.setLineWidth(line_width)
        rectangle.setFrameEnabled(False)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        # workaround for missing setTransparentFill missing from python api
        rectangle.setBrush(brush)
        self.composition.addItem(rectangle)
        # Set up the tick label font
        font_weight = QtGui.QFont.Normal
        font_size = 6
        italics_flag = False
        font = QtGui.QFont(
            'verdana',
            font_size,
            font_weight,
            italics_flag)
        # Draw the bottom line
        up_shift = 0.3  # shift the bottom line up for better rendering
        rectangle = QgsComposerShape(
            scalebar_x,
            scalebar_y + scalebar_height - up_shift,
            scale_bar_width_mm,
            0.1,
            self.composition)

        rectangle.setShapeType(QgsComposerShape.Rectangle)
        pen = QtGui.QPen()
        pen.setColor(QtGui.QColor(255, 255, 255))
        pen.setWidthF(line_width)
        rectangle.setPen(pen)
        #rectangle.setLineWidth(line_width)
        rectangle.setFrameEnabled(False)
        self.composition.addItem(rectangle)

        # Now draw the scalebar ticks
        for tick_counter in range(0, tick_count + 1):
            distance_suffix = ''
            if tick_counter == tick_count:
                distance_suffix = ' ' + units
            real_world_distance = (
                '%.0f%s' %
                (tick_counter *
                ground_segment_width,
                distance_suffix))
            #print 'RW:', myRealWorldDistance
            mm_offset = scalebar_x + (
                tick_counter * print_segment_width_mm)
            #print 'MM:', mm_offset
            tick_height = scalebar_height / 2
            # Lines are not exposed by the api yet so we
            # bodge drawing lines using rectangles with 1px height or width
            tick_width = 0.1  # width or rectangle to be drawn
            uptick_line = QgsComposerShape(
                mm_offset,
                scalebar_y + scalebar_height - tick_height,
                tick_width,
                tick_height,
                self.composition)

            uptick_line.setShapeType(QgsComposerShape.Rectangle)
            pen = QtGui.QPen()
            pen.setWidthF(line_width)
            uptick_line.setPen(pen)
            #uptick_line.setLineWidth(line_width)
            uptick_line.setFrameEnabled(False)
            self.composition.addItem(uptick_line)
            #
            # Add a tick label
            #
            label = QgsComposerLabel(self.composition)
            label.setFont(font)
            label.setText(real_world_distance)
            label.adjustSizeToText()
            label.setItemPosition(
                mm_offset - 3,
                scalebar_y - tick_height)
            label.setFrameEnabled(self.show_frames)
            self.composition.addItem(label)
Exemplo n.º 31
0
class TestQgsAtlasComposition(unittest.TestCase):

    def testCase(self):
        self.TEST_DATA_DIR = unitTestDataPath()
        vectorFileInfo = QFileInfo( self.TEST_DATA_DIR + "/france_parts.shp")
        mVectorLayer = QgsVectorLayer( vectorFileInfo.filePath(), vectorFileInfo.completeBaseName(), "ogr" )

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

        # create composition with composer map
        mMapRenderer = QgsMapRenderer()
        layerStringList = []
        layerStringList.append( mVectorLayer.id() )
        mMapRenderer.setLayerSet( layerStringList )
        mMapRenderer.setProjectionsEnabled( True )
        mMapRenderer.setMapUnits( QGis.Meters )

        # select epsg:2154
        crs = QgsCoordinateReferenceSystem()
        crs.createFromSrid( 2154 )
        mMapRenderer.setDestinationCrs( crs )

        self.mComposition = QgsComposition( mMapRenderer )
        self.mComposition.setPaperSize( 297, 210 )

        # fix the renderer, fill with green
        props = { "color": "0,127,0" }
        fillSymbol = QgsFillSymbolV2.createSimple( props )
        renderer = QgsSingleSymbolRendererV2( fillSymbol )
        mVectorLayer.setRendererV2( renderer )

        # the atlas map
        self.mAtlasMap = QgsComposerMap( self.mComposition, 20, 20, 130, 130 )
        self.mAtlasMap.setFrameEnabled( True )
        self.mComposition.addComposerMap( self.mAtlasMap )

        # the atlas
        self.mAtlas = self.mComposition.atlasComposition()
        self.mAtlas.setCoverageLayer( mVectorLayer )
        self.mAtlas.setEnabled( True )
        self.mComposition.setAtlasMode( QgsComposition.ExportAtlas )

        # an overview
        mOverview = QgsComposerMap( self.mComposition, 180, 20, 50, 50 )
        mOverview.setFrameEnabled( True )
        mOverview.setOverviewFrameMap( self.mAtlasMap.id() )
        self.mComposition.addComposerMap( mOverview )
        nextent = QgsRectangle( 49670.718, 6415139.086, 699672.519, 7065140.887 )
        mOverview.setNewExtent( nextent )

        # set the fill symbol of the overview map
        props2 = { "color": "127,0,0,127" }
        fillSymbol2 = QgsFillSymbolV2.createSimple( props2 )
        mOverview.setOverviewFrameMapSymbol( fillSymbol2 )

        # header label
        self.mLabel1 = QgsComposerLabel( self.mComposition )
        self.mComposition.addComposerLabel( self.mLabel1 )
        self.mLabel1.setText( "[% \"NAME_1\" %] area" )
        self.mLabel1.setFont( QgsFontUtils.getStandardTestFont() )
        self.mLabel1.adjustSizeToText()
        self.mLabel1.setSceneRect( QRectF( 150, 5, 60, 15 ) )

        qWarning( "header label font: %s exactMatch:%s" % ( self.mLabel1.font().toString(), self.mLabel1.font().exactMatch() ) )

        # feature number label
        self.mLabel2 = QgsComposerLabel( self.mComposition )
        self.mComposition.addComposerLabel( self.mLabel2 )
        self.mLabel2.setText( "# [%$feature || ' / ' || $numfeatures%]" )
        self.mLabel2.setFont( QgsFontUtils.getStandardTestFont() )
        self.mLabel2.adjustSizeToText()
        self.mLabel2.setSceneRect( QRectF( 150, 200, 60, 15 ) )

        qWarning( "feature number label font: %s exactMatch:%s" % ( self.mLabel2.font().toString(), self.mLabel2.font().exactMatch() ) )

        self.filename_test()
        self.autoscale_render_test()
        self.autoscale_render_test_old_api()
        self.fixedscale_render_test()
        self.predefinedscales_render_test()
        self.hidden_render_test()

    def filename_test( self ):

        self.mAtlas.setFilenamePattern( "'output_' || $feature" )
        self.mAtlas.beginRender()
        for i in range(0, self.mAtlas.numFeatures()):
            self.mAtlas.prepareForFeature( i )
            expected =  "output_%d" % (i+1)
            assert self.mAtlas.currentFilename() == expected
        self.mAtlas.endRender()

    def autoscale_render_test( self ):
        self.mAtlasMap.setAtlasDriven( True )
        self.mAtlasMap.setAtlasScalingMode( QgsComposerMap.Auto )
        self.mAtlasMap.setAtlasMargin( 0.10 )

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature( i )
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_autoscale%d' % (i + 1), self.mComposition)
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

        self.mAtlasMap.setAtlasDriven( False )
        self.mAtlasMap.setAtlasScalingMode( QgsComposerMap.Fixed )
        self.mAtlasMap.setAtlasMargin( 0 )

    def autoscale_render_test_old_api( self ):
        self.mAtlas.setComposerMap( self.mAtlasMap )
        self.mAtlas.setFixedScale( False )
        self.mAtlas.setMargin( 0.10 )

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature( i )
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_autoscale_old_api%d' % (i + 1), self.mComposition)
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

        self.mAtlas.setFixedScale( True )
        self.mAtlas.setMargin( 0 )
        self.mAtlas.setComposerMap( None )
        self.mAtlasMap.setAtlasDriven( False )

    def fixedscale_render_test( self ):
        self.mAtlasMap.setAtlasDriven( True )
        self.mAtlasMap.setAtlasScalingMode( QgsComposerMap.Fixed )
        self.mAtlasMap.setNewExtent( QgsRectangle( 209838.166, 6528781.020, 610491.166, 6920530.620 ) )

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature( i )
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_fixedscale%d' % (i + 1), self.mComposition)
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

    def predefinedscales_render_test( self ):
        self.mAtlasMap.setAtlasDriven( True )
        self.mAtlasMap.setNewExtent( QgsRectangle( 209838.166, 6528781.020, 610491.166, 6920530.620 ) )
        self.mAtlasMap.setAtlasScalingMode( QgsComposerMap.Predefined )

        scales = [1800000, 5000000]
        self.mAtlas.setPredefinedScales( scales )
        for i, s in enumerate(self.mAtlas.predefinedScales()):
            assert s == scales[i]

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature( i )
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_predefinedscales%d' % (i + 1), self.mComposition)
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

    def hidden_render_test( self ):
        self.mAtlasMap.setNewExtent( QgsRectangle( 209838.166, 6528781.020, 610491.166, 6920530.620 ) )
        self.mAtlasMap.setAtlasScalingMode( QgsComposerMap.Fixed )
        self.mAtlas.setHideCoverage( True )

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature( i )
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_hiding%d' % (i + 1), self.mComposition)
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

    def sorting_render_test( self ):
        self.mAtlasMap.setNewExtent( QgsRectangle( 209838.166, 6528781.020, 610491.166, 6920530.620 ) )
        self.mAtlasMap.setAtlasScalingMode( QgsComposerMap.Fixed )
        self.mAtlas.setHideCoverage( False )

        self.mAtlas.setSortFeatures( True )
        self.mAtlas.setSortKeyAttributeIndex( 4 ) # departement name
        self.mAtlas.setSortAscending( False )

        self.mAtlas.beginRender()

        for i in range(0, 2):
            self.mAtlas.prepareForFeature( i )
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_sorting%d' % (i + 1), self.mComposition)
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()

    def filtering_render_test( self ):
        self.mAtlasMap.setNewExtent( QgsRectangle( 209838.166, 6528781.020, 610491.166, 6920530.620 ) )
        self.mAtlasMap.setAtlasScalingMode( QgsComposerMap.Fixed )
        self.mAtlas.setHideCoverage( False )

        self.mAtlas.setSortFeatures( False )

        self.mAtlas.setFilterFeatures( True )
        self.mAtlas.setFeatureFilter( "substr(NAME_1,1,1)='P'" ) # select only 'Pays de la loire'

        self.mAtlas.beginRender()

        for i in range(0, 1):
            self.mAtlas.prepareForFeature( i )
            self.mLabel1.adjustSizeToText()

            checker = QgsCompositionChecker('atlas_filtering%d' % (i + 1), self.mComposition)
            myTestResult, myMessage = checker.testComposition(0, 200)

            assert myTestResult
        self.mAtlas.endRender()
Exemplo n.º 32
0
    def draw_host_and_time(self, top_offset):
        """Add a note with hostname and time to the composition.

        :param top_offset: Vertical offset at which the logo should be drawn.
        :type top_offset: int
        """
        LOGGER.debug('InaSAFE Map drawDisclaimer called')
        #elapsed_time: 11.612545
        #user: timlinux
        #host_name: ultrabook
        #time_stamp: 2012-10-13_23:10:31
        #myUser = self.keywordIO.readKeywords(self.layer, 'user')
        #myHost = self.keywordIO.readKeywords(self.layer, 'host_name')
        myDateTime = self.keywordIO.read_keywords(self.layer, 'time_stamp')
        myTokens = myDateTime.split('_')
        myDate = myTokens[0]
        myTime = myTokens[1]
        #myElapsedTime = self.keywordIO.readKeywords(self.layer,
        #                                            'elapsed_time')
        #myElapsedTime = humaniseSeconds(myElapsedTime)
        myLongVersion = get_version()
        myTokens = myLongVersion.split('.')
        myVersion = '%s.%s.%s' % (myTokens[0], myTokens[1], myTokens[2])
        myLabelText = self.tr(
            'Date and time of assessment: %s %s\n'
            'Special note: This assessment is a guide - we strongly recommend '
            'that you ground truth the results shown here before deploying '
            'resources and / or personnel.\n'
            'Assessment carried out using InaSAFE release %s (QGIS '
            'plugin version).') % (myDate, myTime, myVersion)
        myFontSize = 6
        myFontWeight = QtGui.QFont.Normal
        myItalicsFlag = True
        myFont = QtGui.QFont('verdana',
                             myFontSize,
                             myFontWeight,
                             myItalicsFlag)
        myLabel = QgsComposerLabel(self.composition)
        myLabel.setFont(myFont)
        myLabel.setText(myLabelText)
        myLabel.adjustSizeToText()
        myLabelHeight = 50.0  # mm determined using qgis map composer
        myLabelWidth = (self.pageWidth / 2) - self.pageMargin
        myLeftOffset = self.pageWidth / 2  # put in right half of page
        myLabel.setItemPosition(myLeftOffset,
                                top_offset,
                                myLabelWidth,
                                myLabelHeight,
                                )
        myLabel.setFrameEnabled(self.showFramesFlag)
        self.composition.addItem(myLabel)
Exemplo n.º 33
0
    def draw_title(self, top_offset):
        """Add a title to the composition.

        :param top_offset: Vertical offset at which the logo should be drawn.
        :type top_offset: int

        :returns: The height of the label as rendered.
        :rtype: float
        """
        LOGGER.debug('InaSAFE Map drawTitle called')
        myFontSize = 14
        myFontWeight = QtGui.QFont.Bold
        myItalicsFlag = False
        myFont = QtGui.QFont('verdana',
                             myFontSize,
                             myFontWeight,
                             myItalicsFlag)
        myLabel = QgsComposerLabel(self.composition)
        myLabel.setFont(myFont)
        myHeading = self.tr('InaSAFE - Indonesia Scenario Assessment'
                            ' for Emergencies')
        myLabel.setText(myHeading)
        myLabel.adjustSizeToText()
        myLabelHeight = 10.0  # determined using qgis map composer
        myLabelWidth = 170.0   # item - position and size...option
        myLeftOffset = self.pageWidth - self.pageMargin - myLabelWidth
        myLabel.setItemPosition(myLeftOffset,
                                top_offset - 2,  # -2 to push it up a little
                                myLabelWidth,
                                myLabelHeight,
                                )
        myLabel.setFrameEnabled(self.showFramesFlag)
        self.composition.addItem(myLabel)
        return myLabelHeight
Exemplo n.º 34
0
    def draw_title(self, top_offset):
        """Add a title to the composition.

        :param top_offset: Vertical offset at which the logo should be drawn.
        :type top_offset: int

        :returns: The height of the label as rendered.
        :rtype: float
        """
        LOGGER.debug('InaSAFE Map drawTitle called')
        font_size = 14
        font_weight = QtGui.QFont.Bold
        italics_flag = False
        font = QtGui.QFont('verdana', font_size, font_weight, italics_flag)
        label = QgsComposerLabel(self.composition)
        label.setFont(font)
        heading = self.tr(
            'InaSAFE - Indonesia Scenario Assessment for Emergencies')
        label.setText(heading)
        label.adjustSizeToText()
        label_height = 10.0  # determined using qgis map composer
        label_width = 170.0  # item - position and size...option
        left_offset = self.page_width - self.page_margin - label_width
        label.setItemPosition(
            left_offset,
            top_offset - 2,  # -2 to push it up a little
            label_width,
            label_height)
        label.setFrameEnabled(self.show_frames)
        self.composition.addItem(label)
        return label_height
Exemplo n.º 35
0
    def draw_host_and_time(self, top_offset):
        """Add a note with hostname and time to the composition.

        :param top_offset: Vertical offset at which the logo should be drawn.
        :type top_offset: int
        """
        LOGGER.debug('InaSAFE Map drawDisclaimer called')
        #elapsed_time: 11.612545
        #user: timlinux
        #host_name: ultrabook
        #time_stamp: 2012-10-13_23:10:31
        #myUser = self.keyword_io.readKeywords(self.layer, 'user')
        #myHost = self.keyword_io.readKeywords(self.layer, 'host_name')
        date_time = self.keyword_io.read_keywords(self.layer, 'time_stamp')
        tokens = date_time.split('_')
        date = tokens[0]
        time = tokens[1]
        #myElapsedTime = self.keyword_io.readKeywords(self.layer,
        #                                            'elapsed_time')
        #myElapsedTime = humaniseSeconds(myElapsedTime)
        long_version = get_version()
        tokens = long_version.split('.')
        version = '%s.%s.%s' % (tokens[0], tokens[1], tokens[2])
        label_text = self.tr(
            'Date and time of assessment: %s %s\n'
            'Special note: This assessment is a guide - we strongly recommend '
            'that you ground truth the results shown here before deploying '
            'resources and / or personnel.\n'
            'Assessment carried out using InaSAFE release %s (QGIS '
            'plugin version).') % (date, time, version)
        font_size = 6
        font_weight = QtGui.QFont.Normal
        italics_flag = True
        font = QtGui.QFont(
            'verdana',
            font_size,
            font_weight,
            italics_flag)
        label = QgsComposerLabel(self.composition)
        label.setFont(font)
        label.setText(label_text)
        label.adjustSizeToText()
        label_height = 50.0  # mm determined using qgis map composer
        label_width = (self.page_width / 2) - self.page_margin
        left_offset = self.page_width / 2  # put in right half of page
        label.setItemPosition(
            left_offset,
            top_offset,
            label_width,
            label_height,)
        label.setFrameEnabled(self.show_frames)
        self.composition.addItem(label)
Exemplo n.º 36
0
    def draw_scalebar(self, composer_map, top_offset):
        """Add a numeric scale to the bottom left of the map.

        We draw the scale bar manually because QGIS does not yet support
        rendering a scale bar for a geographic map in km.

        .. seealso:: :meth:`drawNativeScaleBar`

        :param composer_map: Composer map on which to draw the scalebar.
        :type composer_map: QgsComposerMap

        :param top_offset: Vertical offset at which the logo should be drawn.
        :type top_offset: int
        """
        LOGGER.debug('InaSAFE Map drawScaleBar called')
        canvas = self.iface.mapCanvas()
        renderer = canvas.mapRenderer()
        #
        # Add a linear map scale
        #
        distance_area = QgsDistanceArea()
        distance_area.setSourceCrs(renderer.destinationCrs().srsid())
        distance_area.setEllipsoidalMode(True)
        # Determine how wide our map is in km/m
        # Starting point at BL corner
        composer_extent = composer_map.extent()
        start_point = QgsPoint(composer_extent.xMinimum(),
                               composer_extent.yMinimum())
        # Ending point at BR corner
        end_point = QgsPoint(composer_extent.xMaximum(),
                             composer_extent.yMinimum())
        ground_distance = distance_area.measureLine(start_point, end_point)
        # Get the equivalent map distance per page mm
        map_width = self.mapWidth
        # How far is 1mm on map on the ground in meters?
        mm_to_ground = ground_distance / map_width
        #print 'MM:', myMMDistance
        # How long we want the scale bar to be in relation to the map
        scalebar_to_map_ratio = 0.5
        # How many divisions the scale bar should have
        tick_count = 5
        scale_bar_width_mm = map_width * scalebar_to_map_ratio
        print_segment_width_mm = scale_bar_width_mm / tick_count
        # Segment width in real world (m)
        # We apply some logic here so that segments are displayed in meters
        # if each segment is less that 1000m otherwise km. Also the segment
        # lengths are rounded down to human looking numbers e.g. 1km not 1.1km
        units = ''
        ground_segment_width = print_segment_width_mm * mm_to_ground
        if ground_segment_width < 1000:
            units = 'm'
            ground_segment_width = round(ground_segment_width)
            # adjust the segment width now to account for rounding
            print_segment_width_mm = ground_segment_width / mm_to_ground
        else:
            units = 'km'
            # Segment with in real world (km)
            ground_segment_width = round(ground_segment_width / 1000)
            print_segment_width_mm = ((ground_segment_width * 1000) /
                                      mm_to_ground)
        # Now adjust the scalebar width to account for rounding
        scale_bar_width_mm = tick_count * print_segment_width_mm

        #print "SBWMM:", scale_bar_width_mm
        #print "SWMM:", print_segment_width_mm
        #print "SWM:", myGroundSegmentWidthM
        #print "SWKM:", myGroundSegmentWidthKM
        # start drawing in line segments
        scalebar_height = 5  # mm
        line_width = 0.3  # mm
        inset_distance = 7  # how much to inset the scalebar into the map by
        scalebar_x = self.page_margin + inset_distance
        scalebar_y = (top_offset + self.map_height - inset_distance -
                      scalebar_height)  # mm

        # Draw an outer background box - shamelessly hardcoded buffer
        rectangle = QgsComposerShape(
            scalebar_x - 4,  # left edge
            scalebar_y - 3,  # top edge
            scale_bar_width_mm + 13,  # right edge
            scalebar_height + 6,  # bottom edge
            self.composition)

        rectangle.setShapeType(QgsComposerShape.Rectangle)
        pen = QtGui.QPen()
        pen.setColor(QtGui.QColor(255, 255, 255))
        pen.setWidthF(line_width)
        rectangle.setPen(pen)
        #rectangle.setLineWidth(line_width)
        rectangle.setFrameEnabled(False)
        brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
        # workaround for missing setTransparentFill missing from python api
        rectangle.setBrush(brush)
        self.composition.addItem(rectangle)
        # Set up the tick label font
        font_weight = QtGui.QFont.Normal
        font_size = 6
        italics_flag = False
        font = QtGui.QFont('verdana', font_size, font_weight, italics_flag)
        # Draw the bottom line
        up_shift = 0.3  # shift the bottom line up for better rendering
        rectangle = QgsComposerShape(scalebar_x,
                                     scalebar_y + scalebar_height - up_shift,
                                     scale_bar_width_mm, 0.1, self.composition)

        rectangle.setShapeType(QgsComposerShape.Rectangle)
        pen = QtGui.QPen()
        pen.setColor(QtGui.QColor(255, 255, 255))
        pen.setWidthF(line_width)
        rectangle.setPen(pen)
        #rectangle.setLineWidth(line_width)
        rectangle.setFrameEnabled(False)
        self.composition.addItem(rectangle)

        # Now draw the scalebar ticks
        for tick_counter in range(0, tick_count + 1):
            distance_suffix = ''
            if tick_counter == tick_count:
                distance_suffix = ' ' + units
            real_world_distance = (
                '%.0f%s' %
                (tick_counter * ground_segment_width, distance_suffix))
            #print 'RW:', myRealWorldDistance
            mm_offset = scalebar_x + (tick_counter * print_segment_width_mm)
            #print 'MM:', mm_offset
            tick_height = scalebar_height / 2
            # Lines are not exposed by the api yet so we
            # bodge drawing lines using rectangles with 1px height or width
            tick_width = 0.1  # width or rectangle to be drawn
            uptick_line = QgsComposerShape(
                mm_offset, scalebar_y + scalebar_height - tick_height,
                tick_width, tick_height, self.composition)

            uptick_line.setShapeType(QgsComposerShape.Rectangle)
            pen = QtGui.QPen()
            pen.setWidthF(line_width)
            uptick_line.setPen(pen)
            #uptick_line.setLineWidth(line_width)
            uptick_line.setFrameEnabled(False)
            self.composition.addItem(uptick_line)
            #
            # Add a tick label
            #
            label = QgsComposerLabel(self.composition)
            label.setFont(font)
            label.setText(real_world_distance)
            label.adjustSizeToText()
            label.setItemPosition(mm_offset - 3, scalebar_y - tick_height)
            label.setFrameEnabled(self.show_frames)
            self.composition.addItem(label)
Exemplo n.º 37
0
 def draw_disclaimer(self):
     """Add a disclaimer to the composition."""
     LOGGER.debug('InaSAFE Map drawDisclaimer called')
     myFontSize = 10
     myFontWeight = QtGui.QFont.Normal
     myItalicsFlag = True
     myFont = QtGui.QFont('verdana',
                          myFontSize,
                          myFontWeight,
                          myItalicsFlag)
     myLabel = QgsComposerLabel(self.composition)
     myLabel.setFont(myFont)
     myLabel.setText(self.disclaimer)
     myLabel.adjustSizeToText()
     myLabelHeight = 7.0  # mm determined using qgis map composer
     myLabelWidth = self.pageWidth   # item - position and size...option
     myLeftOffset = self.pageMargin
     myTopOffset = self.pageHeight - self.pageMargin
     myLabel.setItemPosition(myLeftOffset,
                             myTopOffset,
                             myLabelWidth,
                             myLabelHeight,
                             )
     myLabel.setFrameEnabled(self.showFramesFlag)
     self.composition.addItem(myLabel)
    def buildComposerLabel(self, key, item, page):
        '''
        Add a QgsLabel to composition for an item and page
        '''
        cl = QgsComposerLabel(self.currentComposition)

        # 1st page is a map for parcelle
        dpage = page - 1
        if self.etype == 'parcelle' and self.iface:
            dpage = page

        cl.setItemPosition(
            item['position'][0],
            item['position'][1] + (dpage) * (self.pageHeight + 10),
            item['position'][2], item['position'][3], False, -1)
        cl.setVAlign(item['align'][0])
        cl.setHAlign(item['align'][1])
        content = self.getContentForGivenItem(key, item, page)

        cl.setMargin(0)
        cl.setHtmlState(2)
        cl.setText(content)
        cl.setFrameEnabled(False)
        if 'bgcolor' in item:
            cl.setBackgroundColor(item['bgcolor'])
        if 'htmlState' in item:
            cl.setHtmlState(item['htmlState'])
        if 'font' in item:
            cl.setFont(item['font'])
        self.currentComposition.addItem(cl)