예제 #1
0
 def fetchColors(self, context='', baseColor=QColor()):
     if (context == "testscheme"):
         return [[QColor(255, 255, 0), 'schemetest']]
     elif baseColor.isValid():
         return [[baseColor, 'base']]
     else:
         return [[QColor(255, 0, 0), 'red'], [QColor(0, 255, 0), None]]
예제 #2
0
    def testInteriorTicks(self):
        self.mComposerMap.setGridFrameStyle(QgsComposerMap.Zebra)
        myRectangle = QgsRectangle(781662.375, 3339523.125, 793062.375,
                                   3345223.125)
        self.mComposerMap.setNewExtent(myRectangle)
        self.mComposerMap.grid().setIntervalX(2000)
        self.mComposerMap.grid().setIntervalY(2000)
        self.mComposerMap.grid().setAnnotationFontColor(QColor(0, 0, 0))
        self.mComposerMap.grid().setBlendMode(
            QPainter.CompositionMode_SourceOver)
        self.mComposerMap.grid().setFrameStyle(
            QgsComposerMapGrid.InteriorTicks)
        self.mComposerMap.grid().setFrameWidth(10)
        self.mComposerMap.grid().setFramePenSize(1)
        self.mComposerMap.grid().setFramePenColor(QColor(0, 0, 0))
        self.mComposerMap.grid().setEnabled(True)
        self.mComposerMap.grid().setStyle(
            QgsComposerMapGrid.FrameAnnotationsOnly)
        self.mComposerMap.updateBoundingRect()

        checker = QgsCompositionChecker('composermap_interiorticks',
                                        self.mComposition)
        checker.setControlPathPrefix("composer_mapgrid")
        myTestResult, myMessage = checker.testComposition(0, 100)
        assert myTestResult, myMessage
예제 #3
0
    def testZebraStyle(self):
        self.mComposerMap.setGridFrameStyle(QgsComposerMap.Zebra)
        myRectangle = QgsRectangle(785462.375, 3341423.125, 789262.375,
                                   3343323.125)
        self.mComposerMap.setNewExtent(myRectangle)
        self.mComposerMap.grid().setIntervalX(2000)
        self.mComposerMap.grid().setIntervalY(2000)
        self.mComposerMap.grid().setGridLineColor(QColor(0, 0, 0))
        self.mComposerMap.grid().setAnnotationFontColor(QColor(0, 0, 0))
        self.mComposerMap.grid().setBlendMode(
            QPainter.CompositionMode_SourceOver)
        self.mComposerMap.grid().setFrameStyle(QgsComposerMapGrid.Zebra)
        self.mComposerMap.grid().setFrameWidth(10)
        self.mComposerMap.grid().setFramePenSize(1)
        self.mComposerMap.grid().setGridLineWidth(0.5)
        self.mComposerMap.grid().setFramePenColor(QColor(255, 100, 0, 200))
        self.mComposerMap.grid().setFrameFillColor1(QColor(50, 90, 50, 100))
        self.mComposerMap.grid().setFrameFillColor2(QColor(200, 220, 100, 60))
        self.mComposerMap.grid().setEnabled(True)
        self.mComposerMap.updateBoundingRect()

        checker = QgsCompositionChecker('composermap_zebrastyle',
                                        self.mComposition)
        checker.setControlPathPrefix("composer_mapgrid")
        myTestResult, myMessage = checker.testComposition(0, 100)
        assert myTestResult, myMessage
예제 #4
0
 def testColorsNoBase(self):
     """Test getting colors without passing a base color"""
     dummyScheme = DummyColorScheme()
     colors = dummyScheme.fetchColors()
     self.assertEqual(len(colors), 2)
     self.assertEqual(colors[0][0], QColor(255, 0, 0))
     self.assertEqual(colors[0][1], 'red')
     self.assertEqual(colors[1][0], QColor(0, 255, 0))
     self.assertEqual(colors[1][1], None)
예제 #5
0
 def paint(self, painter, option, widget=None):
     rect = QRectF(-(ModelerGraphicItem.BOX_WIDTH + 2) / 2.0,
                   -(ModelerGraphicItem.BOX_HEIGHT + 2) / 2.0,
                   ModelerGraphicItem.BOX_WIDTH + 2,
                   ModelerGraphicItem.BOX_HEIGHT + 2)
     painter.setPen(QPen(Qt.gray, 1))
     color = QColor(125, 232, 232)
     if isinstance(self.element, ModelerParameter):
         color = QColor(179, 179, 255)
     elif isinstance(self.element, Algorithm):
         color = Qt.white
     painter.setBrush(QBrush(color, Qt.SolidPattern))
     painter.drawRect(rect)
     font = QFont('Verdana', 8)
     painter.setFont(font)
     painter.setPen(QPen(Qt.black))
     text = self.getAdjustedText(self.text)
     if isinstance(self.element, Algorithm) and not self.element.active:
         painter.setPen(QPen(Qt.gray))
         text = text + "\n(deactivated)"
     elif self.isSelected():
         painter.setPen(QPen(Qt.blue))
     fm = QFontMetricsF(font)
     text = self.getAdjustedText(self.text)
     h = fm.height()
     pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 25, h / 2.0)
     painter.drawText(pt, text)
     painter.setPen(QPen(Qt.black))
     if isinstance(self.element, Algorithm):
         h = -(fm.height() * 1.2)
         h = h - ModelerGraphicItem.BOX_HEIGHT / 2.0 + 5
         pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 25, h)
         painter.drawText(pt, 'In')
         i = 1
         if not self.element.paramsFolded:
             for param in self.element.algorithm.parameters:
                 if not param.hidden:
                     text = self.getAdjustedText(param.description)
                     h = -(fm.height() * 1.2) * (i + 1)
                     h = h - ModelerGraphicItem.BOX_HEIGHT / 2.0 + 5
                     pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 33, h)
                     painter.drawText(pt, text)
                     i += 1
         h = fm.height() * 1.2
         h = h + ModelerGraphicItem.BOX_HEIGHT / 2.0
         pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 25, h)
         painter.drawText(pt, 'Out')
         if not self.element.outputsFolded:
             for i, out in enumerate(self.element.algorithm.outputs):
                 text = self.getAdjustedText(out.description)
                 h = fm.height() * 1.2 * (i + 2)
                 h = h + ModelerGraphicItem.BOX_HEIGHT / 2.0
                 pt = QPointF(-ModelerGraphicItem.BOX_WIDTH / 2 + 33, h)
                 painter.drawText(pt, text)
     if self.pixmap:
         painter.drawPixmap(-(ModelerGraphicItem.BOX_WIDTH / 2.0) + 3, -8,
                            self.pixmap)
예제 #6
0
    def testZebraStyleSides(self):
        self.mComposerMap.setGridFrameStyle(QgsComposerMap.Zebra)
        myRectangle = QgsRectangle(781662.375, 3339523.125, 793062.375,
                                   3345223.125)
        self.mComposerMap.setNewExtent(myRectangle)
        self.mComposerMap.grid().setIntervalX(2000)
        self.mComposerMap.grid().setIntervalY(2000)
        self.mComposerMap.grid().setGridLineColor(QColor(0, 0, 0))
        self.mComposerMap.grid().setAnnotationFontColor(QColor(0, 0, 0))
        self.mComposerMap.grid().setBlendMode(
            QPainter.CompositionMode_SourceOver)
        self.mComposerMap.grid().setFrameStyle(QgsComposerMapGrid.Zebra)
        self.mComposerMap.grid().setFrameWidth(10)
        self.mComposerMap.grid().setFramePenSize(1)
        self.mComposerMap.grid().setGridLineWidth(0.5)
        self.mComposerMap.grid().setFramePenColor(QColor(0, 0, 0))
        self.mComposerMap.grid().setFrameFillColor1(QColor(0, 0, 0))
        self.mComposerMap.grid().setFrameFillColor2(QColor(255, 255, 255))
        self.mComposerMap.grid().setEnabled(True)

        self.mComposerMap.grid().setFrameSideFlag(QgsComposerMapGrid.FrameLeft,
                                                  True)
        self.mComposerMap.grid().setFrameSideFlag(
            QgsComposerMapGrid.FrameRight, False)
        self.mComposerMap.grid().setFrameSideFlag(QgsComposerMapGrid.FrameTop,
                                                  False)
        self.mComposerMap.grid().setFrameSideFlag(
            QgsComposerMapGrid.FrameBottom, False)
        self.mComposerMap.updateBoundingRect()

        checker = QgsCompositionChecker('composermap_zebrastyle_left',
                                        self.mComposition)
        checker.setControlPathPrefix("composer_mapgrid")
        myTestResult, myMessage = checker.testComposition(0, 100)
        assert myTestResult, myMessage

        self.mComposerMap.grid().setFrameSideFlag(QgsComposerMapGrid.FrameTop,
                                                  True)
        self.mComposerMap.updateBoundingRect()
        checker = QgsCompositionChecker('composermap_zebrastyle_lefttop',
                                        self.mComposition)
        checker.setControlPathPrefix("composer_mapgrid")
        myTestResult, myMessage = checker.testComposition(0, 100)
        assert myTestResult, myMessage

        self.mComposerMap.grid().setFrameSideFlag(
            QgsComposerMapGrid.FrameRight, True)
        self.mComposerMap.updateBoundingRect()
        checker = QgsCompositionChecker('composermap_zebrastyle_lefttopright',
                                        self.mComposition)
        checker.setControlPathPrefix("composer_mapgrid")
        myTestResult, myMessage = checker.testComposition(0, 100)
        assert myTestResult, myMessage

        self.mComposerMap.grid().setFrameSideFlag(
            QgsComposerMapGrid.FrameBottom, True)
        self.mComposerMap.grid().setFrameStyle(QgsComposerMapGrid.NoFrame)
예제 #7
0
 def refreshSettingsOutput(self):
     # Set Python lexer
     self.setLexers()
     caretLineColor = self.settings.value("pythonConsole/caretLineColor",
                                          QColor("#fcf3ed"))
     cursorColor = self.settings.value("pythonConsole/cursorColor",
                                       QColor(Qt.black))
     self.setCaretLineBackgroundColor(caretLineColor)
     self.setCaretForegroundColor(cursorColor)
예제 #8
0
    def refreshSettingsShell(self):
        # Set Python lexer
        self.setLexers()
        threshold = self.settings.value("pythonConsole/autoCompThreshold",
                                        2,
                                        type=int)
        self.setAutoCompletionThreshold(threshold)
        radioButtonSource = self.settings.value(
            "pythonConsole/autoCompleteSource", 'fromAPI')
        autoCompEnabled = self.settings.value(
            "pythonConsole/autoCompleteEnabled", True, type=bool)
        if autoCompEnabled:
            if radioButtonSource == 'fromDoc':
                self.setAutoCompletionSource(self.AcsDocument)
            elif radioButtonSource == 'fromAPI':
                self.setAutoCompletionSource(self.AcsAPIs)
            elif radioButtonSource == 'fromDocAPI':
                self.setAutoCompletionSource(self.AcsAll)
        else:
            self.setAutoCompletionSource(self.AcsNone)

        cursorColor = self.settings.value("pythonConsole/cursorColor",
                                          QColor(Qt.black))
        self.setCaretForegroundColor(cursorColor)

        # Sets minimum height for input area based of font metric
        self._setMinimumHeight()
예제 #9
0
    def testCrossGrid(self):
        myRectangle = QgsRectangle(781662.375, 3339523.125, 793062.375,
                                   3345223.125)
        self.mComposerMap.setNewExtent(myRectangle)
        self.mComposerMap.grid().setEnabled(True)
        self.mComposerMap.grid().setStyle(QgsComposerMapGrid.Cross)
        self.mComposerMap.grid().setCrossLength(2.0)
        self.mComposerMap.grid().setIntervalX(2000)
        self.mComposerMap.grid().setIntervalY(2000)
        self.mComposerMap.grid().setAnnotationEnabled(False)
        self.mComposerMap.grid().setGridLineColor(QColor(0, 255, 0))
        self.mComposerMap.grid().setGridLineWidth(0.5)
        self.mComposerMap.grid().setBlendMode(
            QPainter.CompositionMode_SourceOver)
        self.mComposerMap.updateBoundingRect()

        checker = QgsCompositionChecker('composermap_crossgrid',
                                        self.mComposition)
        checker.setControlPathPrefix("composer_mapgrid")
        myTestResult, myMessage = checker.testComposition()

        self.mComposerMap.grid().setStyle(QgsComposerMapGrid.Solid)
        self.mComposerMap.grid().setEnabled(False)
        self.mComposerMap.grid().setAnnotationEnabled(False)

        assert myTestResult, myMessage
예제 #10
0
def updateMask(control_image_path, rendered_image_path, mask_image_path):
    control_image = imageFromPath(control_image_path)
    if not control_image:
        error('Could not read control image {}'.format(control_image_path))

    rendered_image = imageFromPath(rendered_image_path)
    if not rendered_image:
        error('Could not read rendered image {}'.format(rendered_image_path))
    if not rendered_image.width() == control_image.width(
    ) or not rendered_image.height() == control_image.height():
        print(
            'Size mismatch - control image is {}x{}, rendered image is {}x{}'.
            format(control_image.width(), control_image.height(),
                   rendered_image.width(), rendered_image.height()))

    max_width = min(rendered_image.width(), control_image.width())
    max_height = min(rendered_image.height(), control_image.height())

    #read current mask, if it exist
    mask_image = imageFromPath(mask_image_path)
    if mask_image.isNull():
        print 'Mask image does not exist, creating {}'.format(mask_image_path)
        mask_image = QImage(control_image.width(), control_image.height(),
                            QImage.Format_ARGB32)
        mask_image.fill(QColor(0, 0, 0))

    #loop through pixels in rendered image and compare
    mismatch_count = 0
    linebytes = max_width * 4
    for y in xrange(max_height):
        control_scanline = control_image.constScanLine(y).asstring(linebytes)
        rendered_scanline = rendered_image.constScanLine(y).asstring(linebytes)
        mask_scanline = mask_image.scanLine(y).asstring(linebytes)

        for x in xrange(max_width):
            currentTolerance = qRed(
                struct.unpack('I', mask_scanline[x * 4:x * 4 + 4])[0])

            if currentTolerance == 255:
                #ignore pixel
                continue

            expected_rgb = struct.unpack('I',
                                         control_scanline[x * 4:x * 4 + 4])[0]
            rendered_rgb = struct.unpack('I',
                                         rendered_scanline[x * 4:x * 4 + 4])[0]
            difference = colorDiff(expected_rgb, rendered_rgb)

            if difference > currentTolerance:
                #update mask image
                mask_image.setPixel(x, y,
                                    qRgb(difference, difference, difference))
                mismatch_count += 1

    if mismatch_count:
        #update mask
        mask_image.save(mask_image_path, "png")
        print 'Updated {} pixels in {}'.format(mismatch_count, mask_image_path)
    else:
        print 'No mismatches in {}'.format(mask_image_path)
    def _get_composer_image(self, width, height, dpi):
        image = QImage(QSize(width, height),
                       self._TestMapSettings.outputImageFormat())
        image.fill(QColor(152, 219, 249).rgb())
        image.setDotsPerMeterX(dpi / 25.4 * 1000)
        image.setDotsPerMeterY(dpi / 25.4 * 1000)

        p = QPainter(image)
        p.setRenderHint(
            QPainter.Antialiasing,
            self._TestMapSettings.testFlag(QgsMapSettings.Antialiasing))
        self._c.renderPage(p, 0)
        p.end()

        # image = self._c.printPageAsRaster(0)
        # """:type: QImage"""

        if image.isNull():
            return False, ''

        filepath = getTempfilePath('png')
        res = image.save(filepath, 'png')
        if not res:
            os.unlink(filepath)
            filepath = ''

        return res, filepath
예제 #12
0
 def testColorsWithScheme(self):
     """Test getting colors when specifying a scheme"""
     dummyScheme = DummyColorScheme()
     colors = dummyScheme.fetchColors('testscheme')
     self.assertEqual(len(colors), 1)
     self.assertEqual(colors[0][0], QColor(255, 255, 0))
     self.assertEqual(colors[0][1], 'schemetest')
예제 #13
0
 def testColorsWithBase(self):
     """Test getting colors with a base color"""
     dummyScheme = DummyColorScheme()
     testColor = QColor(0, 0, 255)
     colors = dummyScheme.fetchColors(None, testColor)
     self.assertEqual(len(colors), 1)
     self.assertEqual(colors[0][0], testColor)
     self.assertEqual(colors[0][1], 'base')
예제 #14
0
    def initLexer(self):
        self.mylexer = QsciLexerSQL()

        colorDefault = QColor('#2e3436')
        colorComment = QColor('#c00')
        colorCommentBlock = QColor('#3465a4')
        colorNumber = QColor('#4e9a06')
        colorType = QColor('#4e9a06')
        colorKeyword = QColor('#204a87')
        colorString = QColor('#ce5c00')

        self.mylexer.setDefaultFont(self.defaultFont)
        self.mylexer.setDefaultColor(colorDefault)

        self.mylexer.setColor(colorComment, 1)
        self.mylexer.setColor(colorNumber, 2)
        self.mylexer.setColor(colorString, 3)
        self.mylexer.setColor(colorString, 4)
        self.mylexer.setColor(colorKeyword, 5)
        self.mylexer.setColor(colorString, 6)
        self.mylexer.setColor(colorString, 7)
        self.mylexer.setColor(colorType, 8)
        self.mylexer.setColor(colorCommentBlock, 12)
        self.mylexer.setColor(colorString, 15)

        self.mylexer.setFont(self.italicFont, 1)
        self.mylexer.setFont(self.boldFont, 5)
        self.mylexer.setFont(self.boldFont, 8)
        self.mylexer.setFont(self.italicFont, 12)

        self.setLexer(self.mylexer)
예제 #15
0
    def setCommonOptions(self):
        # Enable non-ASCII characters
        self.setUtf8(True)

        # Default font
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(20)
        self.setFont(font)
        self.setMarginsFont(font)

        self.initLexer()

        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        self.setWrapMode(QsciScintilla.WrapWord)
        self.setWrapVisualFlags(QsciScintilla.WrapFlagByText,
                                QsciScintilla.WrapFlagNone, 4)

        self.setSelectionForegroundColor(QColor('#2e3436'))
        self.setSelectionBackgroundColor(QColor('#babdb6'))

        # Show line numbers
        self.setMarginWidth(1, '000')
        self.setMarginLineNumbers(1, True)
        self.setMarginsForegroundColor(QColor('#2e3436'))
        self.setMarginsBackgroundColor(QColor('#babdb6'))

        # Highlight current line
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QColor('#d3d7cf'))

        # Folding
        self.setFolding(QsciScintilla.BoxedTreeFoldStyle)
        self.setFoldMarginColors(QColor('#d3d7cf'), QColor('#d3d7cf'))

        # Mark column 80 with vertical line
        self.setEdgeMode(QsciScintilla.EdgeLine)
        self.setEdgeColumn(80)
        self.setEdgeColor(QColor('#eeeeec'))

        # Indentation
        self.setAutoIndent(True)
        self.setIndentationsUseTabs(False)
        self.setIndentationWidth(4)
        self.setTabIndents(True)
        self.setBackspaceUnindents(True)
        self.setTabWidth(4)

        # Autocomletion
        self.setAutoCompletionThreshold(2)
        self.setAutoCompletionSource(QsciScintilla.AcsAPIs)

        self.setFonts(10)
예제 #16
0
    def __init__(self, canvas):
        self.canvas = canvas
        QgsMapToolEmitPoint.__init__(self, self.canvas)

        self.rubberBand = QgsRubberBand(self.canvas, QGis.Polygon)
        self.rubberBand.setColor(QColor(255, 0, 0, 100))
        self.rubberBand.setWidth(2)

        self.reset()
예제 #17
0
    def __init__(self, methodName):
        """Run once on class initialization."""
        unittest.TestCase.__init__(self, methodName)

        self.iface = get_iface()

        # initialize class MapRegistry, Canvas, MapRenderer, Map and PAL
        self.mMapRegistry = QgsMapLayerRegistry.instance()

        # create point layer
        myShpFile = os.path.join(TEST_DATA_DIR, 'points.shp')
        self.mPointLayer = QgsVectorLayer(myShpFile, 'Points', 'ogr')
        self.mMapRegistry.addMapLayer(self.mPointLayer)

        self.mSimplifyMethod = QgsVectorSimplifyMethod()
        self.mSimplifyMethod.setSimplifyHints(
            QgsVectorSimplifyMethod.NoSimplification)

        # create polygon layer
        myShpFile = os.path.join(TEST_DATA_DIR, 'polys.shp')
        self.mPolygonLayer = QgsVectorLayer(myShpFile, 'Polygons', 'ogr')
        self.mPolygonLayer.setSimplifyMethod(self.mSimplifyMethod)
        self.mMapRegistry.addMapLayer(self.mPolygonLayer)

        # create line layer
        myShpFile = os.path.join(TEST_DATA_DIR, 'lines.shp')
        self.mLineLayer = QgsVectorLayer(myShpFile, 'Lines', 'ogr')
        self.mLineLayer.setSimplifyMethod(self.mSimplifyMethod)
        self.mMapRegistry.addMapLayer(self.mLineLayer)

        # create two raster layers
        myRasterFile = os.path.join(TEST_DATA_DIR, 'rgb256x256.png')
        self.mRasterLayer1 = QgsRasterLayer(myRasterFile, "raster1")
        self.mRasterLayer2 = QgsRasterLayer(myRasterFile, "raster2")
        myMultiBandRenderer1 = QgsMultiBandColorRenderer(
            self.mRasterLayer1.dataProvider(), 1, 2, 3)
        self.mRasterLayer1.setRenderer(myMultiBandRenderer1)
        self.mMapRegistry.addMapLayer(self.mRasterLayer1)
        myMultiBandRenderer2 = QgsMultiBandColorRenderer(
            self.mRasterLayer2.dataProvider(), 1, 2, 3)
        self.mRasterLayer2.setRenderer(myMultiBandRenderer2)
        self.mMapRegistry.addMapLayer(self.mRasterLayer2)

        # to match blend modes test comparisons background
        self.mCanvas = self.iface.mapCanvas()
        self.mCanvas.setCanvasColor(QColor(152, 219, 249))
        self.mMap = self.mCanvas.map()
        self.mMap.resize(QSize(400, 400))
        self.mapSettings = self.mCanvas.mapSettings()
        self.mapSettings.setOutputSize(QSize(400, 400))
        self.mapSettings.setOutputDpi(96)

        self.extent = QgsRectangle(-118.8888888888887720, 22.8002070393376783,
                                   -83.3333333333331581, 46.8719806763287536)
예제 #18
0
    def testSizeUnit(self):
        # test sizeUnit and setSizeUnit

        # create a marker symbol with a single layer
        markerSymbol = QgsMarkerSymbolV2()
        markerSymbol.deleteSymbolLayer(0)
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayerV2('star', QColor(255, 0, 0),
                                         QColor(0, 255, 0), 10))
        self.assertEqual(markerSymbol.sizeUnit(), QgsSymbolV2.MM)
        markerSymbol.setSizeUnit(QgsSymbolV2.MapUnit)
        self.assertEqual(markerSymbol.sizeUnit(), QgsSymbolV2.MapUnit)
        self.assertEqual(
            markerSymbol.symbolLayer(0).sizeUnit(), QgsSymbolV2.MapUnit)

        # add additional layers
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayerV2('star', QColor(255, 0, 0),
                                         QColor(0, 255, 0), 10))
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayerV2('star', QColor(255, 0, 0),
                                         QColor(0, 255, 0), 30))
        # should now be mixed size units
        self.assertEqual(markerSymbol.sizeUnit(), QgsSymbolV2.Mixed)
        markerSymbol.setSizeUnit(QgsSymbolV2.Pixel)
        self.assertEqual(markerSymbol.sizeUnit(), QgsSymbolV2.Pixel)
        # all layers should have size unit set
        self.assertEqual(
            markerSymbol.symbolLayer(0).sizeUnit(), QgsSymbolV2.Pixel)
        self.assertEqual(
            markerSymbol.symbolLayer(1).sizeUnit(), QgsSymbolV2.Pixel)
        self.assertEqual(
            markerSymbol.symbolLayer(2).sizeUnit(), QgsSymbolV2.Pixel)
예제 #19
0
    def testSize(self):
        # test size and setSize

        # create a marker symbol with a single layer
        markerSymbol = QgsMarkerSymbolV2()
        markerSymbol.deleteSymbolLayer(0)
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayerV2('star', QColor(255, 0, 0),
                                         QColor(0, 255, 0), 10))
        self.assertEqual(markerSymbol.size(), 10)
        markerSymbol.setSize(20)
        self.assertEqual(markerSymbol.size(), 20)
        self.assertEqual(markerSymbol.symbolLayer(0).size(), 20)

        # add additional layers
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayerV2('star', QColor(255, 0, 0),
                                         QColor(0, 255, 0), 10))
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayerV2('star', QColor(255, 0, 0),
                                         QColor(0, 255, 0), 30))
        self.assertEqual(markerSymbol.size(), 30)
        markerSymbol.setSize(3)
        self.assertEqual(markerSymbol.size(), 3)
        # layer sizes should maintain relative size
        self.assertEqual(markerSymbol.symbolLayer(0).size(), 2)
        self.assertEqual(markerSymbol.symbolLayer(1).size(), 1)
        self.assertEqual(markerSymbol.symbolLayer(2).size(), 3)
예제 #20
0
    def testAngle(self):
        # test angle and setAngle

        # create a marker symbol with a single layer
        markerSymbol = QgsMarkerSymbolV2()
        markerSymbol.deleteSymbolLayer(0)
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayerV2('star', QColor(255, 0, 0),
                                         QColor(0, 255, 0), 10, 90))
        self.assertEqual(markerSymbol.angle(), 90)
        markerSymbol.setAngle(100)
        self.assertEqual(markerSymbol.angle(), 100)
        self.assertEqual(markerSymbol.symbolLayer(0).angle(), 100)

        # add additional layers
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayerV2('star', QColor(255, 0, 0),
                                         QColor(0, 255, 0), 10, 130))
        markerSymbol.appendSymbolLayer(
            QgsSimpleMarkerSymbolLayerV2('star', QColor(255, 0, 0),
                                         QColor(0, 255, 0), 10, 150))
        # should take first layer's angle
        self.assertEqual(markerSymbol.angle(), 100)
        markerSymbol.setAngle(10)
        self.assertEqual(markerSymbol.angle(), 10)
        # layer angles should maintain relative angle
        self.assertEqual(markerSymbol.symbolLayer(0).angle(), 10)
        self.assertEqual(markerSymbol.symbolLayer(1).angle(), 40)
        self.assertEqual(markerSymbol.symbolLayer(2).angle(), 60)
예제 #21
0
    def initLexer(self):
        if self.lexerType == self.LEXER_PYTHON:
            self.lexer = QsciLexerPython()

            colorDefault = QColor('#2e3436')
            colorComment = QColor('#c00')
            colorCommentBlock = QColor('#3465a4')
            colorNumber = QColor('#4e9a06')
            colorType = QColor('#4e9a06')
            colorKeyword = QColor('#204a87')
            colorString = QColor('#ce5c00')

            self.lexer.setDefaultFont(self.defaultFont)
            self.lexer.setDefaultColor(colorDefault)

            self.lexer.setColor(colorComment, 1)
            self.lexer.setColor(colorNumber, 2)
            self.lexer.setColor(colorString, 3)
            self.lexer.setColor(colorString, 4)
            self.lexer.setColor(colorKeyword, 5)
            self.lexer.setColor(colorString, 6)
            self.lexer.setColor(colorString, 7)
            self.lexer.setColor(colorType, 8)
            self.lexer.setColor(colorCommentBlock, 12)
            self.lexer.setColor(colorString, 15)

            self.lexer.setFont(self.italicFont, 1)
            self.lexer.setFont(self.boldFont, 5)
            self.lexer.setFont(self.boldFont, 8)
            self.lexer.setFont(self.italicFont, 12)

            self.api = QsciAPIs(self.lexer)

            settings = QSettings()
            useDefaultAPI = bool(
                settings.value('pythonConsole/preloadAPI', True))
            if useDefaultAPI:
                # Load QGIS API shipped with Python console
                self.api.loadPrepared(
                    os.path.join(QgsApplication.pkgDataPath(), 'python',
                                 'qsci_apis', 'pyqgis.pap'))
            else:
                # Load user-defined API files
                apiPaths = settings.value('pythonConsole/userAPI', [])
                for path in apiPaths:
                    self.api.load(path)
                self.api.prepare()
                self.lexer.setAPIs(self.api)
        elif self.lexerType == self.LEXER_R:
            # R lexer
            self.lexer = LexerR()

        self.setLexer(self.lexer)
예제 #22
0
    def testGrid(self):
        """Test that we can create a grid for a map."""
        myRectangle = QgsRectangle(781662.375, 3339523.125, 793062.375,
                                   3345223.125)
        self.mComposerMap.setNewExtent(myRectangle)
        self.mComposerMap.grid().setEnabled(True)
        self.mComposerMap.grid().setIntervalX(2000)
        self.mComposerMap.grid().setIntervalY(2000)
        self.mComposerMap.grid().setAnnotationEnabled(True)
        self.mComposerMap.grid().setGridLineColor(QColor(0, 255, 0))
        self.mComposerMap.grid().setGridLineWidth(0.5)
        self.mComposerMap.grid().setAnnotationFont(
            QgsFontUtils.getStandardTestFont())
        self.mComposerMap.grid().setAnnotationPrecision(0)
        self.mComposerMap.grid().setAnnotationPosition(
            QgsComposerMapGrid.Disabled, QgsComposerMapGrid.Left)
        self.mComposerMap.grid().setAnnotationPosition(
            QgsComposerMapGrid.OutsideMapFrame, QgsComposerMapGrid.Right)
        self.mComposerMap.grid().setAnnotationPosition(
            QgsComposerMapGrid.Disabled, QgsComposerMapGrid.Top)
        self.mComposerMap.grid().setAnnotationPosition(
            QgsComposerMapGrid.OutsideMapFrame, QgsComposerMapGrid.Bottom)
        self.mComposerMap.grid().setAnnotationDirection(
            QgsComposerMapGrid.Horizontal, QgsComposerMapGrid.Right)
        self.mComposerMap.grid().setAnnotationDirection(
            QgsComposerMapGrid.Horizontal, QgsComposerMapGrid.Bottom)
        self.mComposerMap.grid().setAnnotationFontColor(QColor(255, 0, 0, 150))
        self.mComposerMap.grid().setBlendMode(QPainter.CompositionMode_Overlay)
        self.mComposerMap.updateBoundingRect()

        checker = QgsCompositionChecker('composermap_grid', self.mComposition)
        checker.setControlPathPrefix("composer_mapgrid")
        myTestResult, myMessage = checker.testComposition()
        self.mComposerMap.setGridEnabled(False)
        self.mComposerMap.setShowGridAnnotation(False)

        assert myTestResult, myMessage
예제 #23
0
    def write(self, m):
        if self.style == "_traceback":
            # Show errors in red
            stderrColor = QColor(
                self.sO.settings.value("pythonConsole/stderrFontColor",
                                       QColor(Qt.red)))
            self.sO.SendScintilla(QsciScintilla.SCI_STYLESETFORE, 0o01,
                                  stderrColor)
            self.sO.SendScintilla(QsciScintilla.SCI_STYLESETITALIC, 0o01, True)
            self.sO.SendScintilla(QsciScintilla.SCI_STYLESETBOLD, 0o01, True)
            pos = self.sO.SendScintilla(QsciScintilla.SCI_GETCURRENTPOS)
            self.sO.SendScintilla(QsciScintilla.SCI_STARTSTYLING, pos, 31)
            self.sO.append(m)
            self.sO.SendScintilla(QsciScintilla.SCI_SETSTYLING, len(m), 0o01)
        else:
            self.sO.append(m)

        if self.out:
            self.out.write(m)

        self.move_cursor_to_end()

        if self.style != "_traceback":
            QCoreApplication.processEvents()
예제 #24
0
    def __init__(self, methodName):
        """Run once on class initialization."""
        unittest.TestCase.__init__(self, methodName)

        # create composition with composer map
        self.mMapSettings = QgsMapSettings()
        crs = QgsCoordinateReferenceSystem(32633)
        self.mMapSettings.setDestinationCrs(crs)
        self.mMapSettings.setCrsTransformEnabled(False)
        self.mComposition = QgsComposition(self.mMapSettings)
        self.mComposition.setPaperSize(297, 210)
        self.mComposerMap = QgsComposerMap(self.mComposition, 20, 20, 200, 100)
        self.mComposerMap.setFrameEnabled(True)
        self.mComposerMap.setBackgroundColor(QColor(150, 100, 100))
        self.mComposition.addComposerMap(self.mComposerMap)
예제 #25
0
    def setUp(self):
        self.iface = get_iface()

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

        # Create style
        sym2 = QgsLineSymbolV2.createSimple({'color': '#fdbf6f'})
        self.lines_layer.setRendererV2(QgsSingleSymbolRendererV2(sym2))

        self.mapsettings = self.iface.mapCanvas().mapSettings()
        self.mapsettings.setOutputSize(QSize(400, 400))
        self.mapsettings.setOutputDpi(96)
        self.mapsettings.setExtent(QgsRectangle(-113, 28, -91, 40))
        self.mapsettings.setBackgroundColor(QColor("white"))
예제 #26
0
    def __init__(self, parent=None):
        QgsMapCanvas.__init__(self, parent)
        self.parent = parent
        self.setCanvasColor(QColor(255, 255, 255))

        self.item = None
        self.dirty = False
        self.currentLayer = None

        # reuse settings from QGIS
        settings = QSettings()
        self.enableAntiAliasing(
            settings.value("/qgis/enable_anti_aliasing", False, type=bool))
        action = settings.value("/qgis/wheel_action", 0, type=float)
        zoomFactor = settings.value("/qgis/zoom_factor", 2, type=float)
        self.setWheelAction(QgsMapCanvas.WheelAction(action), zoomFactor)
    def _get_composer_svg_image(self, width, height, dpi):
        # from qgscomposer.cpp, QgsComposer::on_mActionExportAsSVG_triggered,
        # near end of function
        svgpath = getTempfilePath('svg')
        temp_size = os.path.getsize(svgpath)

        svg_g = QSvgGenerator()
        # noinspection PyArgumentList
        svg_g.setTitle(QgsProject.instance().title())
        svg_g.setFileName(svgpath)
        svg_g.setSize(QSize(width, height))
        svg_g.setViewBox(QRect(0, 0, width, height))
        svg_g.setResolution(dpi)

        sp = QPainter(svg_g)
        self._c.renderPage(sp, 0)
        sp.end()

        if temp_size == os.path.getsize(svgpath):
            return False, ''

        image = QImage(width, height,
                       self._TestMapSettings.outputImageFormat())
        image.fill(QColor(152, 219, 249).rgb())
        image.setDotsPerMeterX(dpi / 25.4 * 1000)
        image.setDotsPerMeterY(dpi / 25.4 * 1000)

        svgr = QSvgRenderer(svgpath)
        p = QPainter(image)
        p.setRenderHint(
            QPainter.Antialiasing,
            self._TestMapSettings.testFlag(QgsMapSettings.Antialiasing))
        p.setRenderHint(QPainter.TextAntialiasing)
        svgr.render(p)
        p.end()

        filepath = getTempfilePath('png')
        res = image.save(filepath, 'png')
        if not res:
            os.unlink(filepath)
            filepath = ''
        # TODO: remove .svg file as well?

        return res, filepath
예제 #28
0
 def getBaseMapSettings(cls):
     """
     :rtype: QgsMapSettings
     """
     ms = QgsMapSettings()
     crs = QgsCoordinateReferenceSystem()
     """:type: QgsCoordinateReferenceSystem"""
     # default for labeling test data: WGS 84 / UTM zone 13N
     crs.createFromSrid(32613)
     ms.setBackgroundColor(QColor(152, 219, 249))
     ms.setOutputSize(QSize(420, 280))
     ms.setOutputDpi(72)
     ms.setFlag(QgsMapSettings.Antialiasing, True)
     ms.setFlag(QgsMapSettings.UseAdvancedEffects, False)
     ms.setFlag(QgsMapSettings.ForceVectorOutput, False)  # no caching?
     ms.setDestinationCrs(crs)
     ms.setCrsTransformEnabled(False)
     ms.setMapUnits(crs.mapUnits())  # meters
     ms.setExtent(cls.aoiExtent())
     return ms
예제 #29
0
    def testShaderCrash(self):
        """Check if we assign a shader and then reassign it no crash occurs."""
        myPath = os.path.join(unitTestDataPath('raster'),
                              'band1_float32_noct_epsg4326.tif')
        myFileInfo = QFileInfo(myPath)
        myBaseName = myFileInfo.baseName()
        myRasterLayer = QgsRasterLayer(myPath, myBaseName)
        myMessage = 'Raster not loaded: %s' % myPath
        assert myRasterLayer.isValid(), myMessage

        myRasterShader = QgsRasterShader()
        myColorRampShader = QgsColorRampShader()
        myColorRampShader.setColorRampType(QgsColorRampShader.INTERPOLATED)
        myItems = []
        myItem = QgsColorRampShader.ColorRampItem(10, QColor('#ffff00'), 'foo')
        myItems.append(myItem)
        myItem = QgsColorRampShader.ColorRampItem(100, QColor('#ff00ff'),
                                                  'bar')
        myItems.append(myItem)
        myItem = QgsColorRampShader.ColorRampItem(1000, QColor('#00ff00'),
                                                  'kazam')
        myItems.append(myItem)
        myColorRampShader.setColorRampItemList(myItems)
        myRasterShader.setRasterShaderFunction(myColorRampShader)
        myPseudoRenderer = QgsSingleBandPseudoColorRenderer(
            myRasterLayer.dataProvider(), 1, myRasterShader)
        myRasterLayer.setRenderer(myPseudoRenderer)

        return
        ######## works first time #############

        myRasterShader = QgsRasterShader()
        myColorRampShader = QgsColorRampShader()
        myColorRampShader.setColorRampType(QgsColorRampShader.INTERPOLATED)
        myItems = []
        myItem = QgsColorRampShader.ColorRampItem(10, QColor('#ffff00'), 'foo')
        myItems.append(myItem)
        myItem = QgsColorRampShader.ColorRampItem(100, QColor('#ff00ff'),
                                                  'bar')
        myItems.append(myItem)
        myItem = QgsColorRampShader.ColorRampItem(1000, QColor('#00ff00'),
                                                  'kazam')
        myItems.append(myItem)
        myColorRampShader.setColorRampItemList(myItems)
        myRasterShader.setRasterShaderFunction(myColorRampShader)
        ######## crash on next line (fixed now)##################
        myPseudoRenderer = QgsSingleBandPseudoColorRenderer(
            myRasterLayer.dataProvider(), 1, myRasterShader)
        myRasterLayer.setRenderer(myPseudoRenderer)
예제 #30
0
    def renderGeometry(self, geom):
        f = QgsFeature()
        f.setGeometry(geom)

        image = QImage(200, 200, QImage.Format_RGB32)

        painter = QPainter()
        ms = QgsMapSettings()
        extent = geom.geometry().boundingBox()
        # buffer extent by 10%
        if extent.width() > 0:
            extent = extent.buffer((extent.height() + extent.width()) / 20.0)
        else:
            extent = extent.buffer(10)

        ms.setExtent(extent)
        ms.setOutputSize(image.size())
        context = QgsRenderContext.fromMapSettings(ms)
        context.setPainter(painter)
        context.setScaleFactor(96 / 25.4)  # 96 DPI

        painter.begin(image)
        image.fill(QColor(0, 0, 0))

        if geom.type() == QGis.Polygon:
            self.fill_symbol.startRender(context)
            self.fill_symbol.renderFeature(f, context)
            self.fill_symbol.stopRender(context)

        elif geom.type() == QGis.Line:
            self.line_symbol.startRender(context)
            self.line_symbol.renderFeature(f, context)
            self.line_symbol.stopRender(context)

        elif geom.type() == QGis.Point:
            self.marker_symbol.startRender(context)
            self.marker_symbol.renderFeature(f, context)
            self.marker_symbol.stopRender(context)

        painter.end()
        return image