I have created a print layout with some of the layers of my QGIS Project using PyQGIS. I am trying to add a gradient filled rectangle to the layout. In the GUI, I would use the "Add Shape" --> "Add Rectangle" tool, drag the shape to the desired location, and use the "Item Properties" to fill with a gradient. However, I am having difficulties reproducing the shape programmatically.
To create the Layout, I use the following code:
project = QgsProject.instance()
manager = project.layoutManager()
layout = QgsPrintLayout(project)
layoutName = "Some_name"
# The next step allows the script to run multiple times without naming issues
layouts_list = manager.printLayouts()
for layout in layouts_list:
if layout.name() == layoutName:
manager.removeLayout(layout)
layout.initializeDefaults()
layout.setName(layoutName)
manager.addLayout(layout)
After having added my layers, I tried to add a polygon:
# Make a polygon from coordinates (in layout)
# The coordinates are in the layout units
xmin = 20
xmax = 40
ymin = 20
ymax = 60
polygon = QPolygonF()
polygon.append(QPointF(xmin, ymin))
polygon.append(QPointF(xmax, ymin))
polygon.append(QPointF(xmax, ymax))
polygon.append(QPointF(xmin, ymax))
# Create the polygon from nodes
polygonItem = QgsLayoutItemPolygon(polygon, layoutname)
# Add to the layout
layout.addItem(polygonItem)
# Style properties
props = {}
props["color"] = "green"
props["style"] = "solid"
props["style_border"] = "solid"
props["color_border"] = "black"
props["width_border"] = "0.26"
props["joinstyle"] = "miter"
# Create symbolfiller from properties
symbol = QgsFillSymbol.createSimple(props)
polygonItem.setSymbol(symbol)
This approach allows me to create a filled polygon. I cannot find the method to fill the polygon with a gradient, and I haven't yet found the list of options that can be set in the parameter dictionary. I also tried to replace the QgsFillSymbol with QgsGradientFillSymbolLayer, but to no avail.
symbol.symbolLayer(0).setStrokeColor(QColor(255,255,1))to set the stroke colour. – Joseph Sep 17 '19 at 09:56