def _change_data_source(self, layer, datasource, provider_key): """Due to the fact that a project r/w context is not available inside the map layers classes, the original style and subset string restore happens in app, this function replicates app behavior""" options = QgsDataProvider.ProviderOptions() subset_string = '' if not layer.isValid(): try: subset_string = layer.dataProvider().subsetString() except: pass layer.setDataSource(datasource, layer.name(), provider_key, options) if subset_string: layer.setSubsetString(subset_string) self.assertTrue(layer.originalXmlProperties(), layer.name()) context = QgsReadWriteContext() context.setPathResolver(QgsProject.instance().pathResolver()) errorMsg = '' doc = QDomDocument() self.assertTrue(doc.setContent(layer.originalXmlProperties())) layer_node = QDomNode(doc.firstChild()) self.assertTrue(layer.readSymbology(layer_node, errorMsg, context))
def create_qgis_template_output(output_path, layout): """Produce QGIS Template output. :param output_path: The output path. :type output_path: str :param composition: QGIS Composition object to get template. values :type composition: qgis.core.QgsLayout :return: Generated output path. :rtype: str """ # make sure directory is created dirname = os.path.dirname(output_path) if not os.path.exists(dirname): os.makedirs(dirname) context = QgsReadWriteContext() context.setPathResolver(QgsProject.instance().pathResolver()) layout.saveAsTemplate(output_path, context) return output_path
def testReadWriteXml(self): p = QgsProject() l = QgsPrintLayout(p) l.setName('my layout') l.setUnits(QgsUnitTypes.LayoutInches) collection = l.pageCollection() # add a page page = QgsLayoutItemPage(l) page.setPageSize('A6') collection.addPage(page) grid = l.gridSettings() grid.setResolution(QgsLayoutMeasurement(5, QgsUnitTypes.LayoutPoints)) g1 = QgsLayoutGuide( Qt.Horizontal, QgsLayoutMeasurement(5, QgsUnitTypes.LayoutCentimeters), l.pageCollection().page(0)) l.guides().addGuide(g1) snapper = l.snapper() snapper.setSnapTolerance(7) # add some items item1 = QgsLayoutItemMap(l) item1.setId('xxyyxx') l.addItem(item1) item2 = QgsLayoutItemMap(l) item2.setId('zzyyzz') l.addItem(item2) l.setReferenceMap(item2) doc = QDomDocument("testdoc") elem = l.writeXml(doc, QgsReadWriteContext()) l2 = QgsPrintLayout(p) self.assertTrue(l2.readXml(elem, doc, QgsReadWriteContext())) self.assertEqual(l2.name(), 'my layout') self.assertEqual(l2.units(), QgsUnitTypes.LayoutInches) collection2 = l2.pageCollection() self.assertEqual(collection2.pageCount(), 1) self.assertAlmostEqual(collection2.page(0).pageSize().width(), 105, 4) self.assertEqual(collection2.page(0).pageSize().height(), 148) self.assertEqual(l2.gridSettings().resolution().length(), 5.0) self.assertEqual(l2.gridSettings().resolution().units(), QgsUnitTypes.LayoutPoints) self.assertEqual(l2.guides().guidesOnPage(0)[0].orientation(), Qt.Horizontal) self.assertEqual(l2.guides().guidesOnPage(0)[0].position().length(), 5.0) self.assertEqual(l2.guides().guidesOnPage(0)[0].position().units(), QgsUnitTypes.LayoutCentimeters) self.assertEqual(l2.snapper().snapTolerance(), 7) # check restored items new_item1 = l2.itemByUuid(item1.uuid()) self.assertTrue(new_item1) self.assertEqual(new_item1.id(), 'xxyyxx') new_item2 = l2.itemByUuid(item2.uuid()) self.assertTrue(new_item2) self.assertEqual(new_item2.id(), 'zzyyzz') self.assertEqual(l2.referenceMap().id(), 'zzyyzz')
def testQgsGraduatedSymbolRenderer_2(self): """Test QgsGraduatedSymbolRenderer: Adding /removing/editing classes """ # Create a renderer renderer = QgsGraduatedSymbolRenderer() symbol = createMarkerSymbol() renderer.setSourceSymbol(symbol.clone()) symbol.setColor(QColor(255, 0, 0)) # Add class without start and end ranges renderer.addClass(symbol.clone()) renderer.addClass(symbol.clone()) renderer.updateRangeLabel(1, 'Second range') renderer.updateRangeLowerValue(1, 10.0) renderer.updateRangeUpperValue(1, 25.0) renderer.updateRangeRenderState(1, False) symbol.setColor(QColor(0, 0, 255)) renderer.updateRangeSymbol(1, symbol.clone()) # Add as a rangeobject symbol.setColor(QColor(0, 255, 0)) range = QgsRendererRange(20.0, 25.5, symbol.clone(), 'Third range', False) renderer.addClassRange(range) # Add class by lower and upper renderer.addClassLowerUpper(25.5, 30.5) # (Update label for sorting tests) renderer.updateRangeLabel(3, 'Another range') self.assertEqual( dumpRangeLabels(renderer.ranges()), '(0.0 - 0.0,Second range,Third range,Another range,)', 'Added ranges labels not correct') self.assertEqual( dumpRangeBreaks(renderer.ranges()), '(0.0000-0.0000,10.0000-25.0000,20.0000-25.5000,25.5000-30.5000,)', 'Added ranges lower/upper values not correct') # Check that clone function works renderer2 = renderer.clone() self.assertEqual( dumpGraduatedRenderer(renderer), dumpGraduatedRenderer(renderer2), "clone function doesn't replicate renderer properly" ) # Check save and reload from Dom works doc = QDomDocument() element = renderer.save(doc, QgsReadWriteContext()) renderer2 = QgsGraduatedSymbolRenderer.create(element, QgsReadWriteContext()) self.assertEqual( dumpGraduatedRenderer(renderer), dumpGraduatedRenderer(renderer2), "Save/create from DOM doesn't replicate renderer properly" ) # Check sorting renderer.sortByLabel() self.assertEqual( dumpRangeList(renderer.ranges(), labelsOnly=True), '(0.0 - 0.0,Another range,Second range,Third range,)', 'sortByLabel not correct') renderer.sortByValue() self.assertEqual( dumpRangeBreaks(renderer.ranges()), '(0.0000-0.0000,10.0000-25.0000,20.0000-25.5000,25.5000-30.5000,)', 'sortByValue not correct') renderer.sortByValue(Qt.DescendingOrder) self.assertEqual( dumpRangeBreaks(renderer.ranges()), '(25.5000-30.5000,20.0000-25.5000,10.0000-25.0000,0.0000-0.0000,)', 'sortByValue descending not correct') # Check deleting renderer.deleteClass(2) self.assertEqual( dumpRangeBreaks(renderer.ranges()), '(25.5000-30.5000,20.0000-25.5000,0.0000-0.0000,)', 'deleteClass not correct') renderer.deleteAllClasses() self.assertEqual(len(renderer.ranges()), 0, "deleteAllClasses didn't delete all")
def copyLayerViaXmlReadWrite(self, source, dest): # write to xml doc = QDomDocument("testdoc") elem = doc.createElement("maplayer") self.assertTrue(source.writeLayerXml(elem, doc, QgsReadWriteContext())) self.assertTrue(dest.readLayerXml(elem, QgsReadWriteContext()), QgsProject.instance())
def testWriteReadXmlSingleVariant(self): # setup a context context = QgsCoordinateTransformContext() self.assertTrue( context.addSourceDatumTransform( QgsCoordinateReferenceSystem('EPSG:3111'), 1)) self.assertTrue( context.addSourceDatumTransform( QgsCoordinateReferenceSystem('EPSG:28356'), 2)) self.assertTrue( context.addDestinationDatumTransform( QgsCoordinateReferenceSystem('EPSG:3113'), 11)) self.assertTrue( context.addDestinationDatumTransform( QgsCoordinateReferenceSystem('EPSG:28355'), 12)) self.assertTrue( context.addSourceDestinationDatumTransform( QgsCoordinateReferenceSystem('EPSG:3111'), QgsCoordinateReferenceSystem('EPSG:4283'), 1, 2)) self.assertTrue( context.addSourceDestinationDatumTransform( QgsCoordinateReferenceSystem('EPSG:28356'), QgsCoordinateReferenceSystem(4283), 3, 4)) self.assertEqual(context.sourceDatumTransforms(), { 'EPSG:3111': 1, 'EPSG:28356': 2 }) self.assertEqual(context.destinationDatumTransforms(), { 'EPSG:3113': 11, 'EPSG:28355': 12 }) self.assertEqual( context.sourceDestinationDatumTransforms(), { ('EPSG:3111', 'EPSG:4283'): (1, 2), ('EPSG:28356', 'EPSG:4283'): (3, 4) }) # save to xml doc = QDomDocument("testdoc") elem = doc.createElement("test") context.writeXml(elem, QgsReadWriteContext()) # restore from xml context2 = QgsCoordinateTransformContext() context2.readXml(elem, QgsReadWriteContext()) # check result self.assertEqual(context2.sourceDatumTransforms(), { 'EPSG:3111': 1, 'EPSG:28356': 2 }) self.assertEqual(context2.destinationDatumTransforms(), { 'EPSG:3113': 11, 'EPSG:28355': 12 }) self.assertEqual( context2.sourceDestinationDatumTransforms(), { ('EPSG:3111', 'EPSG:4283'): (1, 2), ('EPSG:28356', 'EPSG:4283'): (3, 4) })
def testBasicFormat(self): """ test basic formatter """ f = QgsBasicNumericFormat() context = QgsNumericFormatContext() self.assertEqual(f.formatDouble(0, context), '0') self.assertEqual(f.formatDouble(5, context), '5') self.assertEqual(f.formatDouble(5.5, context), '5.5') self.assertEqual(f.formatDouble(-5, context), '-5') self.assertEqual(f.formatDouble(-5.5, context), '-5.5') self.assertEqual(f.formatDouble(-55555555.5, context), '-55,555,555.5') context.setDecimalSeparator('☕') self.assertEqual(f.formatDouble(0, context), '0') self.assertEqual(f.formatDouble(-5.5, context), '-5☕5') self.assertEqual(f.formatDouble(-55555555.5, context), '-55,555,555☕5') context.setThousandsSeparator('⚡') self.assertEqual(f.formatDouble(-5.5, context), '-5☕5') self.assertEqual(f.formatDouble(-55555555.5, context), '-55⚡555⚡555☕5') f.setShowThousandsSeparator(False) self.assertEqual(f.formatDouble(-5.5, context), '-5☕5') self.assertEqual(f.formatDouble(-55555555.5, context), '-55555555☕5') context.setDecimalSeparator('.') f.setDecimalSeparator('⛹') self.assertEqual(f.formatDouble(-5.5, context), '-5⛹5') self.assertEqual(f.formatDouble(-55555555.5, context), '-55555555⛹5') f.setNumberDecimalPlaces(0) self.assertEqual(f.formatDouble(0, context), '0') self.assertEqual(f.formatDouble(5.5, context), '6') self.assertEqual(f.formatDouble(55555555.5, context), '55555556') self.assertEqual(f.formatDouble(55555555.123456, context), '55555555') self.assertEqual(f.formatDouble(-5.5, context), '-6') self.assertEqual(f.formatDouble(-55555555.5, context), '-55555556') f.setNumberDecimalPlaces(3) self.assertEqual(f.formatDouble(0, context), '0') self.assertEqual(f.formatDouble(5.5, context), '5⛹5') self.assertEqual(f.formatDouble(55555555.5, context), '55555555⛹5') self.assertEqual(f.formatDouble(55555555.123456, context), '55555555⛹123') self.assertEqual(f.formatDouble(-5.5, context), '-5⛹5') self.assertEqual(f.formatDouble(-55555555.5, context), '-55555555⛹5') f.setShowTrailingZeros(True) self.assertEqual(f.formatDouble(0, context), '0⛹000') self.assertEqual(f.formatDouble(5, context), '5⛹000') self.assertEqual(f.formatDouble(-5, context), '-5⛹000') self.assertEqual(f.formatDouble(5.5, context), '5⛹500') self.assertEqual(f.formatDouble(55555555.5, context), '55555555⛹500') self.assertEqual(f.formatDouble(55555555.123456, context), '55555555⛹123') self.assertEqual(f.formatDouble(-5.5, context), '-5⛹500') self.assertEqual(f.formatDouble(-55555555.5, context), '-55555555⛹500') f.setShowPlusSign(True) self.assertEqual(f.formatDouble(0, context), '0⛹000') self.assertEqual(f.formatDouble(5, context), '+5⛹000') self.assertEqual(f.formatDouble(-5, context), '-5⛹000') self.assertEqual(f.formatDouble(5.5, context), '+5⛹500') self.assertEqual(f.formatDouble(55555555.5, context), '+55555555⛹500') self.assertEqual(f.formatDouble(55555555.123456, context), '+55555555⛹123') self.assertEqual(f.formatDouble(-5.5, context), '-5⛹500') self.assertEqual(f.formatDouble(-55555555.5, context), '-55555555⛹500') context.setPositiveSign('w') self.assertEqual(f.formatDouble(5, context), 'w5⛹000') self.assertEqual(f.formatDouble(-5, context), '-5⛹000') self.assertEqual(f.formatDouble(5.5, context), 'w5⛹500') f.setShowPlusSign(False) f.setRoundingType(QgsBasicNumericFormat.SignificantFigures) self.assertEqual(f.formatDouble(0, context), '0⛹00') self.assertEqual(f.formatDouble(5, context), '5⛹00') self.assertEqual(f.formatDouble(-5, context), '-5⛹00') self.assertEqual(f.formatDouble(5.5, context), '5⛹50') self.assertEqual(f.formatDouble(1231.23123123123123, context), '1230') self.assertEqual(f.formatDouble(123.123123123123123, context), '123') self.assertEqual(f.formatDouble(12.3123123123123123, context), '12⛹3') self.assertEqual(f.formatDouble(1.23123123123123123, context), '1⛹23') self.assertEqual(f.formatDouble(-1231.23123123123123, context), '-1230') self.assertEqual(f.formatDouble(-123.123123123123123, context), '-123') self.assertEqual(f.formatDouble(-12.3123123123123123, context), '-12⛹3') self.assertEqual(f.formatDouble(-1.23123123123123123, context), '-1⛹23') self.assertEqual(f.formatDouble(100, context), '100') self.assertEqual(f.formatDouble(1000, context), '1000') self.assertEqual(f.formatDouble(1001, context), '1000') self.assertEqual(f.formatDouble(9999, context), '10000') self.assertEqual(f.formatDouble(10, context), '10⛹0') self.assertEqual(f.formatDouble(1, context), '1⛹00') self.assertEqual(f.formatDouble(0.00000123456, context), '0⛹00000123') self.assertEqual(f.formatDouble(55555555.5, context), '55600000') self.assertEqual(f.formatDouble(55555555.123456, context), '55600000') self.assertEqual(f.formatDouble(-5.5, context), '-5⛹50') self.assertEqual(f.formatDouble(-55555555.5, context), '-55600000') f.setThousandsSeparator('✅') f.setShowThousandsSeparator(True) self.assertEqual(f.formatDouble(-55555555.5, context), '-55✅600✅000') f.setShowThousandsSeparator(False) f.setShowPlusSign(True) f2 = f.clone() self.assertIsInstance(f2, QgsBasicNumericFormat) self.assertEqual(f2.showTrailingZeros(), f.showTrailingZeros()) self.assertEqual(f2.showPlusSign(), f.showPlusSign()) self.assertEqual(f2.numberDecimalPlaces(), f.numberDecimalPlaces()) self.assertEqual(f2.showThousandsSeparator(), f.showThousandsSeparator()) self.assertEqual(f2.roundingType(), f.roundingType()) self.assertEqual(f2.thousandsSeparator(), f.thousandsSeparator()) self.assertEqual(f2.decimalSeparator(), f.decimalSeparator()) doc = QDomDocument("testdoc") elem = doc.createElement("test") f2.writeXml(elem, doc, QgsReadWriteContext()) f3 = QgsNumericFormatRegistry().createFromXml(elem, QgsReadWriteContext()) self.assertIsInstance(f3, QgsBasicNumericFormat) self.assertEqual(f3.showTrailingZeros(), f.showTrailingZeros()) self.assertEqual(f3.showPlusSign(), f.showPlusSign()) self.assertEqual(f3.numberDecimalPlaces(), f.numberDecimalPlaces()) self.assertEqual(f3.showThousandsSeparator(), f.showThousandsSeparator()) self.assertEqual(f3.roundingType(), f.roundingType()) self.assertEqual(f3.thousandsSeparator(), f.thousandsSeparator()) self.assertEqual(f3.decimalSeparator(), f.decimalSeparator())
def testPercentageFormat(self): """ test percentage formatter """ f = QgsPercentageNumericFormat() f.setInputValues(QgsPercentageNumericFormat.ValuesArePercentage) context = QgsNumericFormatContext() self.assertEqual(f.formatDouble(0, context), '0%') self.assertEqual(f.formatDouble(5, context), '5%') self.assertEqual(f.formatDouble(5.5, context), '5.5%') self.assertEqual(f.formatDouble(-5, context), '-5%') self.assertEqual(f.formatDouble(-5.5, context), '-5.5%') self.assertEqual(f.formatDouble(-55555555.5, context), '-55,555,555.5%') context.setDecimalSeparator('x') self.assertEqual(f.formatDouble(0, context), '0%') self.assertEqual(f.formatDouble(-5.5, context), '-5x5%') self.assertEqual(f.formatDouble(-55555555.5, context), '-55,555,555x5%') context.setThousandsSeparator('y') self.assertEqual(f.formatDouble(-5.5, context), '-5x5%') self.assertEqual(f.formatDouble(-55555555.5, context), '-55y555y555x5%') f.setShowThousandsSeparator(False) self.assertEqual(f.formatDouble(-5.5, context), '-5x5%') self.assertEqual(f.formatDouble(-55555555.5, context), '-55555555x5%') context.setDecimalSeparator('.') f.setNumberDecimalPlaces(0) self.assertEqual(f.formatDouble(0, context), '0%') self.assertEqual(f.formatDouble(5.5, context), '6%') self.assertEqual(f.formatDouble(55555555.5, context), '55555556%') self.assertEqual(f.formatDouble(55555555.123456, context), '55555555%') self.assertEqual(f.formatDouble(-5.5, context), '-6%') self.assertEqual(f.formatDouble(-55555555.5, context), '-55555556%') f.setNumberDecimalPlaces(3) self.assertEqual(f.formatDouble(0, context), '0%') self.assertEqual(f.formatDouble(5.5, context), '5.5%') self.assertEqual(f.formatDouble(55555555.5, context), '55555555.5%') self.assertEqual(f.formatDouble(55555555.123456, context), '55555555.123%') self.assertEqual(f.formatDouble(-5.5, context), '-5.5%') self.assertEqual(f.formatDouble(-55555555.5, context), '-55555555.5%') f.setShowTrailingZeros(True) self.assertEqual(f.formatDouble(0, context), '0.000%') self.assertEqual(f.formatDouble(5, context), '5.000%') self.assertEqual(f.formatDouble(-5, context), '-5.000%') self.assertEqual(f.formatDouble(5.5, context), '5.500%') self.assertEqual(f.formatDouble(55555555.5, context), '55555555.500%') self.assertEqual(f.formatDouble(55555555.123456, context), '55555555.123%') self.assertEqual(f.formatDouble(-5.5, context), '-5.500%') self.assertEqual(f.formatDouble(-55555555.5, context), '-55555555.500%') f.setShowPlusSign(True) self.assertEqual(f.formatDouble(0, context), '0.000%') self.assertEqual(f.formatDouble(5, context), '+5.000%') self.assertEqual(f.formatDouble(-5, context), '-5.000%') self.assertEqual(f.formatDouble(5.5, context), '+5.500%') self.assertEqual(f.formatDouble(55555555.5, context), '+55555555.500%') self.assertEqual(f.formatDouble(55555555.123456, context), '+55555555.123%') self.assertEqual(f.formatDouble(-5.5, context), '-5.500%') self.assertEqual(f.formatDouble(-55555555.5, context), '-55555555.500%') f = QgsPercentageNumericFormat() f.setInputValues(QgsPercentageNumericFormat.ValuesAreFractions) context = QgsNumericFormatContext() self.assertEqual(f.formatDouble(0, context), '0%') self.assertEqual(f.formatDouble(5, context), '500%') self.assertEqual(f.formatDouble(5.5, context), '550%') self.assertEqual(f.formatDouble(-5, context), '-500%') self.assertEqual(f.formatDouble(-5.5, context), '-550%') self.assertEqual(f.formatDouble(-55555555.5, context), '-5,555,555,550%') context.setDecimalSeparator('x') self.assertEqual(f.formatDouble(0, context), '0%') self.assertEqual(f.formatDouble(-5.5, context), '-550%') self.assertEqual(f.formatDouble(-0.005, context), '-0x5%') context.setThousandsSeparator('y') self.assertEqual(f.formatDouble(-5.5, context), '-550%') self.assertEqual(f.formatDouble(-55555555.5, context), '-5y555y555y550%') f.setShowThousandsSeparator(False) self.assertEqual(f.formatDouble(-5.5, context), '-550%') self.assertEqual(f.formatDouble(-55555555.5, context), '-5555555550%') context.setDecimalSeparator('.') f.setNumberDecimalPlaces(0) self.assertEqual(f.formatDouble(0, context), '0%') self.assertEqual(f.formatDouble(5.5, context), '550%') self.assertEqual(f.formatDouble(55555555.5, context), '5555555550%') self.assertEqual(f.formatDouble(0.123456, context), '12%') self.assertEqual(f.formatDouble(-5.5, context), '-550%') self.assertEqual(f.formatDouble(-0.123456, context), '-12%') f.setNumberDecimalPlaces(3) self.assertEqual(f.formatDouble(0, context), '0%') self.assertEqual(f.formatDouble(5.5, context), '550%') self.assertEqual(f.formatDouble(55555555.5, context), '5555555550%') self.assertEqual(f.formatDouble(0.123456, context), '12.346%') self.assertEqual(f.formatDouble(-5.5, context), '-550%') self.assertEqual(f.formatDouble(-0.123456, context), '-12.346%') f.setShowTrailingZeros(True) self.assertEqual(f.formatDouble(0, context), '0.000%') self.assertEqual(f.formatDouble(5, context), '500.000%') self.assertEqual(f.formatDouble(-5, context), '-500.000%') self.assertEqual(f.formatDouble(0.5, context), '50.000%') self.assertEqual(f.formatDouble(55555555.5, context), '5555555550.000%') self.assertEqual(f.formatDouble(0.123456, context), '12.346%') self.assertEqual(f.formatDouble(-5.5, context), '-550.000%') self.assertEqual(f.formatDouble(-1234.5, context), '-123450.000%') f.setShowPlusSign(True) self.assertEqual(f.formatDouble(0, context), '0.000%') self.assertEqual(f.formatDouble(5, context), '+500.000%') self.assertEqual(f.formatDouble(-5, context), '-500.000%') self.assertEqual(f.formatDouble(5.5, context), '+550.000%') self.assertEqual(f.formatDouble(-5.5, context), '-550.000%') context.setPercent('p') self.assertEqual(f.formatDouble(0, context), '0.000p') self.assertEqual(f.formatDouble(5, context), '+500.000p') self.assertEqual(f.formatDouble(-5, context), '-500.000p') f2 = f.clone() self.assertIsInstance(f2, QgsPercentageNumericFormat) self.assertEqual(f2.showTrailingZeros(), f.showTrailingZeros()) self.assertEqual(f2.showPlusSign(), f.showPlusSign()) self.assertEqual(f2.numberDecimalPlaces(), f.numberDecimalPlaces()) self.assertEqual(f2.showThousandsSeparator(), f.showThousandsSeparator()) self.assertEqual(f2.inputValues(), f.inputValues()) doc = QDomDocument("testdoc") elem = doc.createElement("test") f2.writeXml(elem, doc, QgsReadWriteContext()) f3 = QgsNumericFormatRegistry().createFromXml(elem, QgsReadWriteContext()) self.assertIsInstance(f3, QgsPercentageNumericFormat) self.assertEqual(f3.showTrailingZeros(), f.showTrailingZeros()) self.assertEqual(f3.showPlusSign(), f.showPlusSign()) self.assertEqual(f3.numberDecimalPlaces(), f.numberDecimalPlaces()) self.assertEqual(f3.showThousandsSeparator(), f.showThousandsSeparator()) self.assertEqual(f3.inputValues(), f.inputValues())
def testCurrencyFormat(self): """ test currency formatter """ f = QgsCurrencyNumericFormat() f.setPrefix('$') context = QgsNumericFormatContext() f.setShowTrailingZeros(False) self.assertEqual(f.formatDouble(0, context), '$0') self.assertEqual(f.formatDouble(5, context), '$5') self.assertEqual(f.formatDouble(5.5, context), '$5.5') self.assertEqual(f.formatDouble(-5, context), '-$5') self.assertEqual(f.formatDouble(-5.5, context), '-$5.5') self.assertEqual(f.formatDouble(-55555555.5, context), '-$55,555,555.5') context.setDecimalSeparator('x') self.assertEqual(f.formatDouble(0, context), '$0') self.assertEqual(f.formatDouble(-5.5, context), '-$5x5') self.assertEqual(f.formatDouble(-55555555.5, context), '-$55,555,555x5') context.setThousandsSeparator('y') self.assertEqual(f.formatDouble(-5.5, context), '-$5x5') self.assertEqual(f.formatDouble(-55555555.5, context), '-$55y555y555x5') f.setShowThousandsSeparator(False) self.assertEqual(f.formatDouble(-5.5, context), '-$5x5') self.assertEqual(f.formatDouble(-55555555.5, context), '-$55555555x5') context.setDecimalSeparator('.') f.setNumberDecimalPlaces(0) self.assertEqual(f.formatDouble(0, context), '$0') self.assertEqual(f.formatDouble(5.5, context), '$6') self.assertEqual(f.formatDouble(55555555.5, context), '$55555556') self.assertEqual(f.formatDouble(55555555.123456, context), '$55555555') self.assertEqual(f.formatDouble(-5.5, context), '-$6') self.assertEqual(f.formatDouble(-55555555.5, context), '-$55555556') f.setNumberDecimalPlaces(3) self.assertEqual(f.formatDouble(0, context), '$0') self.assertEqual(f.formatDouble(5.5, context), '$5.5') self.assertEqual(f.formatDouble(55555555.5, context), '$55555555.5') self.assertEqual(f.formatDouble(55555555.123456, context), '$55555555.123') self.assertEqual(f.formatDouble(-5.5, context), '-$5.5') self.assertEqual(f.formatDouble(-55555555.5, context), '-$55555555.5') f.setShowTrailingZeros(True) self.assertEqual(f.formatDouble(0, context), '$0.000') self.assertEqual(f.formatDouble(5, context), '$5.000') self.assertEqual(f.formatDouble(-5, context), '-$5.000') self.assertEqual(f.formatDouble(5.5, context), '$5.500') self.assertEqual(f.formatDouble(55555555.5, context), '$55555555.500') self.assertEqual(f.formatDouble(55555555.123456, context), '$55555555.123') self.assertEqual(f.formatDouble(-5.5, context), '-$5.500') self.assertEqual(f.formatDouble(-55555555.5, context), '-$55555555.500') f.setShowPlusSign(True) self.assertEqual(f.formatDouble(0, context), '$0.000') self.assertEqual(f.formatDouble(5, context), '+$5.000') self.assertEqual(f.formatDouble(-5, context), '-$5.000') self.assertEqual(f.formatDouble(5.5, context), '+$5.500') self.assertEqual(f.formatDouble(55555555.5, context), '+$55555555.500') self.assertEqual(f.formatDouble(55555555.123456, context), '+$55555555.123') self.assertEqual(f.formatDouble(-5.5, context), '-$5.500') self.assertEqual(f.formatDouble(-55555555.5, context), '-$55555555.500') f.setSuffix('AUD') self.assertEqual(f.formatDouble(0, context), '$0.000AUD') self.assertEqual(f.formatDouble(5, context), '+$5.000AUD') self.assertEqual(f.formatDouble(-5, context), '-$5.000AUD') self.assertEqual(f.formatDouble(5.5, context), '+$5.500AUD') self.assertEqual(f.formatDouble(55555555.5, context), '+$55555555.500AUD') self.assertEqual(f.formatDouble(55555555.123456, context), '+$55555555.123AUD') self.assertEqual(f.formatDouble(-5.5, context), '-$5.500AUD') self.assertEqual(f.formatDouble(-55555555.5, context), '-$55555555.500AUD') f2 = f.clone() self.assertIsInstance(f2, QgsCurrencyNumericFormat) self.assertEqual(f2.showTrailingZeros(), f.showTrailingZeros()) self.assertEqual(f2.showPlusSign(), f.showPlusSign()) self.assertEqual(f2.numberDecimalPlaces(), f.numberDecimalPlaces()) self.assertEqual(f2.showThousandsSeparator(), f.showThousandsSeparator()) self.assertEqual(f2.prefix(), f.prefix()) self.assertEqual(f2.suffix(), f.suffix()) doc = QDomDocument("testdoc") elem = doc.createElement("test") f2.writeXml(elem, doc, QgsReadWriteContext()) f3 = QgsNumericFormatRegistry().createFromXml(elem, QgsReadWriteContext()) self.assertIsInstance(f3, QgsCurrencyNumericFormat) self.assertEqual(f3.showTrailingZeros(), f.showTrailingZeros()) self.assertEqual(f3.showPlusSign(), f.showPlusSign()) self.assertEqual(f3.numberDecimalPlaces(), f.numberDecimalPlaces()) self.assertEqual(f3.showThousandsSeparator(), f.showThousandsSeparator()) self.assertEqual(f3.prefix(), f.prefix()) self.assertEqual(f3.suffix(), f.suffix())
def testSimple(self): s = QgsFillSymbol() s.deleteSymbolLayer(0) random_fill = QgsRandomMarkerFillSymbolLayer(10, seed=481523) marker = QgsSimpleMarkerSymbolLayer( QgsSimpleMarkerSymbolLayer.Triangle, 4) marker.setColor(QColor(255, 0, 0)) marker.setStrokeStyle(Qt.NoPen) marker_symbol = QgsMarkerSymbol() marker_symbol.changeSymbolLayer(0, marker) random_fill.setSubSymbol(marker_symbol) s.appendSymbolLayer(random_fill.clone()) self.assertEqual(s.symbolLayer(0).pointCount(), 10) self.assertEqual(s.symbolLayer(0).seed(), 481523) s.symbolLayer(0).setPointCount(5) s.symbolLayer(0).setSeed(42) self.assertEqual(s.symbolLayer(0).pointCount(), 5) self.assertEqual(s.symbolLayer(0).seed(), 42) s2 = s.clone() self.assertEqual(s2.symbolLayer(0).pointCount(), 5) self.assertEqual(s2.symbolLayer(0).seed(), 42) doc = QDomDocument() context = QgsReadWriteContext() element = QgsSymbolLayerUtils.saveSymbol('test', s, doc, context) s2 = QgsSymbolLayerUtils.loadSymbol(element, context) self.assertEqual(s2.symbolLayer(0).pointCount(), 5) self.assertEqual(s2.symbolLayer(0).seed(), 42) # rendering test s3 = QgsFillSymbol() s3.deleteSymbolLayer(0) s3.appendSymbolLayer(random_fill.clone()) g = QgsGeometry.fromWkt( 'Polygon((0 0, 10 0, 10 10, 0 10, 0 0),(1 1, 1 2, 2 2, 2 1, 1 1),(8 8, 9 8, 9 9, 8 9, 8 8))' ) rendered_image = self.renderGeometry(s3, g) self.assertTrue( self.imageCheck('randommarkerfill', 'randommarkerfill', rendered_image)) s3.symbolLayer(0).setPointCount(3) g = QgsGeometry.fromWkt( 'Polygon((0 0, 10 0, 10 10, 0 10, 0 0),(1 1, 1 2, 2 2, 2 1, 1 1),(8 8, 9 8, 9 9, 8 9, 8 8))' ) rendered_image = self.renderGeometry(s3, g) self.assertTrue( self.imageCheck('randommarkerfill_3', 'randommarkerfill_3', rendered_image)) s3.symbolLayer(0).setSeed(12783) g = QgsGeometry.fromWkt( 'Polygon((0 0, 10 0, 10 10, 0 10, 0 0),(1 1, 1 2, 2 2, 2 1, 1 1),(8 8, 9 8, 9 9, 8 9, 8 8))' ) rendered_image = self.renderGeometry(s3, g) self.assertTrue( self.imageCheck('randommarkerfill_seed', 'randommarkerfill_seed', rendered_image)) # random seed s3.symbolLayer(0).setSeed(0) g = QgsGeometry.fromWkt( 'Polygon((0 0, 10 0, 10 10, 0 10, 0 0),(1 1, 1 2, 2 2, 2 1, 1 1),(8 8, 9 8, 9 9, 8 9, 8 8))' ) rendered_image = self.renderGeometry(s3, g) self.assertFalse( self.imageCheck('randommarkerfill_seed', 'randommarkerfill_seed', rendered_image, expect_fail=True)) # density-based count s3.symbolLayer(0).setSeed(1) s3.symbolLayer(0).setCountMethod( QgsRandomMarkerFillSymbolLayer.DensityBasedCount) s3.symbolLayer(0).setPointCount(5) s3.symbolLayer(0).setDensityArea(250) # 250 square millimeter g = QgsGeometry.fromWkt( 'Polygon((0 0, 10 0, 10 10, 0 10, 0 0),(1 1, 1 2, 2 2, 2 1, 1 1),(8 8, 9 8, 9 9, 8 9, 8 8))' ) rendered_image = self.renderGeometry(s3, g) self.assertTrue( self.imageCheck('randommarkerfill_densitybasedcount', 'randommarkerfill_densitybasedcount', rendered_image))
def qgis_composer_renderer(impact_report, component): """Default Map Report Renderer using QGIS Composer. Render using qgis composer for a given impact_report data and component context. :param impact_report: ImpactReport contains data about the report that is going to be generated. :type impact_report: safe.report.impact_report.ImpactReport :param component: Contains the component metadata and context for rendering the output. :type component: safe.report.report_metadata.QgisComposerComponentsMetadata :return: Whatever type of output the component should be. .. versionadded:: 4.0 """ context = component.context qgis_composition_context = impact_report.qgis_composition_context # load composition object layout = QgsPrintLayout(QgsProject.instance()) # load template main_template_folder = impact_report.metadata.template_folder # we do this condition in case custom template was found if component.template.startswith('../qgis-composer-templates/'): template_path = os.path.join(main_template_folder, component.template) else: template_path = component.template with open(template_path) as template_file: template_content = template_file.read() document = QtXml.QDomDocument() # Replace for k, v in context.substitution_map.items(): template_content = template_content.replace('[{}]'.format(k), v) document.setContent(template_content) rwcontext = QgsReadWriteContext() load_status = layout.loadFromTemplate( document, rwcontext) if not load_status: raise TemplateLoadingError( tr('Error loading template: %s') % template_path) # replace image path for img in context.image_elements: item_id = img.get('id') path = img.get('path') image = layout_item(layout, item_id, QgsLayoutItemPicture) if image and path: image.setPicturePath(path) # replace html frame for html_el in context.html_frame_elements: item_id = html_el.get('id') mode = html_el.get('mode') html_element = layout_item(layout, item_id, QgsLayoutItemHtml) if html_element: if mode == 'text': text = html_el.get('text') text = text if text else '' html_element.setContentMode(QgsLayoutItemHtml.ManualHtml) html_element.setHtml(text) html_element.loadHtml() elif mode == 'url': url = html_el.get('url') html_element.setContentMode(QgsLayoutItemHtml.Url) qurl = QUrl.fromLocalFile(url) html_element.setUrl(qurl) original_crs = impact_report.impact_function.crs destination_crs = qgis_composition_context.map_settings.destinationCrs() coord_transform = QgsCoordinateTransform(original_crs, destination_crs, QgsProject.instance()) # resize map extent for map_el in context.map_elements: item_id = map_el.get('id') split_count = map_el.get('grid_split_count') layers = [ layer for layer in map_el.get('layers') if isinstance( layer, QgsMapLayer) ] map_extent_option = map_el.get('extent') composer_map = layout_item(layout, item_id, QgsLayoutItemMap) for index, layer in enumerate(layers): # we need to check whether the layer is registered or not registered_layer = ( QgsProject.instance().mapLayer(layer.id())) if registered_layer: if not registered_layer == layer: layers[index] = registered_layer else: QgsProject.instance().addMapLayer(layer) """:type: qgis.core.QgsLayoutItemMap""" if composer_map: # Search for specified map extent in the template. min_x = composer_map.extent().xMinimum() if ( impact_report.use_template_extent) else None min_y = composer_map.extent().yMinimum() if ( impact_report.use_template_extent) else None max_x = composer_map.extent().xMaximum() if ( impact_report.use_template_extent) else None max_y = composer_map.extent().yMaximum() if ( impact_report.use_template_extent) else None composer_map.setKeepLayerSet(True) layer_set = [l for l in layers if isinstance(l, QgsMapLayer)] composer_map.setLayers(layer_set) map_overview_extent = None if map_extent_option and isinstance( map_extent_option, QgsRectangle): # use provided map extent extent = coord_transform.transform(map_extent_option) for l in [layer for layer in layers if isinstance(layer, QgsMapLayer)]: layer_extent = coord_transform.transform(l.extent()) if l.name() == map_overview['id']: map_overview_extent = layer_extent else: # if map extent not provided, try to calculate extent # from list of given layers. Combine it so all layers were # shown properly extent = QgsRectangle() extent.setMinimal() for l in [layer for layer in layers if isinstance(layer, QgsMapLayer)]: # combine extent if different layer is provided. layer_extent = coord_transform.transform(l.extent()) extent.combineExtentWith(layer_extent) if l.name() == map_overview['id']: map_overview_extent = layer_extent width = extent.width() height = extent.height() longest_width = width if width > height else height half_length = longest_width / 2 margin = half_length / 5 center = extent.center() min_x = min_x or (center.x() - half_length - margin) max_x = max_x or (center.x() + half_length + margin) min_y = min_y or (center.y() - half_length - margin) max_y = max_y or (center.y() + half_length + margin) # noinspection PyCallingNonCallable square_extent = QgsRectangle(min_x, min_y, max_x, max_y) if component.key == 'population-infographic' and ( map_overview_extent): square_extent = map_overview_extent composer_map.zoomToExtent(square_extent) composer_map.invalidateCache() actual_extent = composer_map.extent() # calculate intervals for grid x_interval = actual_extent.width() / split_count composer_map.grid().setIntervalX(x_interval) y_interval = actual_extent.height() / split_count composer_map.grid().setIntervalY(y_interval) # calculate legend element for leg_el in context.map_legends: item_id = leg_el.get('id') title = leg_el.get('title') layers = [ layer for layer in leg_el.get('layers') if isinstance( layer, QgsMapLayer) ] symbol_count = leg_el.get('symbol_count') column_count = leg_el.get('column_count') legend = layout_item(layout, item_id, QgsLayoutItemLegend) """:type: qgis.core.QgsLayoutItemLegend""" if legend: # set column count if column_count: legend.setColumnCount(column_count) elif symbol_count <= 7: legend.setColumnCount(1) else: legend.setColumnCount(symbol_count / 7 + 1) # set legend title if title is not None and not impact_report.legend_layers: legend.setTitle(title) # set legend root_group = legend.model().rootGroup() for layer in layers: # we need to check whether the layer is registered or not registered_layer = ( QgsProject.instance().mapLayer(layer.id())) if registered_layer: if not registered_layer == layer: layer = registered_layer else: QgsProject.instance().addMapLayer(layer) # used for customizations tree_layer = root_group.addLayer(layer) if impact_report.legend_layers or ( not impact_report.multi_exposure_impact_function): QgsLegendRenderer.setNodeLegendStyle( tree_layer, QgsLegendStyle.Hidden) legend.adjustBoxSize() legend.updateFilterByMap(False) # process to output # in case output folder not specified if impact_report.output_folder is None: impact_report.output_folder = mkdtemp(dir=temp_dir()) output_format = component.output_format component_output_path = impact_report.component_absolute_output_path( component.key) component_output = None doc_format = QgisComposerComponentsMetadata.OutputFormat.DOC_OUTPUT template_format = QgisComposerComponentsMetadata.OutputFormat.QPT if isinstance(output_format, list): component_output = [] for i in range(len(output_format)): each_format = output_format[i] each_path = component_output_path[i] if each_format in doc_format: result_path = create_qgis_pdf_output( impact_report, each_path, layout, each_format, component) component_output.append(result_path) elif each_format == template_format: result_path = create_qgis_template_output( each_path, layout) component_output.append(result_path) elif isinstance(output_format, dict): component_output = {} for key, each_format in list(output_format.items()): each_path = component_output_path[key] if each_format in doc_format: result_path = create_qgis_pdf_output( impact_report, each_path, layout, each_format, component) component_output[key] = result_path elif each_format == template_format: result_path = create_qgis_template_output( each_path, layout) component_output[key] = result_path elif (output_format in QgisComposerComponentsMetadata.OutputFormat.SUPPORTED_OUTPUT): component_output = None if output_format in doc_format: result_path = create_qgis_pdf_output( impact_report, component_output_path, layout, output_format, component) component_output = result_path elif output_format == template_format: result_path = create_qgis_template_output( component_output_path, layout) component_output = result_path component.output = component_output return component.output
def addLayer(self, uri, fileName, layerId, group=None, visible=False, expanded=False): theLayer = None # read QGIS project doc, _ = self.getQgsDoc(fileName) # is project in relative path ? absolute = is_absolute(doc) trusted = project_trusted(doc) node = getFirstChildByTagNameValue(doc.documentElement(), "maplayer", "id", layerId) node = node.cloneNode() if node: idNode = node.namedItem("id") layerType = node.toElement().attribute("type", "vector") # give it a new id (for multiple import) newLayerId = "L%s" % re.sub("[{}-]", "", QUuid.createUuid().toString()) try: idNode.firstChild().toText().setData(newLayerId) except Exception: pass # if relative path, adapt datasource if not absolute: try: datasourceNode = node.namedItem("datasource") ds = datasourceNode.firstChild().toText().data() providerNode = node.namedItem("provider") provider = providerNode.firstChild().toText().data() if provider in ["ogr", "gdal"] and (ds.find(".") == 0): projectpath = QFileInfo(uri).path() newlayerpath = projectpath + "/" + ds datasourceNode.firstChild().toText().setData( newlayerpath) except Exception: pass # read modified layer node if self.optionCreateGroup and group is not None: if layerType == "raster": theLayer = QgsRasterLayer() else: theLayer = QgsVectorLayer() theLayer.setReadExtentFromXml(trusted) theLayer.readLayerXml(node.toElement(), QgsReadWriteContext()) # Special process if the plugin "DB Style Manager" is installed flag = "use_db_style_manager_in_custom_menu" in os.environ if flag and "db-style-manager" in plugins: try: plugins["db-style-manager"].load_style_from_database( theLayer) except Exception: self.log("DB-Style-Manager failed to load the style.") # needed QgsProject.instance().addMapLayer(theLayer, False) # add to group treeNode = group.insertLayer(0, theLayer) treeNode.setExpanded(expanded) treeNode.setItemVisibilityChecked(visible) else: # create layer theLayer = QgsProject.instance().readLayer(node) return QgsProject.instance().mapLayer(newLayerId) else: self.log("{} not found".format(layerId)) return None
def testWriteReadXmlProj6(self): # setup a context context = QgsCoordinateTransformContext() proj_1 = '+proj=pipeline +step +proj=axisswap +order=2,1 +step +proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=push +v_3 +step +proj=cart +ellps=intl +step +proj=helmert +x=-18.944 +y=-379.364 +z=-24.063 +rx=-0.04 +ry=0.764 +rz=-6.431 +s=3.657 +convention=coordinate_frame +step +inv +proj=cart +ellps=WGS84 +step +proj=pop +v_3 +step +proj=unitconvert +xy_in=rad +xy_out=deg +step +proj=axisswap +order=2,1' proj_2 = '+proj=pipeline +step +proj=axisswap +order=2,1 +step +proj=unitconvert +xy_in=deg +xy_out=rad +step +proj=push +v_3 +step +proj=cart +ellps=intl +step +proj=helmert +x=-150 +y=-250 +z=-1 +step +inv +proj=cart +ellps=WGS84 +step +proj=pop +v_3 +step +proj=unitconvert +xy_in=rad +xy_out=deg +step +proj=axisswap +order=2,1' proj_3 = '+proj=pipeline +step +proj=axisswap +order=2,1' self.assertTrue( context.addCoordinateOperation( QgsCoordinateReferenceSystem('EPSG:4204'), QgsCoordinateReferenceSystem('EPSG:4326'), proj_1, True)) self.assertTrue( context.addCoordinateOperation( QgsCoordinateReferenceSystem('EPSG:4205'), QgsCoordinateReferenceSystem('EPSG:4326'), proj_2, False)) # also insert a crs with no authid available self.assertTrue( context.addCoordinateOperation( QgsCoordinateReferenceSystem.fromProj( "+proj=longlat +a=6378137 +rf=298.25722356300003 +no_defs" ), QgsCoordinateReferenceSystem('EPSG:4326'), proj_3, False)) self.assertEqual( context.coordinateOperations(), { ('EPSG:4204', 'EPSG:4326'): proj_1, ('EPSG:4205', 'EPSG:4326'): proj_2, ('', 'EPSG:4326'): proj_3 }) # save to xml doc = QDomDocument("testdoc") elem = doc.createElement("test") context.writeXml(elem, QgsReadWriteContext()) # restore from xml context2 = QgsCoordinateTransformContext() context2.readXml(elem, QgsReadWriteContext()) # check result self.assertEqual( context2.coordinateOperations(), { ('EPSG:4204', 'EPSG:4326'): proj_1, ('EPSG:4205', 'EPSG:4326'): proj_2, ('', 'EPSG:4326'): proj_3 }) self.assertEqual( context2.calculateCoordinateOperation( QgsCoordinateReferenceSystem.fromProj( "+proj=longlat +a=6378137 +rf=298.25722356300003 +no_defs" ), QgsCoordinateReferenceSystem('EPSG:4326')), '+proj=pipeline +step +proj=axisswap +order=2,1') self.assertFalse( context2.mustReverseCoordinateOperation( QgsCoordinateReferenceSystem.fromProj( "+proj=longlat +a=6378137 +rf=298.25722356300003 +no_defs" ), QgsCoordinateReferenceSystem('EPSG:4326'))) self.assertEqual( context2.calculateCoordinateOperation( QgsCoordinateReferenceSystem('EPSG:4326'), QgsCoordinateReferenceSystem.fromProj( "+proj=longlat +a=6378137 +rf=298.25722356300003 +no_defs") ), '+proj=pipeline +step +proj=axisswap +order=2,1') self.assertTrue( context2.mustReverseCoordinateOperation( QgsCoordinateReferenceSystem('EPSG:4326'), QgsCoordinateReferenceSystem.fromProj( "+proj=longlat +a=6378137 +rf=298.25722356300003 +no_defs") )) self.assertTrue( context2.allowFallbackTransform( QgsCoordinateReferenceSystem('EPSG:4204'), QgsCoordinateReferenceSystem('EPSG:4326'))) self.assertFalse( context2.allowFallbackTransform( QgsCoordinateReferenceSystem('EPSG:4205'), QgsCoordinateReferenceSystem('EPSG:4326')))
def __init__(self, size=QSizeF(400, 200), render_type=POINT_RENDERER, x_orientation=ORIENTATION_LEFT_TO_RIGHT, y_orientation=ORIENTATION_UPWARD, allow_mouse_translation=False, allow_wheel_zoom=False, symbology=None, parent_item=None): """ Parameters ---------- size: QSize Size of the item render_type: Literal[POINT_RENDERER, LINE_RENDERER, POLYGON_RENDERER] Type of renderer x_orientation: Literal[ORIENTATION_LEFT_TO_RIGHT, ORIENTATION_RIGHT_TO_LEFT] y_orientation: Literal[ORIENTATION_UPWARD, ORIENTATION_DOWNWARD] allow_mouse_translation: bool Allow the user to translate the item with the mouse (??) allow_wheel_zoom: bool Allow the user to zoom with the mouse wheel symbology: QDomDocument QGIS symbology to use for the renderer parent_item: QGraphicsItem """ LogItem.__init__(self, parent_item) self.__item_size = size self.__data_rect = None self.__data = None self.__delta = None self.__x_orientation = x_orientation self.__y_orientation = y_orientation # origin point of the graph translation, if any self.__translation_orig = None self.__render_type = render_type # type: Literal[POINT_RENDERER, LINE_RENDERER, POLYGON_RENDERER] self.__allow_mouse_translation = allow_mouse_translation self.__allow_wheel_zoom = allow_wheel_zoom self.__layer = None self.__default_renderers = [ QgsFeatureRenderer.defaultRenderer(POINT_RENDERER), QgsFeatureRenderer.defaultRenderer(LINE_RENDERER), QgsFeatureRenderer.defaultRenderer(POLYGON_RENDERER) ] symbol = self.__default_renderers[1].symbol() symbol.setWidth(1.0) symbol = self.__default_renderers[0].symbol() symbol.setSize(5.0) symbol = self.__default_renderers[2].symbol() symbol.symbolLayers()[0].setStrokeWidth(1.0) if not symbology: self.__renderer = self.__default_renderers[self.__render_type] else: self.__renderer = QgsFeatureRenderer.load( symbology.documentElement(), QgsReadWriteContext()) # index of the current point to label self.__old_point_to_label = None self.__point_to_label = None
def test_settings(self): settings = QgsColorRampLegendNodeSettings() settings.setDirection(QgsColorRampLegendNodeSettings.MaximumToMinimum) self.assertEqual(settings.direction(), QgsColorRampLegendNodeSettings.MaximumToMinimum) settings.setMinimumLabel('min') self.assertEqual(settings.minimumLabel(), 'min') settings.setMaximumLabel('max') self.assertEqual(settings.maximumLabel(), 'max') settings.setPrefix('pref') self.assertEqual(settings.prefix(), 'pref') settings.setSuffix('suff') self.assertEqual(settings.suffix(), 'suff') self.assertEqual(settings.orientation(), Qt.Vertical) settings.setOrientation(Qt.Horizontal) self.assertEqual(settings.orientation(), Qt.Horizontal) # Test default self.assertTrue(settings.useContinuousLegend()) settings.setUseContinuousLegend(False) self.assertFalse(settings.useContinuousLegend()) self.assertFalse(settings.textFormat().isValid()) tf = QgsTextFormat() tf.setSize(13) settings.setTextFormat(tf) self.assertEqual(settings.textFormat().size(), 13) self.assertIsNotNone(settings.numericFormat()) settings.setNumericFormat(QgsBearingNumericFormat()) self.assertIsInstance(settings.numericFormat(), QgsBearingNumericFormat) settings2 = QgsColorRampLegendNodeSettings(settings) self.assertEqual(settings2.direction(), QgsColorRampLegendNodeSettings.MaximumToMinimum) self.assertEqual(settings2.minimumLabel(), 'min') self.assertEqual(settings2.maximumLabel(), 'max') self.assertIsInstance(settings2.numericFormat(), QgsBearingNumericFormat) self.assertEqual(settings2.prefix(), 'pref') self.assertEqual(settings2.suffix(), 'suff') self.assertEqual(settings2.textFormat().size(), 13) self.assertEqual(settings2.orientation(), Qt.Horizontal) settings2.setTextFormat(QgsTextFormat()) settings2a = QgsColorRampLegendNodeSettings(settings2) self.assertFalse(settings2a.textFormat().isValid()) doc = QDomDocument("testdoc") elem = doc.createElement('test') settings.writeXml(doc, elem, QgsReadWriteContext()) settings3 = QgsColorRampLegendNodeSettings() settings3.readXml(elem, QgsReadWriteContext()) self.assertEqual(settings3.direction(), QgsColorRampLegendNodeSettings.MaximumToMinimum) self.assertEqual(settings3.minimumLabel(), 'min') self.assertEqual(settings3.maximumLabel(), 'max') self.assertIsInstance(settings3.numericFormat(), QgsBearingNumericFormat) self.assertEqual(settings3.prefix(), 'pref') self.assertEqual(settings3.suffix(), 'suff') self.assertEqual(settings3.textFormat().size(), 13) self.assertEqual(settings3.orientation(), Qt.Horizontal) self.assertFalse(settings3.useContinuousLegend()) # no text format elem = doc.createElement('test2') settings2.writeXml(doc, elem, QgsReadWriteContext()) settings3a = QgsColorRampLegendNodeSettings() settings3a.readXml(elem, QgsReadWriteContext()) self.assertFalse(settings3a.textFormat().isValid())
def makeAtlas(qptChapter, qptDivision, qptForm, zl_layer, zl_field, di_layer, di_field, di_name, scale, form_file=None, form=False, project_name='', root_out='', pbar=False, isTest=True): root_code = os.path.dirname(os.path.realpath(__file__)) ## getpapersize template_file = open(qptDivision, 'r') template_content = template_file.read() template_file.close() document = QDomDocument() document.setContent(template_content) p = QgsProject().instance() composition = QgsLayout(p) composition.loadFromTemplate(document, QgsReadWriteContext()) map_item = composition.itemById('mapa') paper = [ map_item.sizeWithUnits().width(), map_item.sizeWithUnits().height() ] ##get visible layers visibleLayers = p.mapThemeCollection().masterVisibleLayers() ## get project srid... crs = zl_layer.dataProvider().sourceCrs().authid() ## zones 1 layer zvl = zl_layer.clone() global ZVL ZVL = zvl.id() QgsProject.instance().addMapLayer(zvl) #pr = zvl.dataProvider() QgsProject.instance().mapLayer(ZVL).loadNamedStyle( root_code + '/templates/layerstyles/zones.qml') ## divisions 1 layer dvl = QgsVectorLayer("Polygon?crs=" + crs, "divisions_layer", "memory") global DVL DVL = dvl.id() QgsProject.instance().addMapLayer(dvl) #pr = dvl.dataProvider() QgsProject.instance().mapLayer(DVL).startEditing() QgsProject.instance().mapLayer(DVL).loadNamedStyle( root_code + '/templates/layerstyles/div1.qml') pr_dvl = QgsProject.instance().mapLayer(DVL).dataProvider() pr_dvl.addAttributes([ QgsField('id', QVariant.String), QgsField('name', QVariant.String), QgsField('ang', QVariant.String), QgsField('x', QVariant.String), QgsField('y', QVariant.String), ]) QgsProject.instance().mapLayer(DVL).commitChanges() ## divisions 2 layer dvl2 = QgsVectorLayer("Polygon?crs=" + crs, "divisions_layer", "memory") global DVL2 DVL2 = dvl2.id() QgsProject.instance().addMapLayer(dvl2) #pr = dvl2.dataProvider() QgsProject.instance().mapLayer(DVL2).startEditing() QgsProject.instance().mapLayer(DVL2).loadNamedStyle( root_code + '/templates/layerstyles/div2.qml') pr_dvl2 = QgsProject.instance().mapLayer(DVL2).dataProvider() pr_dvl2.addAttributes([ QgsField('id', QVariant.String), QgsField('name', QVariant.String), QgsField('ang', QVariant.String), QgsField('x', QVariant.String), QgsField('y', QVariant.String), ]) QgsProject.instance().mapLayer(DVL2).commitChanges() debug('>> layers setted') ##makestyles:: p = QgsProject.instance() #_zona_big p.mapThemeCollection().removeMapTheme('_zona_big') rec = QgsMapThemeCollection().MapThemeRecord() recList = [] vl = visibleLayers for v in vl: recList.append(QgsMapThemeCollection().MapThemeLayerRecord(v)) recList.append(QgsMapThemeCollection().MapThemeLayerRecord(zvl)) recList.append(QgsMapThemeCollection().MapThemeLayerRecord(dvl)) recList.append(QgsMapThemeCollection().MapThemeLayerRecord(dvl2)) rec.setLayerRecords(recList) p.mapThemeCollection().insert('_zona_big', rec) #_zona_small p.mapThemeCollection().removeMapTheme('_zona_small') rec = QgsMapThemeCollection().MapThemeRecord() recList = [] vl = visibleLayers for v in vl: recList.append(QgsMapThemeCollection().MapThemeLayerRecord(v)) if di_layer not in vl: recList.append(QgsMapThemeCollection().MapThemeLayerRecord(di_layer)) recList.append(QgsMapThemeCollection().MapThemeLayerRecord(zvl)) rec.setLayerRecords(recList) p.mapThemeCollection().insert('_zona_small', rec) #_szona_big p.mapThemeCollection().removeMapTheme('_szona_big') rec = QgsMapThemeCollection().MapThemeRecord() recList = [] vl = visibleLayers for v in vl: recList.append(QgsMapThemeCollection().MapThemeLayerRecord(v)) if di_layer not in vl: recList.append(QgsMapThemeCollection().MapThemeLayerRecord(di_layer)) recList.append(QgsMapThemeCollection().MapThemeLayerRecord(zvl)) rec.setLayerRecords(recList) p.mapThemeCollection().insert('_szona_big', rec) #_szona_small p.mapThemeCollection().removeMapTheme('_szona_small') rec = QgsMapThemeCollection().MapThemeRecord() recList = [] vl = visibleLayers for v in vl: recList.append(QgsMapThemeCollection().MapThemeLayerRecord(v)) if di_layer not in vl: recList.append(QgsMapThemeCollection().MapThemeLayerRecord(di_layer)) recList.append(QgsMapThemeCollection().MapThemeLayerRecord(zvl)) recList.append(QgsMapThemeCollection().MapThemeLayerRecord(dvl)) recList.append(QgsMapThemeCollection().MapThemeLayerRecord(dvl2)) rec.setLayerRecords(recList) p.mapThemeCollection().insert('_szona_small', rec) global mapL mapLmake() ##se puede agilizar #Lz = zl_layer #QgsProject.instance().mapLayer(mapL['zones']) #Lb = QgsProject.instance().mapLayer(mapL['bounds']) #Ld = QgsProject.instance().mapLayer(mapL['divisions']) ########################################################################### x = 0 global pag pag = 1 #for b in Lb.getFeatures(): fr = 0 zones_f = [zzz for zzz in zl_layer.getFeatures()] if pbar: pbar.setValue(1) for b in zones_f: if pbar: pbar.setValue(100 / len(zones_f) * fr) fr += 1 debug('>>>> chapter: ') debug(b.attributes()) #isTest #self.dlg.progressBar.setValue(int(10)) szs = getSubzones(b, paper, scale) mkChapter(b, qptChapter, project_name, root_out, zl_layer, zl_field, di_layer, di_field, di_name) szfr = 0 for sz in szs: szfr += 1 if pbar: pbar.setValue(100 / len(zones_f) * fr + 100 / len(zones_f) / len(szs) * szfr) debug('>>>> division: ') mkDiv(sz, b.geometry(), qptDivision, project_name, root_out, zl_layer, zl_field, di_layer, di_field, di_name) if form: mkForm(sz, qptForm, form_file, project_name, root_out, zl_layer, zl_field, di_layer, di_field, di_name) if isTest: break if isTest: break x += 1 #emptyTemp() # #remove styles p.mapThemeCollection().removeMapTheme('_zona_big') p.mapThemeCollection().removeMapTheme('_zona_small') p.mapThemeCollection().removeMapTheme('_szona_big') p.mapThemeCollection().removeMapTheme('_szona_small') #remove layers QgsProject.instance().removeMapLayer(ZVL) QgsProject.instance().removeMapLayer(DVL) QgsProject.instance().removeMapLayer(DVL2) debug('end') return
def print_atlas(self, project_path, composer_name, predefined_scales, feature_filter=None, page_name_expression=None ): if not feature_filter: QgsMessageLog.logMessage("atlasprint: NO feature_filter provided !", 'atlasprint', Qgis.Info) return None # Get composer from project # in QGIS 2, canno get composers without iface # so we reading project xml and extract composer # in QGIS 3.0, we will use project layoutManager() from xml.etree import ElementTree as ET composer_xml = None with open(project_path, 'r') as f: tree = ET.parse(f) for elem in tree.findall('.//Composer[@title="%s"]' % composer_name): composer_xml = ET.tostring( elem, encoding='utf8', method='xml' ) if not composer_xml: for elem in tree.findall('.//Layout[@name="%s"]' % composer_name): composer_xml = ET.tostring( elem, encoding='utf8', method='xml' ) if not composer_xml: QgsMessageLog.logMessage("atlasprint: Composer XML not parsed !", 'atlasprint', Qgis.Info) return None document = QDomDocument() document.setContent(composer_xml) # Get canvas, map setting & instantiate composition canvas = QgsMapCanvas() project = QgsProject() project.read(project_path) bridge = QgsLayerTreeMapCanvasBridge( project.layerTreeRoot(), canvas ) bridge.setCanvasLayers() layout = QgsPrintLayout(project) # Load content from XML layout.loadFromTemplate( document, QgsReadWriteContext(), ) atlas = layout.atlas() atlas.setEnabled(True) atlas_map = layout.referenceMap() atlas_map.setAtlasDriven(True) atlas_map.setAtlasScalingMode( QgsLayoutItemMap.Predefined ) layout.reportContext().setPredefinedScales(predefined_scales) if page_name_expression: atlas.setPageNameExpression(page_name_expression) # Filter feature here to avoid QGIS looping through every feature when doing : composition.setAtlasMode(QgsComposition.ExportAtlas) coverageLayer = atlas.coverageLayer() # Filter by FID as QGIS cannot compile expressions with $id or other $ vars # which leads to bad perfs for big datasets useFid = None if '$id' in feature_filter: import re ids = list(map(int, re.findall(r'\d+', feature_filter))) if len(ids) > 0: useFid = ids[0] if useFid: qReq = QgsFeatureRequest().setFilterFid(useFid) else: qReq = QgsFeatureRequest().setFilterExpression(feature_filter) # Change feature_filter in order to improve perfs pks = coverageLayer.dataProvider().pkAttributeIndexes() if useFid and len(pks) == 1: pk = coverageLayer.dataProvider().fields()[pks[0]].name() feature_filter = '"%s" IN (%s)' % (pk, useFid) QgsMessageLog.logMessage("atlasprint: feature_filter changed into: %s" % feature_filter, 'atlasprint', Qgis.Info) qReq = QgsFeatureRequest().setFilterExpression(feature_filter) atlas.setFilterFeatures(True) atlas.setFilterExpression(feature_filter) uid = uuid4() i = 0 atlas.beginRender() atlas.seekTo(i) # setup settings settings = QgsLayoutExporter.PdfExportSettings() export_path = os.path.join( tempfile.gettempdir(), '%s_%s.pdf' % (atlas.nameForPage(i), uid) ) exporter = QgsLayoutExporter(layout) result = exporter.exportToPdf(export_path, settings) atlas.endRender() if result != QgsLayoutExporter.Success: QgsMessageLog.logMessage("atlasprint: export not generated %s" % export_path, 'atlasprint', Qgis.Info) return None if not os.path.isfile(export_path): QgsMessageLog.logMessage("atlasprint: export not generated %s" % export_path, 'atlasprint', Qgis.Info) return None QgsMessageLog.logMessage("atlasprint: path generated %s" % export_path, 'atlasprint', Qgis.Info) return export_path
def testBearingFormat(self): """ test bearing formatter """ f = QgsBearingNumericFormat() f.setDirectionFormat( QgsBearingNumericFormat.UseRange0To180WithEWDirectionalSuffix) context = QgsNumericFormatContext() self.assertEqual(f.formatDouble(0, context), '0°') self.assertEqual(f.formatDouble(90, context), '90°E') self.assertEqual(f.formatDouble(180, context), '180°') self.assertEqual(f.formatDouble(270, context), '90°W') self.assertEqual(f.formatDouble(300, context), '60°W') self.assertEqual(f.formatDouble(5, context), '5°E') self.assertEqual(f.formatDouble(5.5, context), '5.5°E') self.assertEqual(f.formatDouble(-5, context), '5°W') self.assertEqual(f.formatDouble(-5.5, context), '5.5°W') context.setDecimalSeparator('x') self.assertEqual(f.formatDouble(0, context), '0°') self.assertEqual(f.formatDouble(-5.5, context), '5x5°W') self.assertEqual(f.formatDouble(180, context), '180°') context.setDecimalSeparator('.') f.setNumberDecimalPlaces(0) self.assertEqual(f.formatDouble(0, context), '0°') self.assertEqual(f.formatDouble(5.5, context), '6°E') self.assertEqual(f.formatDouble(-5.5, context), '6°W') self.assertEqual(f.formatDouble(180, context), '180°') f.setNumberDecimalPlaces(3) self.assertEqual(f.formatDouble(0, context), '0°') self.assertEqual(f.formatDouble(5.5, context), '5.5°E') self.assertEqual(f.formatDouble(-5.5, context), '5.5°W') self.assertEqual(f.formatDouble(180, context), '180°') f.setShowTrailingZeros(True) self.assertEqual(f.formatDouble(0, context), '0.000°E') # todo - fix and avoid E self.assertEqual(f.formatDouble(5, context), '5.000°E') self.assertEqual(f.formatDouble(-5, context), '5.000°W') self.assertEqual(f.formatDouble(5.5, context), '5.500°E') self.assertEqual(f.formatDouble(-5.5, context), '5.500°W') self.assertEqual(f.formatDouble(180, context), '180.000°E') # todo fix and avoid E f = QgsBearingNumericFormat() f.setDirectionFormat( QgsBearingNumericFormat.UseRangeNegative180ToPositive180) self.assertEqual(f.formatDouble(0, context), '0°') self.assertEqual(f.formatDouble(90, context), '90°') self.assertEqual(f.formatDouble(180, context), '180°') self.assertEqual(f.formatDouble(270, context), '-90°') self.assertEqual(f.formatDouble(5, context), '5°') self.assertEqual(f.formatDouble(5.5, context), '5.5°') self.assertEqual(f.formatDouble(-5, context), '-5°') self.assertEqual(f.formatDouble(-5.5, context), '-5.5°') context.setDecimalSeparator('x') self.assertEqual(f.formatDouble(0, context), '0°') self.assertEqual(f.formatDouble(-5.5, context), '-5x5°') self.assertEqual(f.formatDouble(180, context), '180°') context.setDecimalSeparator('.') f.setNumberDecimalPlaces(0) self.assertEqual(f.formatDouble(0, context), '0°') self.assertEqual(f.formatDouble(5.5, context), '6°') self.assertEqual(f.formatDouble(-5.5, context), '-6°') self.assertEqual(f.formatDouble(180, context), '180°') f.setNumberDecimalPlaces(3) self.assertEqual(f.formatDouble(0, context), '0°') self.assertEqual(f.formatDouble(5.5, context), '5.5°') self.assertEqual(f.formatDouble(-5.5, context), '-5.5°') self.assertEqual(f.formatDouble(180, context), '180°') f.setShowTrailingZeros(True) self.assertEqual(f.formatDouble(0, context), '0.000°') self.assertEqual(f.formatDouble(5, context), '5.000°') self.assertEqual(f.formatDouble(-5, context), '-5.000°') self.assertEqual(f.formatDouble(5.5, context), '5.500°') self.assertEqual(f.formatDouble(-5.5, context), '-5.500°') self.assertEqual(f.formatDouble(180, context), '180.000°') f = QgsBearingNumericFormat() f.setDirectionFormat(QgsBearingNumericFormat.UseRange0To360) self.assertEqual(f.formatDouble(0, context), '0°') self.assertEqual(f.formatDouble(90, context), '90°') self.assertEqual(f.formatDouble(180, context), '180°') self.assertEqual(f.formatDouble(270, context), '270°') self.assertEqual(f.formatDouble(5, context), '5°') self.assertEqual(f.formatDouble(5.5, context), '5.5°') self.assertEqual(f.formatDouble(-5, context), '355°') self.assertEqual(f.formatDouble(-5.5, context), '354.5°') context.setDecimalSeparator('x') self.assertEqual(f.formatDouble(0, context), '0°') self.assertEqual(f.formatDouble(-5.5, context), '354x5°') self.assertEqual(f.formatDouble(180, context), '180°') context.setDecimalSeparator('.') f.setNumberDecimalPlaces(0) self.assertEqual(f.formatDouble(0, context), '0°') self.assertEqual(f.formatDouble(5.5, context), '6°') self.assertEqual(f.formatDouble(-5.4, context), '355°') self.assertEqual(f.formatDouble(180, context), '180°') f.setNumberDecimalPlaces(3) self.assertEqual(f.formatDouble(0, context), '0°') self.assertEqual(f.formatDouble(5.5, context), '5.5°') self.assertEqual(f.formatDouble(-5.5, context), '354.5°') self.assertEqual(f.formatDouble(180, context), '180°') f.setShowTrailingZeros(True) self.assertEqual(f.formatDouble(0, context), '0.000°') self.assertEqual(f.formatDouble(5, context), '5.000°') self.assertEqual(f.formatDouble(-5, context), '355.000°') self.assertEqual(f.formatDouble(5.5, context), '5.500°') self.assertEqual(f.formatDouble(-5.5, context), '354.500°') self.assertEqual(f.formatDouble(180, context), '180.000°') f2 = f.clone() self.assertIsInstance(f2, QgsBearingNumericFormat) self.assertEqual(f2.showTrailingZeros(), f.showTrailingZeros()) self.assertEqual(f2.showPlusSign(), f.showPlusSign()) self.assertEqual(f2.numberDecimalPlaces(), f.numberDecimalPlaces()) self.assertEqual(f2.showThousandsSeparator(), f.showThousandsSeparator()) self.assertEqual(f2.directionFormat(), f.directionFormat()) doc = QDomDocument("testdoc") elem = doc.createElement("test") f2.writeXml(elem, doc, QgsReadWriteContext()) f3 = QgsNumericFormatRegistry().createFromXml(elem, QgsReadWriteContext()) self.assertIsInstance(f3, QgsBearingNumericFormat) self.assertEqual(f3.showTrailingZeros(), f.showTrailingZeros()) self.assertEqual(f3.showPlusSign(), f.showPlusSign()) self.assertEqual(f3.numberDecimalPlaces(), f.numberDecimalPlaces()) self.assertEqual(f3.showThousandsSeparator(), f.showThousandsSeparator()) self.assertEqual(f3.directionFormat(), f.directionFormat())
def do_aeag_menu(self, fileName, who, menu=None, visible=None, expanded=None): self.canvas.freeze(True) self.canvas.setRenderFlag(False) group = None theLayer = None groupName = None QgsApplication.setOverrideCursor(Qt.WaitCursor) try: if (type(menu.parentWidget()) == QMenu or type(menu.parentWidget()) == QWidget) and self.optionCreateGroup: groupName = menu.title().replace("&", "") group = QgsProject.instance().layerTreeRoot().findGroup( groupName) if group is None: group = QgsProject.instance().layerTreeRoot().addGroup( groupName) # load all layers if fileName is None and who is None and self.optionLoadAll: for action in menu.actions(): if ((action.text() != self.tr("&Load all")) and (action.text() != "Load all")): action.trigger() else: # read QGis project doc = QtXml.QDomDocument() xml = QFile(fileName) if xml.open(QIODevice.ReadOnly | QIODevice.Text): doc.setContent(xml) # is project in relative path ? absolute = self.isAbsolute(doc) node = getFirstChildByTagNameValue(doc.documentElement(), "maplayer", "id", who) if node: idNode = node.namedItem("id") layerType = node.toElement().attribute("type", "vector") # give it a new id (for multiple import) import re newLayerId = "L%s" % re.sub("[{}-]", "", QUuid.createUuid().toString()) try: idNode.firstChild().toText().setData(newLayerId) except: pass # if relative path, adapt datasource if not absolute: try: datasourceNode = node.namedItem("datasource") ds = datasourceNode.firstChild().toText().data() providerNode = node.namedItem("provider") provider = providerNode.firstChild().toText().data( ) if provider == "ogr" and (ds.find(".") == 0): projectpath = QFileInfo( os.path.realpath(fileName)).path() newlayerpath = projectpath + "/" + ds datasourceNode.firstChild().toText().setData( newlayerpath) except: pass # read modified layer node if self.optionCreateGroup and group is not None: """# sol 1 bug : layer incomplete # because of API strange behaviour, we clone the layer... theLayer = QgsProject.instance().mapLayer(newLayerId) cloneLayer = theLayer.clone() # removing the first QgsProject.instance().removeMapLayer(newLayerId) # adding the clone... treeNode = group.addLayer(cloneLayer) treeNode.setExpanded(expanded) treeNode.setItemVisibilityChecked(visible)""" # solution 2, ok ! if layerType == "raster": theLayer = QgsRasterLayer() else: theLayer = QgsVectorLayer() theLayer.readLayerXml(node.toElement(), QgsReadWriteContext()) # needed QgsProject.instance().addMapLayer(theLayer, False) # add to group treeNode = group.addLayer(theLayer) treeNode.setExpanded(expanded) treeNode.setItemVisibilityChecked(visible) else: # create layer QgsProject.instance().readLayer(node) except Exception as e: QgsMessageLog.logMessage( 'Menu from layer: Invalid ' + (fileName if fileName is not None else ""), 'Extensions') for m in e.args: QgsMessageLog.logMessage(m, 'Extensions') self.canvas.freeze(False) self.canvas.setRenderFlag(True) self.canvas.refresh() QgsApplication.restoreOverrideCursor()
def testScientificFormat(self): """ test scientific formatter """ f = QgsScientificNumericFormat() context = QgsNumericFormatContext() self.assertEqual(f.formatDouble(0, context), '0e+00') self.assertEqual(f.formatDouble(5, context), '5e+00') self.assertEqual(f.formatDouble(5.5, context), '5.5e+00') self.assertEqual(f.formatDouble(-5, context), '-5e+00') self.assertEqual(f.formatDouble(-5.5, context), '-5.5e+00') self.assertEqual(f.formatDouble(-55555555.5, context), '-5.555556e+07') context.setDecimalSeparator('x') self.assertEqual(f.formatDouble(0, context), '0e+00') self.assertEqual(f.formatDouble(-5.5, context), '-5x5e+00') self.assertEqual(f.formatDouble(-55555555.5, context), '-5x555556e+07') context.setDecimalSeparator('.') # places must be at least 1 for scientific notation! f.setNumberDecimalPlaces(0) self.assertEqual(f.numberDecimalPlaces(), 1) self.assertEqual(f.formatDouble(0, context), '0e+00') self.assertEqual(f.formatDouble(5.5, context), '5.5e+00') self.assertEqual(f.formatDouble(55555555.5, context), '5.6e+07') self.assertEqual(f.formatDouble(55555555.123456, context), '5.6e+07') self.assertEqual(f.formatDouble(-5.5, context), '-5.5e+00') self.assertEqual(f.formatDouble(-55555555.5, context), '-5.6e+07') f.setNumberDecimalPlaces(3) self.assertEqual(f.formatDouble(0, context), '0e+00') self.assertEqual(f.formatDouble(5.5, context), '5.5e+00') self.assertEqual(f.formatDouble(55555555.5, context), '5.556e+07') self.assertEqual(f.formatDouble(55555555.123456, context), '5.556e+07') self.assertEqual(f.formatDouble(-5.5, context), '-5.5e+00') self.assertEqual(f.formatDouble(-55555555.5, context), '-5.556e+07') f.setShowTrailingZeros(True) self.assertEqual(f.formatDouble(0, context), '0.000e+00') self.assertEqual(f.formatDouble(5, context), '5.000e+00') self.assertEqual(f.formatDouble(-5, context), '-5.000e+00') self.assertEqual(f.formatDouble(5.5, context), '5.500e+00') self.assertEqual(f.formatDouble(55555555.5, context), '5.556e+07') self.assertEqual(f.formatDouble(55555555.123456, context), '5.556e+07') self.assertEqual(f.formatDouble(-5.5, context), '-5.500e+00') self.assertEqual(f.formatDouble(-55555555.5, context), '-5.556e+07') f.setShowPlusSign(True) self.assertEqual(f.formatDouble(0, context), '0.000e+00') self.assertEqual(f.formatDouble(5, context), '+5.000e+00') self.assertEqual(f.formatDouble(-5, context), '-5.000e+00') self.assertEqual(f.formatDouble(5.5, context), '+5.500e+00') self.assertEqual(f.formatDouble(55555555.5, context), '+5.556e+07') self.assertEqual(f.formatDouble(55555555.123456, context), '+5.556e+07') self.assertEqual(f.formatDouble(-5.5, context), '-5.500e+00') self.assertEqual(f.formatDouble(-55555555.5, context), '-5.556e+07') f2 = f.clone() self.assertIsInstance(f2, QgsScientificNumericFormat) self.assertEqual(f2.showTrailingZeros(), f.showTrailingZeros()) self.assertEqual(f2.showPlusSign(), f.showPlusSign()) self.assertEqual(f2.numberDecimalPlaces(), f.numberDecimalPlaces()) self.assertEqual(f2.showThousandsSeparator(), f.showThousandsSeparator()) doc = QDomDocument("testdoc") elem = doc.createElement("test") f2.writeXml(elem, doc, QgsReadWriteContext()) f3 = QgsNumericFormatRegistry().createFromXml(elem, QgsReadWriteContext()) self.assertIsInstance(f3, QgsScientificNumericFormat) self.assertEqual(f3.showTrailingZeros(), f.showTrailingZeros()) self.assertEqual(f3.showPlusSign(), f.showPlusSign()) self.assertEqual(f3.numberDecimalPlaces(), f.numberDecimalPlaces()) self.assertEqual(f3.showThousandsSeparator(), f.showThousandsSeparator())
def testBasic(self): renderer = QgsPointCloudRgbRenderer() renderer.setBlueAttribute('b') self.assertEqual(renderer.blueAttribute(), 'b') renderer.setGreenAttribute('g') self.assertEqual(renderer.greenAttribute(), 'g') renderer.setRedAttribute('r') self.assertEqual(renderer.redAttribute(), 'r') redce = QgsContrastEnhancement() redce.setMinimumValue(100) redce.setMaximumValue(120) redce.setContrastEnhancementAlgorithm(QgsContrastEnhancement.StretchAndClipToMinimumMaximum) renderer.setRedContrastEnhancement(redce) greence = QgsContrastEnhancement() greence.setMinimumValue(130) greence.setMaximumValue(150) greence.setContrastEnhancementAlgorithm(QgsContrastEnhancement.StretchToMinimumMaximum) renderer.setGreenContrastEnhancement(greence) bluece = QgsContrastEnhancement() bluece.setMinimumValue(170) bluece.setMaximumValue(190) bluece.setContrastEnhancementAlgorithm(QgsContrastEnhancement.ClipToMinimumMaximum) renderer.setBlueContrastEnhancement(bluece) renderer.setMaximumScreenError(18) renderer.setMaximumScreenErrorUnit(QgsUnitTypes.RenderInches) renderer.setPointSize(13) renderer.setPointSizeUnit(QgsUnitTypes.RenderPoints) renderer.setPointSizeMapUnitScale(QgsMapUnitScale(1000, 2000)) rr = renderer.clone() self.assertEqual(rr.maximumScreenError(), 18) self.assertEqual(rr.maximumScreenErrorUnit(), QgsUnitTypes.RenderInches) self.assertEqual(rr.pointSize(), 13) self.assertEqual(rr.pointSizeUnit(), QgsUnitTypes.RenderPoints) self.assertEqual(rr.pointSizeMapUnitScale().minScale, 1000) self.assertEqual(rr.pointSizeMapUnitScale().maxScale, 2000) self.assertEqual(rr.blueAttribute(), 'b') self.assertEqual(rr.greenAttribute(), 'g') self.assertEqual(rr.redAttribute(), 'r') self.assertEqual(rr.redContrastEnhancement().minimumValue(), 100) self.assertEqual(rr.redContrastEnhancement().maximumValue(), 120) self.assertEqual(rr.redContrastEnhancement().contrastEnhancementAlgorithm(), QgsContrastEnhancement.StretchAndClipToMinimumMaximum) self.assertEqual(rr.greenContrastEnhancement().minimumValue(), 130) self.assertEqual(rr.greenContrastEnhancement().maximumValue(), 150) self.assertEqual(rr.greenContrastEnhancement().contrastEnhancementAlgorithm(), QgsContrastEnhancement.StretchToMinimumMaximum) self.assertEqual(rr.blueContrastEnhancement().minimumValue(), 170) self.assertEqual(rr.blueContrastEnhancement().maximumValue(), 190) self.assertEqual(rr.blueContrastEnhancement().contrastEnhancementAlgorithm(), QgsContrastEnhancement.ClipToMinimumMaximum) doc = QDomDocument("testdoc") elem = renderer.save(doc, QgsReadWriteContext()) r2 = QgsPointCloudRgbRenderer.create(elem, QgsReadWriteContext()) self.assertEqual(r2.maximumScreenError(), 18) self.assertEqual(r2.maximumScreenErrorUnit(), QgsUnitTypes.RenderInches) self.assertEqual(r2.pointSize(), 13) self.assertEqual(r2.pointSizeUnit(), QgsUnitTypes.RenderPoints) self.assertEqual(r2.pointSizeMapUnitScale().minScale, 1000) self.assertEqual(r2.pointSizeMapUnitScale().maxScale, 2000) self.assertEqual(r2.blueAttribute(), 'b') self.assertEqual(r2.greenAttribute(), 'g') self.assertEqual(r2.redAttribute(), 'r') self.assertEqual(r2.redContrastEnhancement().minimumValue(), 100) self.assertEqual(r2.redContrastEnhancement().maximumValue(), 120) self.assertEqual(r2.redContrastEnhancement().contrastEnhancementAlgorithm(), QgsContrastEnhancement.StretchAndClipToMinimumMaximum) self.assertEqual(r2.greenContrastEnhancement().minimumValue(), 130) self.assertEqual(r2.greenContrastEnhancement().maximumValue(), 150) self.assertEqual(r2.greenContrastEnhancement().contrastEnhancementAlgorithm(), QgsContrastEnhancement.StretchToMinimumMaximum) self.assertEqual(r2.blueContrastEnhancement().minimumValue(), 170) self.assertEqual(r2.blueContrastEnhancement().maximumValue(), 190) self.assertEqual(r2.blueContrastEnhancement().contrastEnhancementAlgorithm(), QgsContrastEnhancement.ClipToMinimumMaximum)
def testFractionFormat(self): """ test fraction formatter """ f = QgsFractionNumericFormat() f.setUseUnicodeSuperSubscript(False) context = QgsNumericFormatContext() self.assertEqual(f.formatDouble(0, context), '0') self.assertEqual(f.formatDouble(5, context), '5') self.assertEqual(f.formatDouble(5.5, context), '5 1/2') self.assertEqual(f.formatDouble(-5, context), '-5') self.assertEqual(f.formatDouble(-5.5, context), '-5 1/2') self.assertEqual(f.formatDouble(-55555555.5, context), '-55,555,555 1/2') context.setThousandsSeparator('⚡') self.assertEqual(f.formatDouble(-55555555.5, context), '-55⚡555⚡555 1/2') f.setShowThousandsSeparator(False) self.assertEqual(f.formatDouble(-55555555.5, context), '-55555555 1/2') f.setShowPlusSign(True) self.assertEqual(f.formatDouble(0, context), '0') self.assertEqual(f.formatDouble(5, context), '+5') self.assertEqual(f.formatDouble(-5, context), '-5') self.assertEqual(f.formatDouble(5.5, context), '+5 1/2') self.assertEqual(f.formatDouble(-5.5, context), '-5 1/2') self.assertEqual(f.formatDouble(55555555.5, context), '+55555555 1/2') self.assertEqual(f.formatDouble(55555555.123456, context), '+55555555 5797/46956') self.assertEqual(f.formatDouble(-5.5, context), '-5 1/2') self.assertEqual(f.formatDouble(-55555555.5, context), '-55555555 1/2') context.setPositiveSign('w') self.assertEqual(f.formatDouble(5, context), 'w5') self.assertEqual(f.formatDouble(-5, context), '-5') self.assertEqual(f.formatDouble(5.5, context), 'w5 1/2') f.setShowPlusSign(False) f.setUseDedicatedUnicodeCharacters(True) self.assertEqual(f.formatDouble(0, context), '0') self.assertEqual(f.formatDouble(5, context), '5') self.assertEqual(f.formatDouble(5.5, context), '5 ½') self.assertEqual(f.formatDouble(-5, context), '-5') self.assertEqual(f.formatDouble(-5.5, context), '-5 ½') self.assertEqual( f.formatDouble(5.333333333333333333333333333, context), '5 ⅓') self.assertEqual( f.formatDouble(5.666666666666666666666666666, context), '5 ⅔') self.assertEqual(f.formatDouble(5.25, context), '5 ¼') self.assertEqual(f.formatDouble(5.75, context), '5 ¾') self.assertEqual(f.formatDouble(5.2, context), '5 ⅕') self.assertEqual(f.formatDouble(5.4, context), '5 ⅖') self.assertEqual(f.formatDouble(5.6, context), '5 ⅗') self.assertEqual(f.formatDouble(5.8, context), '5 ⅘') self.assertEqual( f.formatDouble(5.1666666666666666666666666666666666, context), '5 ⅙') self.assertEqual( f.formatDouble(5.8333333333333333333333333333333333, context), '5 ⅚') self.assertEqual(f.formatDouble(5.14285714285714285, context), '5 ⅐') self.assertEqual(f.formatDouble(5.125, context), '5 ⅛') self.assertEqual(f.formatDouble(5.375, context), '5 ⅜') self.assertEqual(f.formatDouble(5.625, context), '5 ⅝') self.assertEqual(f.formatDouble(5.875, context), '5 ⅞') self.assertEqual(f.formatDouble(5.1111111111111111, context), '5 ⅑') self.assertEqual(f.formatDouble(5.1, context), '5 ⅒') self.assertEqual(f.formatDouble(5.13131313133, context), '5 13/99') f.setUseUnicodeSuperSubscript(True) self.assertEqual(f.formatDouble(0, context), '0') self.assertEqual(f.formatDouble(5, context), '5') self.assertEqual(f.formatDouble(5.5, context), '5 ½') self.assertEqual(f.formatDouble(-5, context), '-5') self.assertEqual(f.formatDouble(-5.5, context), '-5 ½') self.assertEqual(f.formatDouble(5.55555555, context), '5 ¹¹¹¹¹¹¹¹/₂₀₀₀₀₀₀₀') self.assertEqual(f.formatDouble(-5.55555555, context), '-5 ¹¹¹¹¹¹¹¹/₂₀₀₀₀₀₀₀') self.assertEqual(f.formatDouble(0.555, context), '¹¹¹/₂₀₀') f.setShowPlusSign(True) f.setUseUnicodeSuperSubscript(False) f2 = f.clone() self.assertIsInstance(f2, QgsFractionNumericFormat) self.assertEqual(f2.showPlusSign(), f.showPlusSign()) self.assertEqual(f2.showThousandsSeparator(), f.showThousandsSeparator()) self.assertEqual(f2.thousandsSeparator(), f.thousandsSeparator()) self.assertEqual(f2.useDedicatedUnicodeCharacters(), f.useDedicatedUnicodeCharacters()) self.assertEqual(f2.useUnicodeSuperSubscript(), f.useUnicodeSuperSubscript()) doc = QDomDocument("testdoc") elem = doc.createElement("test") f2.writeXml(elem, doc, QgsReadWriteContext()) f3 = QgsNumericFormatRegistry().createFromXml(elem, QgsReadWriteContext()) self.assertIsInstance(f3, QgsFractionNumericFormat) self.assertEqual(f3.showPlusSign(), f.showPlusSign()) self.assertEqual(f3.showThousandsSeparator(), f.showThousandsSeparator()) self.assertEqual(f3.thousandsSeparator(), f.thousandsSeparator()) self.assertEqual(f3.useDedicatedUnicodeCharacters(), f.useDedicatedUnicodeCharacters()) self.assertEqual(f3.useUnicodeSuperSubscript(), f.useUnicodeSuperSubscript())
def parse_xml(self): """Parse the xml file. Returns false if there is failure.""" xml_file = QFile(self._xml_path) if not xml_file.open(QIODevice.ReadOnly): return False document = QDomDocument() if not document.setContent(xml_file): return False xml_file.close() document_element = document.documentElement() if document_element.tagName() != "qgis_style": return False # Get all the symbols self._symbols = [] symbols_element = document_element.firstChildElement("symbols") symbol_element = symbols_element.firstChildElement() context = QgsReadWriteContext() context.setPathResolver(QgsProject.instance().pathResolver()) while not symbol_element.isNull(): if symbol_element.tagName() == "symbol": symbol = QgsSymbolLayerUtils.loadSymbol( symbol_element, context) if symbol: self._symbols.append({ "name": symbol_element.attribute("name"), "symbol": symbol }) symbol_element = symbol_element.nextSiblingElement() # Get all the colorramps self._colorramps = [] ramps_element = document_element.firstChildElement("colorramps") ramp_element = ramps_element.firstChildElement() while not ramp_element.isNull(): if ramp_element.tagName() == "colorramp": colorramp = QgsSymbolLayerUtils.loadColorRamp(ramp_element) if colorramp: self._colorramps.append({ "name": ramp_element.attribute("name"), "colorramp": colorramp }) ramp_element = ramp_element.nextSiblingElement() # Get all the TextFormats - textformats - textformat self._textformats = [] textformats_element = document_element.firstChildElement("textformats") textformat_element = textformats_element.firstChildElement() while not textformat_element.isNull(): if textformat_element.tagName() == "textformat": textformat = QgsTextFormat() textformat.readXml(textformat_element, QgsReadWriteContext()) if textformat: self._textformats.append({ "name": textformat_element.attribute("name"), "textformat": textformat, }) textformat_element = textformat_element.nextSiblingElement() # Get all the LabelSettings - labelsettings - labelsetting - # QgsPalLayerSettings.readXML? self._labelsettings = [] labels_element = document_element.firstChildElement("labelsettings") label_element = labels_element.firstChildElement() while not label_element.isNull(): if label_element.tagName() == "labelsetting": labelsettings = QgsPalLayerSettings() labelsettings.readXml(label_element, QgsReadWriteContext()) if labelsettings: self._labelsettings.append({ "name": label_element.attribute("name"), "labelsettings": labelsettings, }) label_element = label_element.nextSiblingElement() return True
def testBlockingItems(self): """ Test rendering map item with blocking items """ format = QgsTextFormat() format.setFont(QgsFontUtils.getStandardTestFont("Bold")) format.setSize(20) format.setNamedStyle("Bold") format.setColor(QColor(0, 0, 0)) settings = QgsPalLayerSettings() settings.setFormat(format) settings.fieldName = "'X'" settings.isExpression = True settings.placement = QgsPalLayerSettings.OverPoint vl = QgsVectorLayer("Point?crs=epsg:4326&field=id:integer", "vl", "memory") vl.setRenderer(QgsNullSymbolRenderer()) f = QgsFeature(vl.fields(), 1) for x in range(15): for y in range(15): f.setGeometry(QgsPoint(x, y)) vl.dataProvider().addFeature(f) vl.setLabeling(QgsVectorLayerSimpleLabeling(settings)) vl.setLabelsEnabled(True) p = QgsProject() engine_settings = QgsLabelingEngineSettings() engine_settings.setFlag(QgsLabelingEngineSettings.DrawLabelRectOnly, True) p.setLabelingEngineSettings(engine_settings) p.addMapLayer(vl) layout = QgsLayout(p) layout.initializeDefaults() p.setCrs(QgsCoordinateReferenceSystem('EPSG:4326')) map = QgsLayoutItemMap(layout) map.attemptSetSceneRect(QRectF(10, 10, 180, 180)) map.setFrameEnabled(True) map.zoomToExtent(vl.extent()) map.setLayers([vl]) map.setId('map') layout.addLayoutItem(map) map2 = QgsLayoutItemMap(layout) map2.attemptSetSceneRect(QRectF(0, 5, 50, 80)) map2.setFrameEnabled(True) map2.setBackgroundEnabled(False) map2.setId('map2') layout.addLayoutItem(map2) map3 = QgsLayoutItemMap(layout) map3.attemptSetSceneRect(QRectF(150, 160, 50, 50)) map3.setFrameEnabled(True) map3.setBackgroundEnabled(False) map3.setId('map3') layout.addLayoutItem(map3) map.addLabelBlockingItem(map2) map.addLabelBlockingItem(map3) map.setMapFlags(QgsLayoutItemMap.MapItemFlags()) checker = QgsLayoutChecker('composermap_label_blockers', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) doc = QDomDocument("testdoc") elem = layout.writeXml(doc, QgsReadWriteContext()) l2 = QgsLayout(p) self.assertTrue(l2.readXml(elem, doc, QgsReadWriteContext())) map_restore = [i for i in l2.items() if isinstance(i, QgsLayoutItemMap) and i.id() == 'map'][0] map2_restore = [i for i in l2.items() if isinstance(i, QgsLayoutItemMap) and i.id() == 'map2'][0] map3_restore = [i for i in l2.items() if isinstance(i, QgsLayoutItemMap) and i.id() == 'map3'][0] self.assertTrue(map_restore.isLabelBlockingItem(map2_restore)) self.assertTrue(map_restore.isLabelBlockingItem(map3_restore))
def testBasicFormat(self): """ test basic formatter """ f = QgsBasicNumericFormat() context = QgsNumericFormatContext() self.assertEqual(f.formatDouble(0, context), '0') self.assertEqual(f.formatDouble(5, context), '5') self.assertEqual(f.formatDouble(5.5, context), '5.5') self.assertEqual(f.formatDouble(-5, context), '-5') self.assertEqual(f.formatDouble(-5.5, context), '-5.5') self.assertEqual(f.formatDouble(-55555555.5, context), '-55,555,555.5') context.setDecimalSeparator('x') self.assertEqual(f.formatDouble(0, context), '0') self.assertEqual(f.formatDouble(-5.5, context), '-5x5') self.assertEqual(f.formatDouble(-55555555.5, context), '-55,555,555x5') context.setThousandsSeparator('y') self.assertEqual(f.formatDouble(-5.5, context), '-5x5') self.assertEqual(f.formatDouble(-55555555.5, context), '-55y555y555x5') f.setShowThousandsSeparator(False) self.assertEqual(f.formatDouble(-5.5, context), '-5x5') self.assertEqual(f.formatDouble(-55555555.5, context), '-55555555x5') context.setDecimalSeparator('.') f.setNumberDecimalPlaces(0) self.assertEqual(f.formatDouble(0, context), '0') self.assertEqual(f.formatDouble(5.5, context), '6') self.assertEqual(f.formatDouble(55555555.5, context), '55555556') self.assertEqual(f.formatDouble(55555555.123456, context), '55555555') self.assertEqual(f.formatDouble(-5.5, context), '-6') self.assertEqual(f.formatDouble(-55555555.5, context), '-55555556') f.setNumberDecimalPlaces(3) self.assertEqual(f.formatDouble(0, context), '0') self.assertEqual(f.formatDouble(5.5, context), '5.5') self.assertEqual(f.formatDouble(55555555.5, context), '55555555.5') self.assertEqual(f.formatDouble(55555555.123456, context), '55555555.123') self.assertEqual(f.formatDouble(-5.5, context), '-5.5') self.assertEqual(f.formatDouble(-55555555.5, context), '-55555555.5') f.setShowTrailingZeros(True) self.assertEqual(f.formatDouble(0, context), '0.000') self.assertEqual(f.formatDouble(5, context), '5.000') self.assertEqual(f.formatDouble(-5, context), '-5.000') self.assertEqual(f.formatDouble(5.5, context), '5.500') self.assertEqual(f.formatDouble(55555555.5, context), '55555555.500') self.assertEqual(f.formatDouble(55555555.123456, context), '55555555.123') self.assertEqual(f.formatDouble(-5.5, context), '-5.500') self.assertEqual(f.formatDouble(-55555555.5, context), '-55555555.500') f.setShowPlusSign(True) self.assertEqual(f.formatDouble(0, context), '0.000') self.assertEqual(f.formatDouble(5, context), '+5.000') self.assertEqual(f.formatDouble(-5, context), '-5.000') self.assertEqual(f.formatDouble(5.5, context), '+5.500') self.assertEqual(f.formatDouble(55555555.5, context), '+55555555.500') self.assertEqual(f.formatDouble(55555555.123456, context), '+55555555.123') self.assertEqual(f.formatDouble(-5.5, context), '-5.500') self.assertEqual(f.formatDouble(-55555555.5, context), '-55555555.500') context.setPositiveSign('w') self.assertEqual(f.formatDouble(5, context), 'w5.000') self.assertEqual(f.formatDouble(-5, context), '-5.000') self.assertEqual(f.formatDouble(5.5, context), 'w5.500') f2 = f.clone() self.assertIsInstance(f2, QgsBasicNumericFormat) self.assertEqual(f2.showTrailingZeros(), f.showTrailingZeros()) self.assertEqual(f2.showPlusSign(), f.showPlusSign()) self.assertEqual(f2.numberDecimalPlaces(), f.numberDecimalPlaces()) self.assertEqual(f2.showThousandsSeparator(), f.showThousandsSeparator()) doc = QDomDocument("testdoc") elem = doc.createElement("test") f2.writeXml(elem, doc, QgsReadWriteContext()) f3 = QgsNumericFormatRegistry().createFromXml(elem, QgsReadWriteContext()) self.assertIsInstance(f3, QgsBasicNumericFormat) self.assertEqual(f3.showTrailingZeros(), f.showTrailingZeros()) self.assertEqual(f3.showPlusSign(), f.showPlusSign()) self.assertEqual(f3.numberDecimalPlaces(), f.numberDecimalPlaces()) self.assertEqual(f3.showThousandsSeparator(), f.showThousandsSeparator())
def testEnterCategory(self): context = QgsReadWriteContext() context.pushMessage('msg0', Qgis.Critical) with QgsReadWriteContext.enterCategory(context, 'cat1'): context.pushMessage('msg1', Qgis.Warning) with QgsReadWriteContext.enterCategory(context, 'cat2', "detail2"): context.pushMessage('msg2') context.pushMessage('msg3') context.pushMessage('msg4') messages = context.takeMessages() self.assertEqual(messages[0].message(), 'msg0') self.assertEqual(messages[0].level(), Qgis.Critical) self.assertEqual(messages[0].categories(), []) self.assertEqual(messages[1].message(), 'msg1') self.assertEqual(messages[1].level(), Qgis.Warning) self.assertEqual(messages[1].categories(), ['cat1']) self.assertEqual(messages[2].message(), 'msg2') self.assertEqual(messages[2].categories(), ['cat1', 'cat2 :: detail2']) self.assertEqual(messages[3].message(), 'msg3') self.assertEqual(messages[3].categories(), ['cat1']) self.assertEqual(messages[4].message(), 'msg4') self.assertEqual(messages[4].categories(), [])
def test_read_write_project_with_layout(self): """ Test saving/restoring dialog state of layout plot in project """ # print('read write project with layout test') # create project and layout project = QgsProject.instance() layout = QgsPrintLayout(project) layout_name = "PrintLayoutReadWrite" layout.initializeDefaults() layout.setName(layout_name) layout_plot = PlotLayoutItem(layout) layout_plot.setId('plot_item') plot_item_id = layout_plot.id() self.assertEqual(len(layout_plot.plot_settings), 1) # self.assertEqual(len(layout.items()), 0) layout.addLayoutItem(layout_plot) # self.assertEqual(len(layout.items()), 1) plot_dialog = PlotLayoutItemWidget(None, layout_plot) # add second plot plot_dialog.add_plot() self.assertEqual(len(layout_plot.plot_settings), 2) # edit first plot plot_dialog.setDockMode(True) plot_dialog.show_properties() plot_property_panel = plot_dialog.panel plot_property_panel.set_plot_type('violin') self.assertEqual(plot_property_panel.ptype, 'violin') plot_property_panel.acceptPanel() plot_property_panel.destroy() # edit second plot plot_dialog.plot_list.setCurrentRow(1) plot_dialog.show_properties() plot_property_panel = plot_dialog.panel plot_property_panel.set_plot_type('bar') self.assertEqual(plot_property_panel.ptype, 'bar') plot_property_panel.acceptPanel() plot_property_panel.destroy() # write xml xml_doc = QDomDocument('layout') element = layout.writeXml(xml_doc, QgsReadWriteContext()) layout_plot.remove_plot(0) self.assertEqual(len(layout_plot.plot_settings), 1) self.assertEqual(layout_plot.plot_settings[0].plot_type, 'bar') layout_plot.remove_plot(0) self.assertEqual(len(layout_plot.plot_settings), 0) # read xml layout2 = QgsPrintLayout(project) self.assertTrue(layout2.readXml(element, xml_doc, QgsReadWriteContext())) layout_plot2 = layout2.itemById(plot_item_id) self.assertTrue(layout_plot2) self.assertEqual(len(layout_plot2.plot_settings), 2) self.assertEqual(layout_plot2.plot_settings[0].plot_type, 'violin') self.assertEqual(layout_plot2.plot_settings[1].plot_type, 'bar')
def testSaveLoadTemplate(self): tmpfile = os.path.join(self.basetestpath, 'testTemplate.qpt') p = QgsProject() l = QgsLayout(p) l.initializeDefaults() # add some items item1 = QgsLayoutItemLabel(l) item1.setId('xxyyxx') item1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters)) item1.attemptResize( QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) l.addItem(item1) item2 = QgsLayoutItemLabel(l) item2.setId('zzyyzz') item2.attemptMove( QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters)) item2.attemptResize( QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters)) l.addItem(item2) # multiframe multiframe1 = QgsLayoutItemHtml(l) multiframe1.setHtml('mf1') l.addMultiFrame(multiframe1) frame1 = QgsLayoutFrame(l, multiframe1) frame1.setId('frame1') frame1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters)) frame1.attemptResize( QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) multiframe1.addFrame(frame1) multiframe2 = QgsLayoutItemHtml(l) multiframe2.setHtml('mf2') l.addMultiFrame(multiframe2) frame2 = QgsLayoutFrame(l, multiframe2) frame2.setId('frame2') frame2.attemptMove( QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters)) frame2.attemptResize( QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters)) multiframe2.addFrame(frame2) uuids = { item1.uuid(), item2.uuid(), frame1.uuid(), frame2.uuid(), multiframe1.uuid(), multiframe2.uuid() } original_uuids = { item1.uuid(), item2.uuid(), frame1.uuid(), frame2.uuid() } self.assertTrue(l.saveAsTemplate(tmpfile, QgsReadWriteContext())) l2 = QgsLayout(p) with open(tmpfile) as f: template_content = f.read() doc = QDomDocument() doc.setContent(template_content) # adding to existing items new_items, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), False) self.assertTrue(ok) self.assertEqual(len(new_items), 4) items = l2.items() multiframes = l2.multiFrames() self.assertEqual(len(multiframes), 2) self.assertTrue([i for i in items if i.id() == 'xxyyxx']) self.assertTrue([i for i in items if i.id() == 'zzyyzz']) self.assertTrue([i for i in items if i.id() == 'frame1']) self.assertTrue([i for i in items if i.id() == 'frame2']) self.assertTrue([i for i in multiframes if i.html() == 'mf1']) self.assertTrue([i for i in multiframes if i.html() == 'mf2']) self.assertTrue(new_items[0] in l2.items()) self.assertTrue(new_items[1] in l2.items()) self.assertTrue(new_items[2] in l2.items()) self.assertTrue(new_items[3] in l2.items()) # double check that new items have a unique uid self.assertNotIn(new_items[0].uuid(), uuids) uuids.add(new_items[0].uuid()) self.assertNotIn(new_items[1].uuid(), uuids) uuids.add(new_items[1].uuid()) self.assertNotIn(new_items[2].uuid(), uuids) uuids.add(new_items[2].uuid()) self.assertNotIn(new_items[3].uuid(), uuids) uuids.add(new_items[3].uuid()) self.assertNotIn( multiframes[0].uuid(), [multiframe1.uuid(), multiframe2.uuid()]) self.assertNotIn( multiframes[1].uuid(), [multiframe1.uuid(), multiframe2.uuid()]) new_multiframe1 = [i for i in multiframes if i.html() == 'mf1'][0] self.assertEqual(new_multiframe1.layout(), l2) new_multiframe2 = [i for i in multiframes if i.html() == 'mf2'][0] self.assertEqual(new_multiframe2.layout(), l2) new_frame1 = sip.cast([i for i in items if i.id() == 'frame1'][0], QgsLayoutFrame) new_frame2 = sip.cast([i for i in items if i.id() == 'frame2'][0], QgsLayoutFrame) self.assertEqual(new_frame1.multiFrame(), new_multiframe1) self.assertEqual(new_multiframe1.frames()[0].uuid(), new_frame1.uuid()) self.assertEqual(new_frame2.multiFrame(), new_multiframe2) self.assertEqual(new_multiframe2.frames()[0].uuid(), new_frame2.uuid()) # adding to existing items new_items2, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), False) self.assertTrue(ok) self.assertEqual(len(new_items2), 4) items = l2.items() self.assertEqual(len(items), 8) multiframes2 = l2.multiFrames() self.assertEqual(len(multiframes2), 4) multiframes2 = [ m for m in l2.multiFrames() if not m.uuid() in [new_multiframe1.uuid(), new_multiframe2.uuid()] ] self.assertEqual(len(multiframes2), 2) self.assertTrue([i for i in items if i.id() == 'xxyyxx']) self.assertTrue([i for i in items if i.id() == 'zzyyzz']) self.assertTrue([i for i in items if i.id() == 'frame1']) self.assertTrue([i for i in items if i.id() == 'frame2']) self.assertTrue([i for i in multiframes2 if i.html() == 'mf1']) self.assertTrue([i for i in multiframes2 if i.html() == 'mf2']) self.assertTrue(new_items[0] in l2.items()) self.assertTrue(new_items[1] in l2.items()) self.assertTrue(new_items[2] in l2.items()) self.assertTrue(new_items[3] in l2.items()) self.assertTrue(new_items2[0] in l2.items()) self.assertTrue(new_items2[1] in l2.items()) self.assertTrue(new_items2[2] in l2.items()) self.assertTrue(new_items2[3] in l2.items()) self.assertNotIn(new_items2[0].uuid(), uuids) uuids.add(new_items[0].uuid()) self.assertNotIn(new_items2[1].uuid(), uuids) uuids.add(new_items[1].uuid()) self.assertNotIn(new_items2[2].uuid(), uuids) uuids.add(new_items[2].uuid()) self.assertNotIn(new_items2[3].uuid(), uuids) uuids.add(new_items[3].uuid()) self.assertNotIn(multiframes2[0].uuid(), [ multiframe1.uuid(), multiframe2.uuid(), new_multiframe1.uuid(), new_multiframe2.uuid() ]) self.assertNotIn(multiframes2[1].uuid(), [ multiframe1.uuid(), multiframe2.uuid(), new_multiframe1.uuid(), new_multiframe2.uuid() ]) new_multiframe1b = [i for i in multiframes2 if i.html() == 'mf1'][0] self.assertEqual(new_multiframe1b.layout(), l2) new_multiframe2b = [i for i in multiframes2 if i.html() == 'mf2'][0] self.assertEqual(new_multiframe2b.layout(), l2) new_frame1b = sip.cast([ i for i in items if i.id() == 'frame1' and i.uuid() != new_frame1.uuid() ][0], QgsLayoutFrame) new_frame2b = sip.cast([ i for i in items if i.id() == 'frame2' and i.uuid() != new_frame2.uuid() ][0], QgsLayoutFrame) self.assertEqual(new_frame1b.multiFrame(), new_multiframe1b) self.assertEqual(new_multiframe1b.frames()[0].uuid(), new_frame1b.uuid()) self.assertEqual(new_frame2b.multiFrame(), new_multiframe2b) self.assertEqual(new_multiframe2b.frames()[0].uuid(), new_frame2b.uuid()) # clearing existing items new_items3, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), True) new_multiframes = l2.multiFrames() self.assertTrue(ok) self.assertEqual(len(new_items3), 5) # includes page self.assertEqual(len(new_multiframes), 2) items = l2.items() self.assertTrue([ i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'xxyyxx' ]) self.assertTrue([ i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'zzyyzz' ]) self.assertTrue([ i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'frame1' ]) self.assertTrue([ i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'frame2' ]) self.assertTrue(new_items3[0] in l2.items()) self.assertTrue(new_items3[1] in l2.items()) self.assertTrue(new_items3[2] in l2.items()) self.assertTrue(new_items3[3] in l2.items()) new_multiframe1 = [i for i in new_multiframes if i.html() == 'mf1'][0] new_multiframe2 = [i for i in new_multiframes if i.html() == 'mf2'][0] new_frame1 = sip.cast([ i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'frame1' ][0], QgsLayoutFrame) new_frame2 = sip.cast([ i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'frame2' ][0], QgsLayoutFrame) self.assertEqual(new_frame1.multiFrame(), new_multiframe1) self.assertEqual(new_multiframe1.frames()[0].uuid(), new_frame1.uuid()) self.assertEqual(new_frame2.multiFrame(), new_multiframe2) self.assertEqual(new_multiframe2.frames()[0].uuid(), new_frame2.uuid())
def testBasic(self): renderer = QgsPointCloudAttributeByRampRenderer() renderer.setAttribute('attr') self.assertEqual(renderer.attribute(), 'attr') renderer.setMinimum(5) self.assertEqual(renderer.minimum(), 5) renderer.setMaximum(15) self.assertEqual(renderer.maximum(), 15) ramp = QgsStyle.defaultStyle().colorRamp("Viridis") shader = QgsColorRampShader(20, 30, ramp) renderer.setColorRampShader(shader) self.assertEqual(renderer.colorRampShader().minimumValue(), 20) self.assertEqual(renderer.colorRampShader().maximumValue(), 30) renderer.setMaximumScreenError(18) renderer.setMaximumScreenErrorUnit(QgsUnitTypes.RenderInches) renderer.setPointSize(13) renderer.setPointSizeUnit(QgsUnitTypes.RenderPoints) renderer.setPointSizeMapUnitScale(QgsMapUnitScale(1000, 2000)) rr = renderer.clone() self.assertEqual(rr.maximumScreenError(), 18) self.assertEqual(rr.maximumScreenErrorUnit(), QgsUnitTypes.RenderInches) self.assertEqual(rr.pointSize(), 13) self.assertEqual(rr.pointSizeUnit(), QgsUnitTypes.RenderPoints) self.assertEqual(rr.pointSizeMapUnitScale().minScale, 1000) self.assertEqual(rr.pointSizeMapUnitScale().maxScale, 2000) self.assertEqual(rr.attribute(), 'attr') self.assertEqual(rr.minimum(), 5) self.assertEqual(rr.maximum(), 15) self.assertEqual(rr.colorRampShader().minimumValue(), 20) self.assertEqual(rr.colorRampShader().maximumValue(), 30) self.assertEqual( rr.colorRampShader().sourceColorRamp().color1().name(), renderer.colorRampShader().sourceColorRamp().color1().name()) self.assertEqual( rr.colorRampShader().sourceColorRamp().color2().name(), renderer.colorRampShader().sourceColorRamp().color2().name()) doc = QDomDocument("testdoc") elem = renderer.save(doc, QgsReadWriteContext()) r2 = QgsPointCloudAttributeByRampRenderer.create( elem, QgsReadWriteContext()) self.assertEqual(r2.maximumScreenError(), 18) self.assertEqual(r2.maximumScreenErrorUnit(), QgsUnitTypes.RenderInches) self.assertEqual(r2.pointSize(), 13) self.assertEqual(r2.pointSizeUnit(), QgsUnitTypes.RenderPoints) self.assertEqual(r2.pointSizeMapUnitScale().minScale, 1000) self.assertEqual(r2.pointSizeMapUnitScale().maxScale, 2000) self.assertEqual(r2.attribute(), 'attr') self.assertEqual(r2.minimum(), 5) self.assertEqual(r2.maximum(), 15) self.assertEqual(r2.colorRampShader().minimumValue(), 20) self.assertEqual(r2.colorRampShader().maximumValue(), 30) self.assertEqual( r2.colorRampShader().sourceColorRamp().color1().name(), renderer.colorRampShader().sourceColorRamp().color1().name()) self.assertEqual( r2.colorRampShader().sourceColorRamp().color2().name(), renderer.colorRampShader().sourceColorRamp().color2().name())
def testAddItemsFromXml(self): p = QgsProject() l = QgsLayout(p) # add some items item1 = QgsLayoutItemLabel(l) item1.setId('xxyyxx') item1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters)) item1.attemptResize( QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) l.addItem(item1) item2 = QgsLayoutItemLabel(l) item2.setId('zzyyzz') item2.attemptMove( QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters)) item2.attemptResize( QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters)) l.addItem(item2) doc = QDomDocument("testdoc") # store in xml elem = l.writeXml(doc, QgsReadWriteContext()) l2 = QgsLayout(p) new_items = l2.addItemsFromXml(elem, doc, QgsReadWriteContext()) self.assertEqual(len(new_items), 2) items = l2.items() self.assertTrue([i for i in items if i.id() == 'xxyyxx']) self.assertTrue([i for i in items if i.id() == 'zzyyzz']) self.assertTrue(new_items[0] in l2.items()) self.assertTrue(new_items[1] in l2.items()) new_item1 = [i for i in items if i.id() == 'xxyyxx'][0] new_item2 = [i for i in items if i.id() == 'zzyyzz'][0] self.assertEqual(new_item1.positionWithUnits(), QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(new_item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) self.assertEqual( new_item2.positionWithUnits(), QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters)) self.assertEqual( new_item2.sizeWithUnits(), QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters)) # test with a group group = QgsLayoutItemGroup(l) group.addItem(item1) group.addItem(item2) l.addLayoutItem(group) elem = l.writeXml(doc, QgsReadWriteContext()) l3 = QgsLayout(p) new_items = l3.addItemsFromXml(elem, doc, QgsReadWriteContext()) self.assertEqual(len(new_items), 3) items = l3.items() self.assertTrue([i for i in items if i.id() == 'xxyyxx']) self.assertTrue([i for i in items if i.id() == 'zzyyzz']) self.assertTrue(new_items[0] in l3.items()) self.assertTrue(new_items[1] in l3.items()) self.assertTrue(new_items[2] in l3.items()) # f*** you sip, I'll just manually cast new_group = sip.cast(l3.itemByUuid(group.uuid()), QgsLayoutItemGroup) self.assertIsNotNone(new_group) other_items = [i for i in new_items if i.type() != new_group.type()] self.assertCountEqual(new_group.items(), other_items) # test restoring at set position l3 = QgsLayout(p) new_items = l3.addItemsFromXml(elem, doc, QgsReadWriteContext(), QPointF(10, 30)) self.assertEqual(len(new_items), 3) items = l3.items() new_item1 = [i for i in items if i.id() == 'xxyyxx'][0] new_item2 = [i for i in items if i.id() == 'zzyyzz'][0] self.assertEqual( new_item1.positionWithUnits(), QgsLayoutPoint(10, 30, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(new_item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) self.assertEqual( new_item2.positionWithUnits(), QgsLayoutPoint(2.0, 4.0, QgsUnitTypes.LayoutCentimeters)) self.assertEqual( new_item2.sizeWithUnits(), QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters)) # paste in place l4 = QgsLayout(p) page = QgsLayoutItemPage(l) page.setPageSize('A3') l4.pageCollection().addPage(page) page = QgsLayoutItemPage(l) page.setPageSize('A6') l4.pageCollection().addPage(page) new_items = l4.addItemsFromXml(elem, doc, QgsReadWriteContext(), QPointF(10, 30), True) self.assertEqual(len(new_items), 3) new_item1 = [i for i in new_items if i.id() == 'xxyyxx'][0] new_item2 = [i for i in new_items if i.id() == 'zzyyzz'][0] self.assertEqual(new_item1.pagePositionWithUnits(), QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(new_item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(new_item1.page(), 0) self.assertEqual( new_item2.pagePositionWithUnits(), QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters)) self.assertEqual( new_item2.sizeWithUnits(), QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters)) self.assertEqual(new_item2.page(), 0) # paste in place, page 2 new_items = l4.addItemsFromXml(elem, doc, QgsReadWriteContext(), QPointF(10, 550), True) self.assertEqual(len(new_items), 3) new_item1 = [i for i in new_items if i.id() == 'xxyyxx'][0] new_item2 = [i for i in new_items if i.id() == 'zzyyzz'][0] self.assertEqual(new_item1.pagePositionWithUnits(), QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(new_item1.page(), 1) self.assertEqual(new_item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) self.assertEqual( new_item2.pagePositionWithUnits(), QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters)) self.assertEqual(new_item2.page(), 1) self.assertEqual( new_item2.sizeWithUnits(), QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters))
def testSaveLoadTemplate(self): tmpfile = os.path.join(self.basetestpath, 'testTemplate.qpt') p = QgsProject() l = QgsLayout(p) l.initializeDefaults() # add some items item1 = QgsLayoutItemLabel(l) item1.setId('xxyyxx') item1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters)) item1.attemptResize( QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) l.addItem(item1) item2 = QgsLayoutItemLabel(l) item2.setId('zzyyzz') item2.attemptMove( QgsLayoutPoint(1.4, 1.8, QgsUnitTypes.LayoutCentimeters)) item2.attemptResize( QgsLayoutSize(2.8, 2.2, QgsUnitTypes.LayoutCentimeters)) l.addItem(item2) uuids = {item1.uuid(), item2.uuid()} original_uuids = {item1.uuid(), item2.uuid()} self.assertTrue(l.saveAsTemplate(tmpfile, QgsReadWriteContext())) l2 = QgsLayout(p) with open(tmpfile) as f: template_content = f.read() doc = QDomDocument() doc.setContent(template_content) # adding to existing items new_items, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), False) self.assertTrue(ok) self.assertEqual(len(new_items), 2) items = l2.items() self.assertTrue([i for i in items if i.id() == 'xxyyxx']) self.assertTrue([i for i in items if i.id() == 'zzyyzz']) self.assertTrue(new_items[0] in l2.items()) self.assertTrue(new_items[1] in l2.items()) # double check that new items have a unique uid self.assertNotIn(new_items[0].uuid(), uuids) self.assertIn(new_items[0].templateUuid(), original_uuids) uuids.add(new_items[0].uuid()) self.assertNotIn(new_items[1].uuid(), uuids) self.assertIn(new_items[1].templateUuid(), original_uuids) uuids.add(new_items[1].uuid()) # adding to existing items new_items2, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), False) self.assertTrue(ok) self.assertEqual(len(new_items2), 2) items = l2.items() self.assertEqual(len(items), 4) self.assertTrue([i for i in items if i.id() == 'xxyyxx']) self.assertTrue([i for i in items if i.id() == 'zzyyzz']) self.assertTrue(new_items[0] in l2.items()) self.assertTrue(new_items[1] in l2.items()) self.assertTrue(new_items2[0] in l2.items()) self.assertTrue(new_items2[1] in l2.items()) self.assertNotIn(new_items2[0].uuid(), uuids) self.assertIn(new_items2[0].templateUuid(), original_uuids) uuids.add(new_items[0].uuid()) self.assertNotIn(new_items2[1].uuid(), uuids) self.assertIn(new_items2[1].templateUuid(), original_uuids) uuids.add(new_items[1].uuid()) # clearing existing items new_items3, ok = l2.loadFromTemplate(doc, QgsReadWriteContext(), True) self.assertTrue(ok) self.assertEqual(len(new_items3), 3) # includes page items = l2.items() self.assertTrue([ i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'xxyyxx' ]) self.assertTrue([ i for i in items if isinstance(i, QgsLayoutItem) and i.id() == 'zzyyzz' ]) self.assertTrue(new_items3[0] in l2.items()) self.assertTrue(new_items3[1] in l2.items()) self.assertIn(new_items3[0].templateUuid(), original_uuids) self.assertIn(new_items3[1].templateUuid(), original_uuids) self.assertEqual(l2.itemByUuid(new_items3[0].templateUuid(), True), new_items3[0]) self.assertEqual(l2.itemByUuid(new_items3[1].templateUuid(), True), new_items3[1])
def mkForm(b, qptForm, form_file, project_name, root_out, zl_layer, zl_field, di_layer, di_field, di_name): root_code = os.path.dirname(os.path.realpath(__file__)) name = str(b.attribute(1).replace('_', '.')) + '_' + str( b.attribute(3)) + '_' + str(b.attribute(4)) template_file = open(qptForm, 'r') template_content = template_file.read() template_file.close() document = QDomDocument() document.setContent(template_content) composition = QgsLayout(QgsProject().instance()) composition.loadFromTemplate(document, QgsReadWriteContext()) corners = composition.itemById('corners') corners.setPicturePath(root_code + '/templates/corners_a4.svg') logo = composition.itemById('logo') logo.setPicturePath(root_code + '/templates/logo.svg') ##title ti = composition.itemById('project') ti.setText(project_name) ##zona zo = composition.itemById('zona') zo.setText(str(b.attribute(1).replace('_', '.'))) ##pagina zo = composition.itemById('pagina') zo.setText(name) #form qr = composition.itemById('form') qr.setPicturePath(form_file) #qrcode qr = composition.itemById('qrcode') data = name qrpath = makeQR(data, name) qr.setPicturePath(qrpath) ##cbarres cbarres = composition.itemById('cbarres') cbarres.setText('*' + str(b.attribute(1).replace('_', '.')) + ',' + str(b.attribute(3)) + ',' + str(b.attribute(4)) + '*') composition.refresh() zz = zl_layer.getFeatures( QgsFeatureRequest(QgsExpression('"name" = \'' + b.attribute(1) + '\''))) zz = [x for x in zz] z = zz[0].geometry() currentDistrict = unicode(zz[0].attribute(zl_field)) image_name = str(b.attribute(1).replace('_', '-')) + '_' + str( b.id()) + '_form' + '_' + currentDistrict printRaster(composition, image_name, root_out) return