def testSnapPointToGrid(self): p = QgsProject() l = QgsLayout(p) # need a page to snap to grid page = QgsLayoutItemPage(l) page.setPageSize('A4') l.pageCollection().addPage(page) s = QgsLayoutSnapper(l) l.gridSettings().setResolution( QgsLayoutMeasurement(5, QgsUnitTypes.LayoutMillimeters)) s.setSnapToGrid(True) s.setSnapTolerance(1) point, snappedX, snappedY = s.snapPointToGrid(QPointF(1, 1), 1) self.assertTrue(snappedX) self.assertTrue(snappedY) self.assertEqual(point, QPointF(0, 0)) point, snappedX, snappedY = s.snapPointToGrid(QPointF(9, 1), 1) self.assertTrue(snappedX) self.assertTrue(snappedY) self.assertEqual(point, QPointF(10, 0)) point, snappedX, snappedY = s.snapPointToGrid(QPointF(1, 11), 1) self.assertTrue(snappedX) self.assertTrue(snappedY) self.assertEqual(point, QPointF(0, 10)) point, snappedX, snappedY = s.snapPointToGrid(QPointF(13, 11), 1) self.assertFalse(snappedX) self.assertTrue(snappedY) self.assertEqual(point, QPointF(13, 10)) point, snappedX, snappedY = s.snapPointToGrid(QPointF(11, 13), 1) self.assertTrue(snappedX) self.assertFalse(snappedY) self.assertEqual(point, QPointF(10, 13)) point, snappedX, snappedY = s.snapPointToGrid(QPointF(13, 23), 1) self.assertFalse(snappedX) self.assertFalse(snappedY) self.assertEqual(point, QPointF(13, 23)) # grid disabled s.setSnapToGrid(False) point, nappedX, snappedY = s.snapPointToGrid(QPointF(1, 1), 1) self.assertFalse(nappedX) self.assertFalse(snappedY) self.assertEqual(point, QPointF(1, 1)) s.setSnapToGrid(True) # with different pixel scale point, snappedX, snappedY = s.snapPointToGrid(QPointF(0.5, 0.5), 1) self.assertTrue(snappedX) self.assertTrue(snappedY) self.assertEqual(point, QPointF(0, 0)) point, snappedX, snappedY = s.snapPointToGrid(QPointF(0.5, 0.5), 3) self.assertFalse(snappedX) self.assertFalse(snappedY) self.assertEqual(point, QPointF(0.5, 0.5)) # with offset grid l.gridSettings().setOffset(QgsLayoutPoint(2, 0)) point, snappedX, snappedY = s.snapPointToGrid(QPointF(13, 23), 1) self.assertTrue(snappedX) self.assertFalse(snappedY) self.assertEqual(point, QPointF(12, 23))
def testExportToSvg(self): md = QgsProject.instance().metadata() md.setTitle('proj title') md.setAuthor('proj author') md.setCreationDateTime( QDateTime(QDate(2011, 5, 3), QTime(9, 4, 5), QTimeZone(36000))) md.setIdentifier('proj identifier') md.setAbstract('proj abstract') md.setKeywords({'kw': ['kw1', 'kw2']}) QgsProject.instance().setMetadata(md) l = QgsLayout(QgsProject.instance()) l.initializeDefaults() # add a second page page2 = QgsLayoutItemPage(l) page2.setPageSize('A5') l.pageCollection().addPage(page2) # add some items item1 = QgsLayoutItemShape(l) item1.attemptSetSceneRect(QRectF(10, 20, 100, 150)) fill = QgsSimpleFillSymbolLayer() fill_symbol = QgsFillSymbol() fill_symbol.changeSymbolLayer(0, fill) fill.setColor(Qt.green) fill.setStrokeStyle(Qt.NoPen) item1.setSymbol(fill_symbol) l.addItem(item1) item2 = QgsLayoutItemShape(l) item2.attemptSetSceneRect(QRectF(10, 20, 100, 150)) item2.attemptMove(QgsLayoutPoint(10, 20), page=1) fill = QgsSimpleFillSymbolLayer() fill_symbol = QgsFillSymbol() fill_symbol.changeSymbolLayer(0, fill) fill.setColor(Qt.cyan) fill.setStrokeStyle(Qt.NoPen) item2.setSymbol(fill_symbol) l.addItem(item2) exporter = QgsLayoutExporter(l) # setup settings settings = QgsLayoutExporter.SvgExportSettings() settings.dpi = 80 settings.forceVectorOutput = False settings.exportMetadata = True svg_file_path = os.path.join(self.basetestpath, 'test_exporttosvgdpi.svg') svg_file_path_2 = os.path.join(self.basetestpath, 'test_exporttosvgdpi_2.svg') self.assertEqual(exporter.exportToSvg(svg_file_path, settings), QgsLayoutExporter.Success) self.assertTrue(os.path.exists(svg_file_path)) self.assertTrue(os.path.exists(svg_file_path_2)) # metadata def checkMetadata(f, expected): # ideally we'd check the path too - but that's very complex given that # the output from Qt svg generator isn't valid XML, and no Python standard library # xml parser handles invalid xml... self.assertEqual('proj title' in open(f).read(), expected) self.assertEqual('proj author' in open(f).read(), expected) self.assertEqual('proj identifier' in open(f).read(), expected) self.assertEqual('2011-05-03' in open(f).read(), expected) self.assertEqual('proj abstract' in open(f).read(), expected) self.assertEqual('kw1' in open(f).read(), expected) self.assertEqual('kw2' in open(f).read(), expected) for f in [svg_file_path, svg_file_path_2]: checkMetadata(f, True) rendered_page_1 = os.path.join(self.basetestpath, 'test_exporttosvgdpi.png') svgToPng(svg_file_path, rendered_page_1, width=936) rendered_page_2 = os.path.join(self.basetestpath, 'test_exporttosvgdpi2.png') svgToPng(svg_file_path_2, rendered_page_2, width=467) self.assertTrue( self.checkImage('exporttosvgdpi_page1', 'exporttopdfdpi_page1', rendered_page_1, size_tolerance=1)) self.assertTrue( self.checkImage('exporttosvgdpi_page2', 'exporttopdfdpi_page2', rendered_page_2, size_tolerance=1)) # no metadata settings.exportMetadata = False self.assertEqual(exporter.exportToSvg(svg_file_path, settings), QgsLayoutExporter.Success) for f in [svg_file_path, svg_file_path_2]: checkMetadata(f, False) # layered settings.exportAsLayers = True settings.exportMetadata = True svg_file_path = os.path.join(self.basetestpath, 'test_exporttosvglayered.svg') svg_file_path_2 = os.path.join(self.basetestpath, 'test_exporttosvglayered_2.svg') self.assertEqual(exporter.exportToSvg(svg_file_path, settings), QgsLayoutExporter.Success) self.assertTrue(os.path.exists(svg_file_path)) self.assertTrue(os.path.exists(svg_file_path_2)) rendered_page_1 = os.path.join(self.basetestpath, 'test_exporttosvglayered.png') svgToPng(svg_file_path, rendered_page_1, width=936) rendered_page_2 = os.path.join(self.basetestpath, 'test_exporttosvglayered2.png') svgToPng(svg_file_path_2, rendered_page_2, width=467) self.assertTrue( self.checkImage('exporttosvglayered_page1', 'exporttopdfdpi_page1', rendered_page_1, size_tolerance=1)) self.assertTrue( self.checkImage('exporttosvglayered_page2', 'exporttopdfdpi_page2', rendered_page_2, size_tolerance=1)) for f in [svg_file_path, svg_file_path_2]: checkMetadata(f, True) # layered no metadata settings.exportAsLayers = True settings.exportMetadata = False self.assertEqual(exporter.exportToSvg(svg_file_path, settings), QgsLayoutExporter.Success) for f in [svg_file_path, svg_file_path_2]: checkMetadata(f, False)
def testRequiresRasterization(self): l = QgsLayout(QgsProject.instance()) item = self.make_item(l) self.assertFalse(item.requiresRasterization()) item.setBlendMode(QPainter.CompositionMode_SourceIn) self.assertTrue(item.requiresRasterization())
def testResize(self): p = QgsProject() l = QgsLayout(p) # add some items item1 = QgsLayoutItemPicture(l) item1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters)) item1.attemptResize( QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) l.addItem(item1) item2 = QgsLayoutItemPicture(l) item2.attemptMove(QgsLayoutPoint(7, 10, QgsUnitTypes.LayoutMillimeters)) item2.attemptResize( QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters)) l.addItem(item2) item3 = QgsLayoutItemPicture(l) item3.attemptMove( QgsLayoutPoint(0.8, 1.2, QgsUnitTypes.LayoutCentimeters)) item3.attemptResize( QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters)) l.addItem(item3) QgsLayoutAligner.resizeItems(l, [item1, item2, item3], QgsLayoutAligner.ResizeNarrowest) self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(10, 12, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters)) self.assertEqual( item3.sizeWithUnits(), QgsLayoutSize(1.0, 1.6, QgsUnitTypes.LayoutCentimeters)) l.undoStack().stack().undo() QgsLayoutAligner.resizeItems(l, [item1, item2, item3], QgsLayoutAligner.ResizeWidest) self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(18, 9, QgsUnitTypes.LayoutMillimeters)) self.assertEqual( item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters)) l.undoStack().stack().undo() QgsLayoutAligner.resizeItems(l, [item1, item2, item3], QgsLayoutAligner.ResizeShortest) self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 9, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters)) self.assertEqual( item3.sizeWithUnits(), QgsLayoutSize(1.8, 0.9, QgsUnitTypes.LayoutCentimeters)) l.undoStack().stack().undo() QgsLayoutAligner.resizeItems(l, [item1, item2, item3], QgsLayoutAligner.ResizeTallest) self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 16, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 16, QgsUnitTypes.LayoutMillimeters)) self.assertEqual( item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters)) l.undoStack().stack().undo() item2.attemptResize( QgsLayoutSize(10, 19, QgsUnitTypes.LayoutMillimeters)) QgsLayoutAligner.resizeItems(l, [item1, item2, item3], QgsLayoutAligner.ResizeToSquare) self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 18, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(19, 19, QgsUnitTypes.LayoutMillimeters)) self.assertEqual( item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.8, QgsUnitTypes.LayoutCentimeters)) l.undoStack().stack().undo() QgsLayoutAligner.resizeItems(l, [item1], QgsLayoutAligner.ResizeToSquare) self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 18, QgsUnitTypes.LayoutMillimeters))
def testExportToImage(self): md = QgsProject.instance().metadata() md.setTitle('proj title') md.setAuthor('proj author') md.setCreationDateTime( QDateTime(QDate(2011, 5, 3), QTime(9, 4, 5), QTimeZone(36000))) md.setIdentifier('proj identifier') md.setAbstract('proj abstract') md.setKeywords({'kw': ['kw1', 'kw2'], 'KWx': ['kw3', 'kw4']}) QgsProject.instance().setMetadata(md) l = QgsLayout(QgsProject.instance()) l.initializeDefaults() # add a second page page2 = QgsLayoutItemPage(l) page2.setPageSize('A5') l.pageCollection().addPage(page2) # add some items item1 = QgsLayoutItemShape(l) item1.attemptSetSceneRect(QRectF(10, 20, 100, 150)) fill = QgsSimpleFillSymbolLayer() fill_symbol = QgsFillSymbol() fill_symbol.changeSymbolLayer(0, fill) fill.setColor(Qt.green) fill.setStrokeStyle(Qt.NoPen) item1.setSymbol(fill_symbol) l.addItem(item1) item2 = QgsLayoutItemShape(l) item2.attemptSetSceneRect(QRectF(10, 20, 100, 150)) item2.attemptMove(QgsLayoutPoint(10, 20), page=1) fill = QgsSimpleFillSymbolLayer() fill_symbol = QgsFillSymbol() fill_symbol.changeSymbolLayer(0, fill) fill.setColor(Qt.cyan) fill.setStrokeStyle(Qt.NoPen) item2.setSymbol(fill_symbol) l.addItem(item2) exporter = QgsLayoutExporter(l) # setup settings settings = QgsLayoutExporter.ImageExportSettings() settings.dpi = 80 rendered_file_path = os.path.join(self.basetestpath, 'test_exporttoimagedpi.png') self.assertEqual(exporter.exportToImage(rendered_file_path, settings), QgsLayoutExporter.Success) self.assertTrue( self.checkImage('exporttoimagedpi_page1', 'exporttoimagedpi_page1', rendered_file_path)) page2_path = os.path.join(self.basetestpath, 'test_exporttoimagedpi_2.png') self.assertTrue( self.checkImage('exporttoimagedpi_page2', 'exporttoimagedpi_page2', page2_path)) for f in (rendered_file_path, page2_path): d = gdal.Open(f) metadata = d.GetMetadata() self.assertEqual(metadata['Author'], 'proj author') self.assertEqual(metadata['Created'], '2011-05-03T09:04:05+10:00') self.assertEqual(metadata['Keywords'], 'KWx: kw3,kw4;kw: kw1,kw2') self.assertEqual(metadata['Subject'], 'proj abstract') self.assertEqual(metadata['Title'], 'proj title') # crop to contents settings.cropToContents = True settings.cropMargins = QgsMargins(10, 20, 30, 40) rendered_file_path = os.path.join(self.basetestpath, 'test_exporttoimagecropped.png') self.assertEqual(exporter.exportToImage(rendered_file_path, settings), QgsLayoutExporter.Success) self.assertTrue( self.checkImage('exporttoimagecropped_page1', 'exporttoimagecropped_page1', rendered_file_path)) page2_path = os.path.join(self.basetestpath, 'test_exporttoimagecropped_2.png') self.assertTrue( self.checkImage('exporttoimagecropped_page2', 'exporttoimagecropped_page2', page2_path)) # specific pages settings.cropToContents = False settings.pages = [1] rendered_file_path = os.path.join(self.basetestpath, 'test_exporttoimagepages.png') self.assertEqual(exporter.exportToImage(rendered_file_path, settings), QgsLayoutExporter.Success) self.assertFalse(os.path.exists(rendered_file_path)) page2_path = os.path.join(self.basetestpath, 'test_exporttoimagepages_2.png') self.assertTrue( self.checkImage('exporttoimagedpi_page2', 'exporttoimagedpi_page2', page2_path)) # image size settings.imageSize = QSize(600, 851) rendered_file_path = os.path.join(self.basetestpath, 'test_exporttoimagesize.png') self.assertEqual(exporter.exportToImage(rendered_file_path, settings), QgsLayoutExporter.Success) self.assertFalse(os.path.exists(rendered_file_path)) page2_path = os.path.join(self.basetestpath, 'test_exporttoimagesize_2.png') self.assertTrue( self.checkImage('exporttoimagesize_page2', 'exporttoimagesize_page2', page2_path)) # image size with incorrect aspect ratio # this can happen as a result of data defined page sizes settings.imageSize = QSize(851, 600) rendered_file_path = os.path.join( self.basetestpath, 'test_exporttoimagesizebadaspect.png') self.assertEqual(exporter.exportToImage(rendered_file_path, settings), QgsLayoutExporter.Success) page2_path = os.path.join(self.basetestpath, 'test_exporttoimagesizebadaspect_2.png') im = QImage(page2_path) self.assertTrue( self.checkImage('exporttoimagesize_badaspect', 'exporttoimagedpi_page2', page2_path), '{}x{}'.format(im.width(), im.height()))
def testStacking(self): p = QgsProject() l = QgsLayout(p) # add some items item1 = QgsLayoutItemMap(l) l.addLayoutItem(item1) item2 = QgsLayoutItemMap(l) l.addLayoutItem(item2) item3 = QgsLayoutItemMap(l) l.addLayoutItem(item3) self.assertEqual(item1.zValue(), 1) self.assertEqual(item2.zValue(), 2) self.assertEqual(item3.zValue(), 3) # no effect interactions self.assertFalse(l.raiseItem(None)) self.assertFalse(l.lowerItem(None)) self.assertFalse(l.moveItemToTop(None)) self.assertFalse(l.moveItemToBottom(None)) self.assertEqual(item1.zValue(), 1) self.assertEqual(item2.zValue(), 2) self.assertEqual(item3.zValue(), 3) # raising self.assertFalse(l.raiseItem(item3)) self.assertEqual(item1.zValue(), 1) self.assertEqual(item2.zValue(), 2) self.assertEqual(item3.zValue(), 3) self.assertTrue(l.raiseItem(item2)) self.assertEqual(item1.zValue(), 1) self.assertEqual(item2.zValue(), 3) self.assertEqual(item3.zValue(), 2) self.assertFalse(l.raiseItem(item2)) self.assertEqual(item1.zValue(), 1) self.assertEqual(item2.zValue(), 3) self.assertEqual(item3.zValue(), 2) self.assertTrue(l.raiseItem(item1)) self.assertEqual(item1.zValue(), 2) self.assertEqual(item2.zValue(), 3) self.assertEqual(item3.zValue(), 1) # lower self.assertFalse(l.lowerItem(item3)) self.assertEqual(item1.zValue(), 2) self.assertEqual(item2.zValue(), 3) self.assertEqual(item3.zValue(), 1) self.assertTrue(l.lowerItem(item2)) self.assertEqual(item1.zValue(), 3) self.assertEqual(item2.zValue(), 2) self.assertEqual(item3.zValue(), 1) self.assertTrue(l.lowerItem(item2)) self.assertEqual(item1.zValue(), 3) self.assertEqual(item2.zValue(), 1) self.assertEqual(item3.zValue(), 2) # raise to top self.assertFalse(l.moveItemToTop(item1)) self.assertEqual(item1.zValue(), 3) self.assertEqual(item2.zValue(), 1) self.assertEqual(item3.zValue(), 2) self.assertTrue(l.moveItemToTop(item3)) self.assertEqual(item1.zValue(), 2) self.assertEqual(item2.zValue(), 1) self.assertEqual(item3.zValue(), 3) self.assertTrue(l.moveItemToTop(item2)) self.assertEqual(item1.zValue(), 1) self.assertEqual(item2.zValue(), 3) self.assertEqual(item3.zValue(), 2) # move to bottom self.assertFalse(l.moveItemToBottom(item1)) self.assertEqual(item1.zValue(), 1) self.assertEqual(item2.zValue(), 3) self.assertEqual(item3.zValue(), 2) self.assertTrue(l.moveItemToBottom(item3)) self.assertEqual(item1.zValue(), 2) self.assertEqual(item2.zValue(), 3) self.assertEqual(item3.zValue(), 1) self.assertTrue(l.moveItemToBottom(item2)) self.assertEqual(item1.zValue(), 3) self.assertEqual(item2.zValue(), 1) self.assertEqual(item3.zValue(), 2)
def testUpdateGuide(self): p = QgsProject() l = QgsLayout(p) l.initializeDefaults() # add a page # add a second page page2 = QgsLayoutItemPage(l) page2.setPageSize('A5') l.pageCollection().addPage(page2) g = QgsLayoutGuide( Qt.Horizontal, QgsLayoutMeasurement(5, QgsUnitTypes.LayoutCentimeters), l.pageCollection().page(0)) g.setLayout(l) g.update() self.assertTrue(g.item().isVisible()) self.assertEqual(g.item().line().x1(), 0) self.assertEqual(g.item().line().y1(), 50) self.assertEqual(g.item().line().x2(), 297) self.assertEqual(g.item().line().y2(), 50) self.assertEqual(g.layoutPosition(), 50) g.setPosition(QgsLayoutMeasurement(15, QgsUnitTypes.LayoutMillimeters)) g.update() self.assertTrue(g.item().isVisible()) self.assertEqual(g.item().line().x1(), 0) self.assertEqual(g.item().line().y1(), 15) self.assertEqual(g.item().line().x2(), 297) self.assertEqual(g.item().line().y2(), 15) self.assertEqual(g.layoutPosition(), 15) # guide on page2 g1 = QgsLayoutGuide( Qt.Horizontal, QgsLayoutMeasurement(5, QgsUnitTypes.LayoutCentimeters), l.pageCollection().page(1)) g1.setLayout(l) g1.update() g1.setPosition(QgsLayoutMeasurement(15, QgsUnitTypes.LayoutMillimeters)) g1.update() self.assertTrue(g1.item().isVisible()) self.assertEqual(g1.item().line().x1(), 0) self.assertEqual(g1.item().line().y1(), 235) self.assertEqual(g1.item().line().x2(), 148) self.assertEqual(g1.item().line().y2(), 235) self.assertEqual(g1.layoutPosition(), 235) # vertical guide g2 = QgsLayoutGuide( Qt.Vertical, QgsLayoutMeasurement(5, QgsUnitTypes.LayoutCentimeters), l.pageCollection().page(0)) g2.setLayout(l) g2.update() self.assertTrue(g2.item().isVisible()) self.assertEqual(g2.item().line().x1(), 50) self.assertEqual(g2.item().line().y1(), 0) self.assertEqual(g2.item().line().x2(), 50) self.assertEqual(g2.item().line().y2(), 210) self.assertEqual(g2.layoutPosition(), 50) g.setPage(None) g.update() self.assertFalse(g.item().isVisible()) g.setPage(l.pageCollection().page(0)) g.update() self.assertTrue(g.item().isVisible()) #throw it off the bottom of the page g.setPosition( QgsLayoutMeasurement(1115, QgsUnitTypes.LayoutMillimeters)) g.update() self.assertFalse(g.item().isVisible()) # guide on page2 g3 = QgsLayoutGuide( Qt.Vertical, QgsLayoutMeasurement(5, QgsUnitTypes.LayoutCentimeters), l.pageCollection().page(1)) g3.setLayout(l) g3.update() self.assertTrue(g3.item().isVisible()) self.assertEqual(g3.item().line().x1(), 50) self.assertEqual(g3.item().line().y1(), 220) self.assertEqual(g3.item().line().x2(), 50) self.assertEqual(g3.item().line().y2(), 430) self.assertEqual(g3.layoutPosition(), 50)
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 testSelectNextByZOrder(self): p = QgsProject() l = QgsLayout(p) # add some items item1 = QgsLayoutItemPicture(l) l.addItem(item1) item2 = QgsLayoutItemPicture(l) l.addItem(item2) item3 = QgsLayoutItemPicture(l) item3.setLocked(True) l.addItem(item3) view = QgsLayoutView() # no layout, no crash view.selectNextItemAbove() view.selectNextItemBelow() view.setCurrentLayout(l) focused_item_spy = QSignalSpy(view.itemFocused) # no selection view.selectNextItemAbove() view.selectNextItemBelow() self.assertEqual(len(focused_item_spy), 0) l.setSelectedItem(item1) self.assertEqual(len(focused_item_spy), 1) # already bottom most view.selectNextItemBelow() self.assertTrue(item1.isSelected()) self.assertFalse(item2.isSelected()) self.assertFalse(item3.isSelected()) self.assertEqual(len(focused_item_spy), 1) view.selectNextItemAbove() self.assertFalse(item1.isSelected()) self.assertTrue(item2.isSelected()) self.assertFalse(item3.isSelected()) self.assertEqual(len(focused_item_spy), 2) view.selectNextItemAbove() self.assertFalse(item1.isSelected()) self.assertFalse(item2.isSelected()) self.assertTrue(item3.isSelected()) self.assertEqual(len(focused_item_spy), 3) view.selectNextItemAbove() # already top most self.assertFalse(item1.isSelected()) self.assertFalse(item2.isSelected()) self.assertTrue(item3.isSelected()) self.assertEqual(len(focused_item_spy), 3) view.selectNextItemBelow() self.assertFalse(item1.isSelected()) self.assertTrue(item2.isSelected()) self.assertFalse(item3.isSelected()) self.assertEqual(len(focused_item_spy), 4) view.selectNextItemBelow() self.assertTrue(item1.isSelected()) self.assertFalse(item2.isSelected()) self.assertFalse(item3.isSelected()) self.assertEqual(len(focused_item_spy), 5) view.selectNextItemBelow() # back to bottom most self.assertTrue(item1.isSelected()) self.assertFalse(item2.isSelected()) self.assertFalse(item3.isSelected()) self.assertEqual(len(focused_item_spy), 5)
def testPartialLabels(self): """ Test rendering map item with a show partial labels flag """ 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.UsePartialCandidates, False) 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]) layout.addLayoutItem(map) # default should always be to hide partial labels self.assertFalse(map.mapFlags() & QgsLayoutItemMap.ShowPartialLabels) # hiding partial labels (the default) map.setMapFlags(QgsLayoutItemMap.MapItemFlags()) checker = QgsLayoutChecker('composermap_label_nomargin', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) # showing partial labels map.setMapFlags(QgsLayoutItemMap.ShowPartialLabels) checker = QgsLayoutChecker('composermap_show_partial_labels', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message)
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 testLabelMargin(self): """ Test rendering map item with a label margin set """ 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.UsePartialCandidates, False) 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]) layout.addLayoutItem(map) checker = QgsLayoutChecker('composermap_label_nomargin', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) map.setLabelMargin( QgsLayoutMeasurement(15, QgsUnitTypes.LayoutMillimeters)) checker = QgsLayoutChecker('composermap_label_margin', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) map.setLabelMargin( QgsLayoutMeasurement(3, QgsUnitTypes.LayoutCentimeters)) checker = QgsLayoutChecker('composermap_label_cm_margin', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) map.setMapRotation(45) map.zoomToExtent(vl.extent()) map.setScale(map.scale() * 1.2) checker = QgsLayoutChecker('composermap_rotated_label_margin', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) # data defined map.setMapRotation(0) map.zoomToExtent(vl.extent()) map.dataDefinedProperties().setProperty( QgsLayoutObject.MapLabelMargin, QgsProperty.fromExpression('1+3')) map.refresh() checker = QgsLayoutChecker('composermap_dd_label_margin', layout) checker.setControlPathPrefix("composer_map") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message)
def testLegendRenderWithMapTheme(self): """Test rendering legends linked to map themes""" QgsProject.instance().removeAllMapLayers() point_path = os.path.join(TEST_DATA_DIR, 'points.shp') point_layer = QgsVectorLayer(point_path, 'points', 'ogr') line_path = os.path.join(TEST_DATA_DIR, 'lines.shp') line_layer = QgsVectorLayer(line_path, 'lines', 'ogr') QgsProject.instance().clear() QgsProject.instance().addMapLayers([point_layer, line_layer]) marker_symbol = QgsMarkerSymbol.createSimple({ 'color': '#ff0000', 'outline_style': 'no', 'size': '5' }) point_layer.setRenderer(QgsSingleSymbolRenderer(marker_symbol)) point_layer.styleManager().addStyleFromLayer("red") line_symbol = QgsLineSymbol.createSimple({ 'color': '#ff0000', 'line_width': '2' }) line_layer.setRenderer(QgsSingleSymbolRenderer(line_symbol)) line_layer.styleManager().addStyleFromLayer("red") red_record = QgsMapThemeCollection.MapThemeRecord() point_red_record = QgsMapThemeCollection.MapThemeLayerRecord( point_layer) point_red_record.usingCurrentStyle = True point_red_record.currentStyle = 'red' red_record.addLayerRecord(point_red_record) line_red_record = QgsMapThemeCollection.MapThemeLayerRecord(line_layer) line_red_record.usingCurrentStyle = True line_red_record.currentStyle = 'red' red_record.addLayerRecord(line_red_record) QgsProject.instance().mapThemeCollection().insert('red', red_record) marker_symbol1 = QgsMarkerSymbol.createSimple({ 'color': '#0000ff', 'outline_style': 'no', 'size': '5' }) marker_symbol2 = QgsMarkerSymbol.createSimple({ 'color': '#0000ff', 'name': 'diamond', 'outline_style': 'no', 'size': '5' }) marker_symbol3 = QgsMarkerSymbol.createSimple({ 'color': '#0000ff', 'name': 'rectangle', 'outline_style': 'no', 'size': '5' }) point_layer.setRenderer( QgsCategorizedSymbolRenderer('Class', [ QgsRendererCategory('B52', marker_symbol1, ''), QgsRendererCategory('Biplane', marker_symbol2, ''), QgsRendererCategory('Jet', marker_symbol3, ''), ])) point_layer.styleManager().addStyleFromLayer("blue") line_symbol = QgsLineSymbol.createSimple({ 'color': '#0000ff', 'line_width': '2' }) line_layer.setRenderer(QgsSingleSymbolRenderer(line_symbol)) line_layer.styleManager().addStyleFromLayer("blue") blue_record = QgsMapThemeCollection.MapThemeRecord() point_blue_record = QgsMapThemeCollection.MapThemeLayerRecord( point_layer) point_blue_record.usingCurrentStyle = True point_blue_record.currentStyle = 'blue' blue_record.addLayerRecord(point_blue_record) line_blue_record = QgsMapThemeCollection.MapThemeLayerRecord( line_layer) line_blue_record.usingCurrentStyle = True line_blue_record.currentStyle = 'blue' blue_record.addLayerRecord(line_blue_record) QgsProject.instance().mapThemeCollection().insert('blue', blue_record) layout = QgsLayout(QgsProject.instance()) layout.initializeDefaults() map1 = QgsLayoutItemMap(layout) map1.attemptSetSceneRect(QRectF(20, 20, 80, 80)) map1.setFrameEnabled(True) map1.setLayers([point_layer, line_layer]) layout.addLayoutItem(map1) map1.setExtent(point_layer.extent()) map1.setFollowVisibilityPreset(True) map1.setFollowVisibilityPresetName('red') map2 = QgsLayoutItemMap(layout) map2.attemptSetSceneRect(QRectF(20, 120, 80, 80)) map2.setFrameEnabled(True) map2.setLayers([point_layer, line_layer]) layout.addLayoutItem(map2) map2.setExtent(point_layer.extent()) map2.setFollowVisibilityPreset(True) map2.setFollowVisibilityPresetName('blue') legend = QgsLayoutItemLegend(layout) legend.setTitle("Legend") legend.attemptSetSceneRect(QRectF(120, 20, 80, 80)) legend.setFrameEnabled(True) legend.setFrameStrokeWidth(QgsLayoutMeasurement(2)) legend.setBackgroundColor(QColor(200, 200, 200)) legend.setTitle('') layout.addLayoutItem(legend) legend.setLinkedMap(map1) legend2 = QgsLayoutItemLegend(layout) legend2.setTitle("Legend") legend2.attemptSetSceneRect(QRectF(120, 120, 80, 80)) legend2.setFrameEnabled(True) legend2.setFrameStrokeWidth(QgsLayoutMeasurement(2)) legend2.setBackgroundColor(QColor(200, 200, 200)) legend2.setTitle('') layout.addLayoutItem(legend2) legend2.setLinkedMap(map2) checker = QgsLayoutChecker('composer_legend_theme', layout) checker.setControlPathPrefix("composer_legend") result, message = checker.testLayout() self.report += checker.report() self.assertTrue(result, message) QgsProject.instance().clear()
def testSnapRect(self): p = QgsProject() l = QgsLayout(p) page = QgsLayoutItemPage(l) page.setPageSize('A4') l.pageCollection().addPage(page) s = QgsLayoutSnapper(l) guides = l.guides() # first test snapping to grid l.gridSettings().setResolution( QgsLayoutMeasurement(5, QgsUnitTypes.LayoutMillimeters)) s.setSnapToItems(False) s.setSnapToGrid(True) s.setSnapTolerance(1) rect, snapped = s.snapRect(QRectF(1, 1, 2, 1), 1) self.assertTrue(snapped) self.assertEqual(rect, QRectF(0, 0, 2, 1)) rect, snapped = s.snapRect(QRectF(1, 1, 3.5, 3.5), 1) self.assertTrue(snapped) self.assertEqual(rect, QRectF(1.5, 1.5, 3.5, 3.5)) s.setSnapToItems(False) s.setSnapToGrid(False) rect, snapped = s.snapRect(QRectF(1, 1, 3.5, 3.5), 1) self.assertFalse(snapped) self.assertEqual(rect, QRectF(1, 1, 3.5, 3.5)) # test that guide takes precedence s.setSnapToGrid(True) s.setSnapToGuides(True) guides.addGuide( QgsLayoutGuide(Qt.Horizontal, QgsLayoutMeasurement(0.5), page)) rect, snapped = s.snapRect(QRectF(1, 1, 2, 3), 1) self.assertTrue(snapped) self.assertEqual(rect, QRectF(0.0, 0.5, 2.0, 3.0)) # add an item item1 = QgsLayoutItemMap(l) item1.attemptMove( QgsLayoutPoint(121, 1.1, QgsUnitTypes.LayoutMillimeters)) l.addItem(item1) # test that guide takes precedence over item s.setSnapToGrid(True) s.setSnapToGuides(True) s.setSnapToItems(True) rect, snapped = s.snapRect(QRectF(1, 1, 2, 3), 1) self.assertTrue(snapped) self.assertEqual(rect, QRectF(0.0, 0.5, 2.0, 3.0)) # but items take precedence over grid s.setSnapToGuides(False) rect, snapped = s.snapRect(QRectF(1, 1, 2, 3), 1) self.assertTrue(snapped) self.assertEqual(rect, QRectF(0.0, 1.1, 2.0, 3.0)) # ... unless item is ignored! rect, snapped = s.snapRect(QRectF(1, 1, 2, 3), 1, None, None, [item1]) self.assertTrue(snapped) self.assertEqual(rect, QRectF(0.0, 0.0, 2.0, 3.0))
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 testStacking(self): p = QgsProject() l = QgsLayout(p) # add some items item1 = QgsLayoutItemPicture(l) l.addLayoutItem(item1) item2 = QgsLayoutItemPicture(l) l.addLayoutItem(item2) item3 = QgsLayoutItemPicture(l) l.addLayoutItem(item3) view = QgsLayoutView() view.setCurrentLayout(l) self.assertEqual(item1.zValue(), 1) self.assertEqual(item2.zValue(), 2) self.assertEqual(item3.zValue(), 3) # no effect interactions view.raiseSelectedItems() view.lowerSelectedItems() view.moveSelectedItemsToTop() view.moveSelectedItemsToBottom() self.assertEqual(item1.zValue(), 1) self.assertEqual(item2.zValue(), 2) self.assertEqual(item3.zValue(), 3) # raising item3.setSelected(True) view.raiseSelectedItems() self.assertEqual(item1.zValue(), 1) self.assertEqual(item2.zValue(), 2) self.assertEqual(item3.zValue(), 3) item3.setSelected(False) item2.setSelected(True) view.raiseSelectedItems() self.assertEqual(item1.zValue(), 1) self.assertEqual(item2.zValue(), 3) self.assertEqual(item3.zValue(), 2) view.raiseSelectedItems() self.assertEqual(item1.zValue(), 1) self.assertEqual(item2.zValue(), 3) self.assertEqual(item3.zValue(), 2) item2.setSelected(False) item1.setSelected(True) view.raiseSelectedItems() self.assertEqual(item1.zValue(), 2) self.assertEqual(item2.zValue(), 3) self.assertEqual(item3.zValue(), 1) # lower item1.setSelected(False) item3.setSelected(True) view.lowerSelectedItems() self.assertEqual(item1.zValue(), 2) self.assertEqual(item2.zValue(), 3) self.assertEqual(item3.zValue(), 1) item3.setSelected(False) item2.setSelected(True) view.lowerSelectedItems() self.assertEqual(item1.zValue(), 3) self.assertEqual(item2.zValue(), 2) self.assertEqual(item3.zValue(), 1) view.lowerSelectedItems() self.assertEqual(item1.zValue(), 3) self.assertEqual(item2.zValue(), 1) self.assertEqual(item3.zValue(), 2) # raise to top item2.setSelected(False) item1.setSelected(True) view.moveSelectedItemsToTop() self.assertEqual(item1.zValue(), 3) self.assertEqual(item2.zValue(), 1) self.assertEqual(item3.zValue(), 2) item1.setSelected(False) item3.setSelected(True) view.moveSelectedItemsToTop() self.assertEqual(item1.zValue(), 2) self.assertEqual(item2.zValue(), 1) self.assertEqual(item3.zValue(), 3) item3.setSelected(False) item2.setSelected(True) view.moveSelectedItemsToTop() self.assertEqual(item1.zValue(), 1) self.assertEqual(item2.zValue(), 3) self.assertEqual(item3.zValue(), 2) # move to bottom item2.setSelected(False) item1.setSelected(True) view.moveSelectedItemsToBottom() self.assertEqual(item1.zValue(), 1) self.assertEqual(item2.zValue(), 3) self.assertEqual(item3.zValue(), 2) item1.setSelected(False) item3.setSelected(True) view.moveSelectedItemsToBottom() self.assertEqual(item1.zValue(), 2) self.assertEqual(item2.zValue(), 3) self.assertEqual(item3.zValue(), 1) item3.setSelected(False) item2.setSelected(True) view.moveSelectedItemsToBottom() self.assertEqual(item1.zValue(), 3) self.assertEqual(item2.zValue(), 1) self.assertEqual(item3.zValue(), 2)
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 testCopyPaste(self): p = QgsProject() l = QgsLayout(p) # clear clipboard mime_data = QMimeData() mime_data.setData("text/xml", QByteArray()) clipboard = QApplication.clipboard() clipboard.setMimeData(mime_data) # add an item item1 = QgsLayoutItemLabel(l) item1.setText('label 1') l.addLayoutItem(item1) item1.setSelected(True) item2 = QgsLayoutItemLabel(l) item2.setText('label 2') l.addLayoutItem(item2) item2.setSelected(True) # multiframes multiframe1 = QgsLayoutItemHtml(l) multiframe1.setHtml('mf1') l.addMultiFrame(multiframe1) frame1 = QgsLayoutFrame(l, multiframe1) frame1.setId('frame1a') multiframe1.addFrame(frame1) frame1b = QgsLayoutFrame(l, multiframe1) frame1b.setId('frame1b') multiframe1.addFrame(frame1b) # not selected frame1c = QgsLayoutFrame(l, multiframe1) frame1c.setId('frame1b') multiframe1.addFrame(frame1c) # not selected multiframe2 = QgsLayoutItemHtml(l) multiframe2.setHtml('mf2') l.addMultiFrame(multiframe2) frame2 = QgsLayoutFrame(l, multiframe2) frame2.setId('frame2') multiframe2.addFrame(frame2) frame1.setSelected(True) frame2.setSelected(True) view = QgsLayoutView() view.setCurrentLayout(l) self.assertFalse(view.hasItemsInClipboard()) view.copySelectedItems(QgsLayoutView.ClipboardCopy) self.assertTrue(view.hasItemsInClipboard()) pasted = view.pasteItems(QgsLayoutView.PasteModeCursor) self.assertEqual(len(pasted), 4) new_multiframes = [ m for m in l.multiFrames() if m not in [multiframe1, multiframe2] ] self.assertEqual(len(new_multiframes), 2) self.assertIn(pasted[0], l.items()) self.assertIn(pasted[1], l.items()) labels = [ p for p in pasted if p.type() == QgsLayoutItemRegistry.LayoutLabel ] self.assertIn( sip.cast(labels[0], QgsLayoutItemLabel).text(), ('label 1', 'label 2')) self.assertIn( sip.cast(labels[1], QgsLayoutItemLabel).text(), ('label 1', 'label 2')) frames = [ p for p in pasted if p.type() == QgsLayoutItemRegistry.LayoutFrame ] pasted_frame1 = sip.cast(frames[0], QgsLayoutFrame) pasted_frame2 = sip.cast(frames[1], QgsLayoutFrame) self.assertIn(pasted_frame1.multiFrame(), new_multiframes) self.assertIn(new_multiframes[0].frames()[0].uuid(), (pasted_frame1.uuid(), pasted_frame2.uuid())) self.assertIn(pasted_frame2.multiFrame(), new_multiframes) self.assertIn(new_multiframes[1].frames()[0].uuid(), (pasted_frame1.uuid(), pasted_frame2.uuid())) self.assertEqual(frame1.multiFrame(), multiframe1) self.assertCountEqual(multiframe1.frames(), [frame1, frame1b, frame1c]) self.assertEqual(frame1b.multiFrame(), multiframe1) self.assertEqual(frame1c.multiFrame(), multiframe1) self.assertEqual(frame2.multiFrame(), multiframe2) self.assertCountEqual(multiframe2.frames(), [frame2]) # copy specific item view.copyItems([item2], QgsLayoutView.ClipboardCopy) l2 = QgsLayout(p) view2 = QgsLayoutView() view2.setCurrentLayout(l2) pasted = view2.pasteItems(QgsLayoutView.PasteModeCursor) self.assertEqual(len(pasted), 1) self.assertIn(pasted[0], l2.items()) self.assertEqual( sip.cast(pasted[0], QgsLayoutItemLabel).text(), 'label 2')
def testCollection(self): p = QgsProject() l = QgsLayout(p) l.initializeDefaults() # add a page guides = l.guides() # no guides initially self.assertEqual(guides.rowCount(QModelIndex()), 0) self.assertFalse( guides.data(QModelIndex(), QgsLayoutGuideCollection.OrientationRole)) self.assertFalse(guides.guides(Qt.Horizontal)) self.assertFalse(guides.guides(Qt.Vertical)) # add a guide g1 = QgsLayoutGuide( Qt.Horizontal, QgsLayoutMeasurement(5, QgsUnitTypes.LayoutCentimeters), l.pageCollection().page(0)) guides.addGuide(g1) self.assertEqual(guides.rowCount(QModelIndex()), 1) self.assertEqual( guides.data(guides.index(0, 0), QgsLayoutGuideCollection.OrientationRole), Qt.Horizontal) self.assertEqual( guides.data(guides.index(0, 0), QgsLayoutGuideCollection.PositionRole), 5) self.assertEqual( guides.data(guides.index(0, 0), QgsLayoutGuideCollection.UnitsRole), QgsUnitTypes.LayoutCentimeters) self.assertEqual( guides.data(guides.index(0, 0), QgsLayoutGuideCollection.PageRole), 0) self.assertEqual(guides.guides(Qt.Horizontal), [g1]) self.assertFalse(guides.guides(Qt.Vertical)) self.assertEqual(guides.guidesOnPage(0), [g1]) self.assertEqual(guides.guidesOnPage(1), []) g2 = QgsLayoutGuide(Qt.Horizontal, QgsLayoutMeasurement(15), l.pageCollection().page(0)) guides.addGuide(g2) self.assertEqual(guides.rowCount(QModelIndex()), 2) self.assertEqual( guides.data(guides.index(1, 0), QgsLayoutGuideCollection.OrientationRole), Qt.Horizontal) self.assertEqual( guides.data(guides.index(1, 0), QgsLayoutGuideCollection.PositionRole), 15) self.assertEqual( guides.data(guides.index(1, 0), QgsLayoutGuideCollection.UnitsRole), QgsUnitTypes.LayoutMillimeters) self.assertEqual( guides.data(guides.index(1, 0), QgsLayoutGuideCollection.PageRole), 0) self.assertEqual(guides.guides(Qt.Horizontal), [g1, g2]) self.assertFalse(guides.guides(Qt.Vertical)) self.assertEqual(guides.guidesOnPage(0), [g1, g2]) page2 = QgsLayoutItemPage(l) page2.setPageSize('A3') l.pageCollection().addPage(page2) g3 = QgsLayoutGuide(Qt.Vertical, QgsLayoutMeasurement(35), l.pageCollection().page(1)) guides.addGuide(g3) self.assertEqual(guides.rowCount(QModelIndex()), 3) self.assertEqual( guides.data(guides.index(2, 0), QgsLayoutGuideCollection.OrientationRole), Qt.Vertical) self.assertEqual( guides.data(guides.index(2, 0), QgsLayoutGuideCollection.PositionRole), 35) self.assertEqual( guides.data(guides.index(2, 0), QgsLayoutGuideCollection.UnitsRole), QgsUnitTypes.LayoutMillimeters) self.assertEqual( guides.data(guides.index(2, 0), QgsLayoutGuideCollection.PageRole), 1) self.assertEqual(guides.guides(Qt.Horizontal), [g1, g2]) self.assertEqual(guides.guides(Qt.Horizontal, 0), [g1, g2]) self.assertEqual(guides.guides(Qt.Horizontal, 1), []) self.assertEqual(guides.guides(Qt.Vertical), [g3]) self.assertEqual(guides.guides(Qt.Vertical, 0), []) self.assertEqual(guides.guides(Qt.Vertical, 1), [g3]) self.assertEqual(guides.guides(Qt.Vertical, 2), []) self.assertEqual(guides.guidesOnPage(0), [g1, g2]) self.assertEqual(guides.guidesOnPage(1), [g3])
def testResizeToContents(self): p = QgsProject() l = QgsLayout(p) shape1 = QgsLayoutItemShape(l) shape1.attemptResize(QgsLayoutSize(90, 50)) shape1.attemptMove(QgsLayoutPoint(90, 50)) shape1.setItemRotation(45, False) l.addLayoutItem(shape1) shape2 = QgsLayoutItemShape(l) shape2.attemptResize(QgsLayoutSize(110, 50)) shape2.attemptMove(QgsLayoutPoint(100, 150), True, False, 0) l.addLayoutItem(shape2) shape3 = QgsLayoutItemShape(l) l.addLayoutItem(shape3) shape3.attemptResize(QgsLayoutSize(50, 100)) shape3.attemptMove(QgsLayoutPoint(210, 250), True, False, 0) shape4 = QgsLayoutItemShape(l) l.addLayoutItem(shape4) shape4.attemptResize(QgsLayoutSize(50, 30)) shape4.attemptMove(QgsLayoutPoint(10, 340), True, False, 0) shape4.setVisibility(False) # resize with no existing pages l.pageCollection().resizeToContents(QgsMargins(1, 2, 3, 4), QgsUnitTypes.LayoutCentimeters) self.assertEqual(l.pageCollection().pageCount(), 1) self.assertAlmostEqual( l.pageCollection().page(0).sizeWithUnits().width(), 290.3, 2) self.assertAlmostEqual( l.pageCollection().page(0).sizeWithUnits().height(), 380.36, 2) self.assertAlmostEqual( l.pageCollection().page(0).sizeWithUnits().units(), QgsUnitTypes.LayoutMillimeters) self.assertAlmostEqual(shape1.positionWithUnits().x(), 90.15, 2) self.assertAlmostEqual(shape1.positionWithUnits().y(), 20.21, 2) self.assertAlmostEqual(shape2.positionWithUnits().x(), 100.15, 2) self.assertAlmostEqual(shape2.positionWithUnits().y(), 120.21, 2) self.assertAlmostEqual(shape3.positionWithUnits().x(), 210.15, 2) self.assertAlmostEqual(shape3.positionWithUnits().y(), 220.21, 2) self.assertAlmostEqual(shape4.positionWithUnits().x(), 10.15, 2) self.assertAlmostEqual(shape4.positionWithUnits().y(), 310.21, 2) # add a second page page2 = QgsLayoutItemPage(l) page2.setPageSize("A4", QgsLayoutItemPage.Landscape) l.pageCollection().addPage(page2) # add some guides g1 = QgsLayoutGuide( Qt.Horizontal, QgsLayoutMeasurement(2.5, QgsUnitTypes.LayoutCentimeters), l.pageCollection().page(0)) l.guides().addGuide(g1) g2 = QgsLayoutGuide( Qt.Vertical, QgsLayoutMeasurement(4.5, QgsUnitTypes.LayoutCentimeters), l.pageCollection().page(0)) l.guides().addGuide(g2) # second page should be removed l.pageCollection().resizeToContents(QgsMargins(0, 0, 0, 0), QgsUnitTypes.LayoutCentimeters) self.assertEqual(l.pageCollection().pageCount(), 1) self.assertAlmostEqual( l.pageCollection().page(0).sizeWithUnits().width(), 250.3, 2) self.assertAlmostEqual( l.pageCollection().page(0).sizeWithUnits().height(), 320.36, 2) self.assertAlmostEqual( l.pageCollection().page(0).sizeWithUnits().units(), QgsUnitTypes.LayoutMillimeters) self.assertAlmostEqual(g1.position().length(), 0.5, 2) self.assertAlmostEqual(g2.position().length(), 3.5, 2)
def testDistribute(self): p = QgsProject() l = QgsLayout(p) # add some items item1 = QgsLayoutItemPicture(l) item1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters)) item1.attemptResize( QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) l.addItem(item1) item2 = QgsLayoutItemPicture(l) item2.attemptMove(QgsLayoutPoint(7, 10, QgsUnitTypes.LayoutMillimeters)) item2.attemptResize( QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters)) l.addItem(item2) item3 = QgsLayoutItemPicture(l) item3.attemptMove( QgsLayoutPoint(0.8, 1.2, QgsUnitTypes.LayoutCentimeters)) item3.attemptResize( QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters)) l.addItem(item3) QgsLayoutAligner.distributeItems(l, [item1, item2, item3], QgsLayoutAligner.DistributeLeft) self.assertEqual(item1.positionWithUnits(), QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) self.assertAlmostEqual(item2.positionWithUnits().x(), 6.0, 3) self.assertEqual(item2.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters) self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters)) self.assertAlmostEqual(item3.positionWithUnits().x(), 0.8, 3) self.assertEqual(item3.positionWithUnits().units(), QgsUnitTypes.LayoutCentimeters) self.assertEqual( item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters)) QgsLayoutAligner.distributeItems(l, [item1, item2, item3], QgsLayoutAligner.DistributeHCenter) self.assertAlmostEqual(item1.positionWithUnits().x(), 5.0, 3) self.assertEqual(item1.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters) self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) self.assertAlmostEqual(item2.positionWithUnits().x(), 6.0, 3) self.assertEqual(item2.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters) self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters)) self.assertAlmostEqual(item3.positionWithUnits().x(), 0.8, 3) self.assertEqual(item3.positionWithUnits().units(), QgsUnitTypes.LayoutCentimeters) self.assertEqual( item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters)) QgsLayoutAligner.distributeItems(l, [item1, item2, item3], QgsLayoutAligner.DistributeRight) self.assertAlmostEqual(item1.positionWithUnits().x(), 3.0, 3) self.assertEqual(item1.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters) self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) self.assertAlmostEqual(item2.positionWithUnits().x(), 6.0, 3) self.assertEqual(item2.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters) self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters)) self.assertAlmostEqual(item3.positionWithUnits().x(), 0.8, 3) self.assertEqual(item3.positionWithUnits().units(), QgsUnitTypes.LayoutCentimeters) self.assertEqual( item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters)) QgsLayoutAligner.distributeItems(l, [item1, item2, item3], QgsLayoutAligner.DistributeTop) self.assertAlmostEqual(item1.positionWithUnits().y(), 8.0, 3) self.assertEqual(item1.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters) self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) self.assertAlmostEqual(item2.positionWithUnits().y(), 10.0, 3) self.assertEqual(item2.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters) self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters)) self.assertAlmostEqual(item3.positionWithUnits().y(), 1.2, 3) self.assertEqual(item3.positionWithUnits().units(), QgsUnitTypes.LayoutCentimeters) self.assertEqual( item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters)) QgsLayoutAligner.distributeItems(l, [item1, item2, item3], QgsLayoutAligner.DistributeVCenter) self.assertAlmostEqual(item1.positionWithUnits().y(), 8.0, 3) self.assertEqual(item1.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters) self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) self.assertAlmostEqual(item2.positionWithUnits().y(), 12.5, 3) self.assertEqual(item2.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters) self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters)) self.assertAlmostEqual(item3.positionWithUnits().y(), 1.2, 3) self.assertEqual(item3.positionWithUnits().units(), QgsUnitTypes.LayoutCentimeters) self.assertEqual( item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters)) QgsLayoutAligner.distributeItems(l, [item1, item2, item3], QgsLayoutAligner.DistributeBottom) self.assertAlmostEqual(item1.positionWithUnits().y(), 8.0, 3) self.assertEqual(item1.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters) self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) self.assertAlmostEqual(item2.positionWithUnits().y(), 15.0, 3) self.assertEqual(item2.positionWithUnits().units(), QgsUnitTypes.LayoutMillimeters) self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters)) self.assertAlmostEqual(item3.positionWithUnits().y(), 1.2, 3) self.assertEqual(item3.positionWithUnits().units(), QgsUnitTypes.LayoutCentimeters) self.assertEqual( item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters))
def testLayout(self): # test that layouts have a collection p = QgsProject() l = QgsLayout(p) self.assertTrue(l.pageCollection()) self.assertEqual(l.pageCollection().layout(), l)
def testAlign(self): p = QgsProject() l = QgsLayout(p) # add some items item1 = QgsLayoutItemPicture(l) item1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters)) item1.attemptResize( QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) l.addItem(item1) item2 = QgsLayoutItemPicture(l) item2.attemptMove(QgsLayoutPoint(6, 10, QgsUnitTypes.LayoutMillimeters)) item2.attemptResize( QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters)) l.addItem(item2) item3 = QgsLayoutItemPicture(l) item3.attemptMove( QgsLayoutPoint(0.8, 1.2, QgsUnitTypes.LayoutCentimeters)) item3.attemptResize( QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters)) l.addItem(item3) QgsLayoutAligner.alignItems(l, [item1, item2, item3], QgsLayoutAligner.AlignLeft) self.assertEqual(item1.positionWithUnits(), QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item2.positionWithUnits(), QgsLayoutPoint(4, 10, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters)) self.assertEqual( item3.positionWithUnits(), QgsLayoutPoint(0.4, 1.2, QgsUnitTypes.LayoutCentimeters)) self.assertEqual( item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters)) QgsLayoutAligner.alignItems(l, [item1, item2, item3], QgsLayoutAligner.AlignHCenter) self.assertEqual(item1.positionWithUnits(), QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item2.positionWithUnits(), QgsLayoutPoint(8, 10, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters)) self.assertEqual( item3.positionWithUnits(), QgsLayoutPoint(0.4, 1.2, QgsUnitTypes.LayoutCentimeters)) self.assertEqual( item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters)) QgsLayoutAligner.alignItems(l, [item1, item2, item3], QgsLayoutAligner.AlignRight) self.assertEqual(item1.positionWithUnits(), QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) self.assertEqual( item2.positionWithUnits(), QgsLayoutPoint(12, 10, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters)) self.assertEqual( item3.positionWithUnits(), QgsLayoutPoint(0.4, 1.2, QgsUnitTypes.LayoutCentimeters)) self.assertEqual( item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters)) QgsLayoutAligner.alignItems(l, [item1, item2, item3], QgsLayoutAligner.AlignTop) self.assertEqual(item1.positionWithUnits(), QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item2.positionWithUnits(), QgsLayoutPoint(12, 8, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters)) self.assertEqual( item3.positionWithUnits(), QgsLayoutPoint(0.4, 0.8, QgsUnitTypes.LayoutCentimeters)) self.assertEqual( item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters)) QgsLayoutAligner.alignItems(l, [item1, item2, item3], QgsLayoutAligner.AlignVCenter) self.assertEqual(item1.positionWithUnits(), QgsLayoutPoint(4, 10, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) self.assertEqual( item2.positionWithUnits(), QgsLayoutPoint(12, 11.5, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters)) self.assertEqual( item3.positionWithUnits(), QgsLayoutPoint(0.4, 0.8, QgsUnitTypes.LayoutCentimeters)) self.assertEqual( item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters)) QgsLayoutAligner.alignItems(l, [item1, item2, item3], QgsLayoutAligner.AlignBottom) self.assertEqual(item1.positionWithUnits(), QgsLayoutPoint(4, 12, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item1.sizeWithUnits(), QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) self.assertEqual( item2.positionWithUnits(), QgsLayoutPoint(12, 15, QgsUnitTypes.LayoutMillimeters)) self.assertEqual(item2.sizeWithUnits(), QgsLayoutSize(10, 9, QgsUnitTypes.LayoutMillimeters)) self.assertEqual( item3.positionWithUnits(), QgsLayoutPoint(0.4, 0.8, QgsUnitTypes.LayoutCentimeters)) self.assertEqual( item3.sizeWithUnits(), QgsLayoutSize(1.8, 1.6, QgsUnitTypes.LayoutCentimeters))
def testPredictionPageNumberForPoint(self): """ Test predictPageNumberForPoint """ p = QgsProject() l = QgsLayout(p) collection = l.pageCollection() # add a page page = QgsLayoutItemPage(l) page.setPageSize(QgsLayoutSize(100, 100)) collection.addPage(page) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, -100)), 0) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, -1)), 0) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, 20)), 0) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, 120)), 1) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, 230)), 2) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, 350)), 3) page2 = QgsLayoutItemPage(l) page2.setPageSize(QgsLayoutSize(100, 50)) collection.addPage(page2) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, -100)), 0) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, -1)), 0) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, 20)), 0) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, 120)), 1) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, 230)), 2) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, 280)), 3) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, 340)), 4) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, 370)), 5) page3 = QgsLayoutItemPage(l) page3.setPageSize(QgsLayoutSize(100, 200)) collection.addPage(page3) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, -100)), 0) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, -1)), 0) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, 20)), 0) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, 120)), 1) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, 230)), 2) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, 280)), 2) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, 340)), 2) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, 370)), 2) self.assertEqual( collection.predictPageNumberForPoint(QPointF(-100, 470)), 3)
def testExportToPdf(self): md = QgsProject.instance().metadata() md.setTitle('proj title') md.setAuthor('proj author') md.setCreationDateTime( QDateTime(QDate(2011, 5, 3), QTime(9, 4, 5), QTimeZone(36000))) md.setIdentifier('proj identifier') md.setAbstract('proj abstract') md.setKeywords({'kw': ['kw1', 'kw2'], 'KWx': ['kw3', 'kw4']}) QgsProject.instance().setMetadata(md) l = QgsLayout(QgsProject.instance()) l.initializeDefaults() # add a second page page2 = QgsLayoutItemPage(l) page2.setPageSize('A5') l.pageCollection().addPage(page2) # add some items item1 = QgsLayoutItemShape(l) item1.attemptSetSceneRect(QRectF(10, 20, 100, 150)) fill = QgsSimpleFillSymbolLayer() fill_symbol = QgsFillSymbol() fill_symbol.changeSymbolLayer(0, fill) fill.setColor(Qt.green) fill.setStrokeStyle(Qt.NoPen) item1.setSymbol(fill_symbol) l.addItem(item1) item2 = QgsLayoutItemShape(l) item2.attemptSetSceneRect(QRectF(10, 20, 100, 150)) item2.attemptMove(QgsLayoutPoint(10, 20), page=1) fill = QgsSimpleFillSymbolLayer() fill_symbol = QgsFillSymbol() fill_symbol.changeSymbolLayer(0, fill) fill.setColor(Qt.cyan) fill.setStrokeStyle(Qt.NoPen) item2.setSymbol(fill_symbol) l.addItem(item2) exporter = QgsLayoutExporter(l) # setup settings settings = QgsLayoutExporter.PdfExportSettings() settings.dpi = 80 settings.rasterizeWholeImage = False settings.forceVectorOutput = False settings.exportMetadata = True pdf_file_path = os.path.join(self.basetestpath, 'test_exporttopdfdpi.pdf') self.assertEqual(exporter.exportToPdf(pdf_file_path, settings), QgsLayoutExporter.Success) self.assertTrue(os.path.exists(pdf_file_path)) rendered_page_1 = os.path.join(self.basetestpath, 'test_exporttopdfdpi.png') dpi = 80 pdfToPng(pdf_file_path, rendered_page_1, dpi=dpi, page=1) rendered_page_2 = os.path.join(self.basetestpath, 'test_exporttopdfdpi2.png') pdfToPng(pdf_file_path, rendered_page_2, dpi=dpi, page=2) self.assertTrue( self.checkImage('exporttopdfdpi_page1', 'exporttopdfdpi_page1', rendered_page_1, size_tolerance=1)) self.assertTrue( self.checkImage('exporttopdfdpi_page2', 'exporttopdfdpi_page2', rendered_page_2, size_tolerance=1)) d = gdal.Open(pdf_file_path) metadata = d.GetMetadata() self.assertEqual(metadata['AUTHOR'], 'proj author') self.assertEqual(metadata['CREATION_DATE'], "D:20110503090405+10'0'") self.assertEqual(metadata['KEYWORDS'], 'KWx: kw3,kw4;kw: kw1,kw2') self.assertEqual(metadata['SUBJECT'], 'proj abstract') self.assertEqual(metadata['TITLE'], 'proj title')
def testPages(self): """ Test adding/retrieving/deleting pages from the collection """ p = QgsProject() l = QgsLayout(p) collection = l.pageCollection() self.assertEqual(collection.pageCount(), 0) self.assertFalse(collection.pages()) self.assertFalse(collection.page(-1)) self.assertFalse(collection.page(0)) self.assertFalse(collection.page(1)) # add a page page = QgsLayoutItemPage(l) page.setPageSize('A4') self.assertEqual(collection.pageNumber(page), -1) collection.addPage(page) self.assertTrue(page in l.items()) self.assertEqual(collection.pageCount(), 1) self.assertEqual(collection.pages(), [page]) self.assertFalse(collection.page(-1)) self.assertEqual(collection.page(0), page) self.assertFalse(collection.page(1)) self.assertEqual(collection.pageNumber(page), 0) # add a second page page2 = QgsLayoutItemPage(l) page2.setPageSize('A5') collection.addPage(page2) self.assertEqual(collection.pageCount(), 2) self.assertEqual(collection.pages(), [page, page2]) self.assertFalse(collection.page(-1)) self.assertEqual(collection.page(0), page) self.assertEqual(collection.page(1), page2) self.assertEqual(collection.pageNumber(page2), 1) # insert a page page3 = QgsLayoutItemPage(l) page3.setPageSize('A3') collection.insertPage(page3, 1) self.assertTrue(page3 in l.items()) self.assertEqual(collection.pageCount(), 3) self.assertEqual(collection.pages(), [page, page3, page2]) self.assertEqual(collection.page(0), page) self.assertEqual(collection.page(1), page3) self.assertEqual(collection.page(2), page2) self.assertEqual(collection.pageNumber(page3), 1) # delete page collection.deletePage(-1) self.assertEqual(collection.pageCount(), 3) self.assertEqual(collection.pages(), [page, page3, page2]) collection.deletePage(100) self.assertEqual(collection.pageCount(), 3) self.assertEqual(collection.pages(), [page, page3, page2]) collection.deletePage(1) self.assertEqual(collection.pageCount(), 2) self.assertEqual(collection.pages(), [page, page2]) # make sure page was deleted QCoreApplication.sendPostedEvents(None, QEvent.DeferredDelete) self.assertTrue(sip.isdeleted(page3)) del l QCoreApplication.sendPostedEvents(None, QEvent.DeferredDelete) self.assertTrue(sip.isdeleted(page)) self.assertTrue(sip.isdeleted(page2))
def testPrint(self): l = QgsLayout(QgsProject.instance()) l.initializeDefaults() # add a second page page2 = QgsLayoutItemPage(l) page2.setPageSize('A5') l.pageCollection().addPage(page2) # add some items item1 = QgsLayoutItemShape(l) item1.attemptSetSceneRect(QRectF(10, 20, 100, 150)) fill = QgsSimpleFillSymbolLayer() fill_symbol = QgsFillSymbol() fill_symbol.changeSymbolLayer(0, fill) fill.setColor(Qt.green) fill.setStrokeStyle(Qt.NoPen) item1.setSymbol(fill_symbol) l.addItem(item1) item2 = QgsLayoutItemShape(l) item2.attemptSetSceneRect(QRectF(10, 20, 100, 150)) item2.attemptMove(QgsLayoutPoint(10, 20), page=1) fill = QgsSimpleFillSymbolLayer() fill_symbol = QgsFillSymbol() fill_symbol.changeSymbolLayer(0, fill) fill.setColor(Qt.cyan) fill.setStrokeStyle(Qt.NoPen) item2.setSymbol(fill_symbol) l.addItem(item2) exporter = QgsLayoutExporter(l) # setup settings settings = QgsLayoutExporter.PrintExportSettings() settings.dpi = 80 settings.rasterizeWholeImage = False pdf_file_path = os.path.join(self.basetestpath, 'test_printdpi.pdf') # make a qprinter directed to pdf printer = QPrinter() printer.setOutputFileName(pdf_file_path) printer.setOutputFormat(QPrinter.PdfFormat) self.assertEqual(exporter.print(printer, settings), QgsLayoutExporter.Success) self.assertTrue(os.path.exists(pdf_file_path)) rendered_page_1 = os.path.join(self.basetestpath, 'test_exporttopdfdpi.png') dpi = 80 pdfToPng(pdf_file_path, rendered_page_1, dpi=dpi, page=1) rendered_page_2 = os.path.join(self.basetestpath, 'test_exporttopdfdpi2.png') pdfToPng(pdf_file_path, rendered_page_2, dpi=dpi, page=2) self.assertTrue( self.checkImage('printdpi_page1', 'exporttopdfdpi_page1', rendered_page_1, size_tolerance=1)) self.assertTrue( self.checkImage('printdpi_page2', 'exporttopdfdpi_page2', rendered_page_2, size_tolerance=1))
def testPagePositionToAbsolute(self): """ Test pagePositionToAbsolute """ p = QgsProject() l = QgsLayout(p) collection = l.pageCollection() # invalid pages self.assertEqual( collection.pagePositionToAbsolute(-1, QgsLayoutPoint(1, 1)), QgsLayoutPoint(1, 1)) self.assertEqual( collection.pagePositionToAbsolute(0, QgsLayoutPoint(1, 1)), QgsLayoutPoint(1, 1)) self.assertEqual( collection.pagePositionToAbsolute(100, QgsLayoutPoint(1, 1)), QgsLayoutPoint(1, 1)) # add a page page = QgsLayoutItemPage(l) page.setPageSize('A4') collection.addPage(page) #invalid pages self.assertEqual( collection.pagePositionToAbsolute(-1, QgsLayoutPoint(1, 1)), QgsLayoutPoint(1, 1)) self.assertEqual( collection.pagePositionToAbsolute(1, QgsLayoutPoint(1, 1)), QgsLayoutPoint(1, 1)) #valid page self.assertEqual( collection.pagePositionToAbsolute(0, QgsLayoutPoint(1, 1)), QgsLayoutPoint(1, 1)) self.assertEqual( collection.pagePositionToAbsolute(0, QgsLayoutPoint(5, 6)), QgsLayoutPoint(5, 6)) self.assertEqual( collection.pagePositionToAbsolute( 0, QgsLayoutPoint(5, 6, QgsUnitTypes.LayoutCentimeters)), QgsLayoutPoint(5, 6, QgsUnitTypes.LayoutCentimeters)) page2 = QgsLayoutItemPage(l) page2.setPageSize('A5') collection.addPage(page2) #invalid pages self.assertEqual( collection.pagePositionToAbsolute(-1, QgsLayoutPoint(1, 1)), QgsLayoutPoint(1, 1)) self.assertEqual( collection.pagePositionToAbsolute(3, QgsLayoutPoint(1, 1)), QgsLayoutPoint(1, 1)) #valid pages self.assertEqual( collection.pagePositionToAbsolute(0, QgsLayoutPoint(1, 1)), QgsLayoutPoint(1, 1)) self.assertEqual( collection.pagePositionToAbsolute(0, QgsLayoutPoint(5, 6)), QgsLayoutPoint(5, 6)) self.assertEqual( collection.pagePositionToAbsolute( 0, QgsLayoutPoint(5, 6, QgsUnitTypes.LayoutCentimeters)), QgsLayoutPoint(5, 6, QgsUnitTypes.LayoutCentimeters)) self.assertEqual( collection.pagePositionToAbsolute(1, QgsLayoutPoint(1, 1)), QgsLayoutPoint(1, 308.0)) self.assertEqual( collection.pagePositionToAbsolute(1, QgsLayoutPoint(5, 6)), QgsLayoutPoint(5, 313.0)) self.assertEqual( collection.pagePositionToAbsolute( 1, QgsLayoutPoint(0.5, 0.6, QgsUnitTypes.LayoutCentimeters)), QgsLayoutPoint(0.5, 31.3, QgsUnitTypes.LayoutCentimeters))
def testInitialSizeSymbolMapUnits(self): """Test initial size of legend with a symbol size in map units""" point_path = os.path.join(TEST_DATA_DIR, 'points.shp') point_layer = QgsVectorLayer(point_path, 'points', 'ogr') QgsProject.instance().addMapLayers([point_layer]) marker_symbol = QgsMarkerSymbol.createSimple({ 'color': '#ff0000', 'outline_style': 'no', 'size': '5', 'size_unit': 'MapUnit' }) point_layer.setRenderer(QgsSingleSymbolRenderer(marker_symbol)) s = QgsMapSettings() s.setLayers([point_layer]) layout = QgsLayout(QgsProject.instance()) layout.initializeDefaults() map = QgsLayoutItemMap(layout) map.attemptSetSceneRect(QRectF(20, 20, 80, 80)) map.setFrameEnabled(True) map.setLayers([point_layer]) layout.addLayoutItem(map) map.setExtent(point_layer.extent()) legend = QgsLayoutItemLegend(layout) legend.setTitle("Legend") legend.attemptSetSceneRect(QRectF(120, 20, 80, 80)) legend.setFrameEnabled(True) legend.setFrameStrokeWidth(QgsLayoutMeasurement(2)) legend.setBackgroundColor(QColor(200, 200, 200)) legend.setTitle('') layout.addLayoutItem(legend) legend.setLinkedMap(map) checker = QgsLayoutChecker('composer_legend_mapunits', layout) checker.setControlPathPrefix("composer_legend") result, message = checker.testLayout() self.assertTrue(result, message) # resize with non-top-left reference point legend.setResizeToContents(False) legend.setReferencePoint(QgsLayoutItem.LowerRight) legend.attemptMove(QgsLayoutPoint(120, 90)) legend.attemptResize(QgsLayoutSize(50, 60)) self.assertEqual(legend.positionWithUnits().x(), 120.0) self.assertEqual(legend.positionWithUnits().y(), 90.0) self.assertAlmostEqual(legend.pos().x(), 70, -1) self.assertAlmostEqual(legend.pos().y(), 30, -1) legend.setResizeToContents(True) legend.updateLegend() self.assertEqual(legend.positionWithUnits().x(), 120.0) self.assertEqual(legend.positionWithUnits().y(), 90.0) self.assertAlmostEqual(legend.pos().x(), 91, -1) self.assertAlmostEqual(legend.pos().y(), 71, -1) QgsProject.instance().removeMapLayers([point_layer.id()])
def testSnapPointsToItems(self): p = QgsProject() l = QgsLayout(p) page = QgsLayoutItemPage(l) page.setPageSize('A4') #l.pageCollection().addPage(page) s = QgsLayoutSnapper(l) guides = l.guides() s.setSnapToItems(True) s.setSnapTolerance(1) # no items point, snapped = s.snapPointsToItems([0.5], Qt.Horizontal, 1, []) self.assertFalse(snapped) line = QGraphicsLineItem() line.setVisible(True) point, snapped = s.snapPointsToItems([0.5], Qt.Horizontal, 1, [], line) self.assertFalse(line.isVisible()) guides.addGuide( QgsLayoutGuide(Qt.Vertical, QgsLayoutMeasurement(1), page)) # add an item item1 = QgsLayoutItemMap(l) item1.attemptMove(QgsLayoutPoint(4, 8, QgsUnitTypes.LayoutMillimeters)) item1.attemptResize( QgsLayoutSize(18, 12, QgsUnitTypes.LayoutMillimeters)) l.addItem(item1) point, snapped = s.snapPointsToItems([3.5], Qt.Horizontal, 1, [], line) self.assertTrue(snapped) self.assertEqual(point, 0.5) self.assertTrue(line.isVisible()) point, snapped = s.snapPointsToItems([4.5], Qt.Horizontal, 1, []) self.assertTrue(snapped) self.assertEqual(point, -0.5) point, snapped = s.snapPointsToItems([4.6, 4.5], Qt.Horizontal, 1, []) self.assertTrue(snapped) self.assertEqual(point, -0.5) point, snapped = s.snapPointsToItems([4.6, 4.5, 3.7], Qt.Horizontal, 1, []) self.assertTrue(snapped) self.assertAlmostEqual(point, 0.3, 5) # ignoring item point, snapped = s.snapPointsToItems([4.5], Qt.Horizontal, 1, [item1]) self.assertFalse(snapped) # outside tolerance point, snapped = s.snapPointsToItems([5.5], Qt.Horizontal, 1, [], line) self.assertFalse(snapped) self.assertFalse(line.isVisible()) # snap to center point, snapped = s.snapPointsToItems([12.5], Qt.Horizontal, 1, []) self.assertTrue(snapped) self.assertEqual(point, 0.5) # snap to right point, snapped = s.snapPointsToItems([22.5], Qt.Horizontal, 1, []) self.assertTrue(snapped) self.assertEqual(point, -0.5) #snap to top point, snapped = s.snapPointsToItems([7.5], Qt.Vertical, 1, [], line) self.assertTrue(snapped) self.assertEqual(point, 0.5) self.assertTrue(line.isVisible()) point, snapped = s.snapPointsToItems([8.5], Qt.Vertical, 1, []) self.assertTrue(snapped) self.assertEqual(point, -0.5) # outside tolerance point, snapped = s.snapPointsToItems([5.5], Qt.Vertical, 1, [], line) self.assertFalse(snapped) self.assertFalse(line.isVisible()) # snap to center point, snapped = s.snapPointsToItems([13.5], Qt.Vertical, 1, []) self.assertTrue(snapped) self.assertEqual(point, 0.5) # snap to bottom point, snapped = s.snapPointsToItems([20.5], Qt.Vertical, 1, []) self.assertTrue(snapped) self.assertEqual(point, -0.5) # snapping off s.setSnapToItems(False) line.setVisible(True) point, snapped = s.snapPointsToItems([20.5], Qt.Vertical, 1, [], line) self.assertFalse(snapped) self.assertFalse(line.isVisible()) # with different pixel scale s.setSnapToItems(True) point, snapped = s.snapPointsToItems([20.5], Qt.Vertical, 3, []) self.assertFalse(snapped)