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:


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

# 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)

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.


After you defined symbol, just add the following line immediately after to create a gradient brush style:


So it looks like:

# Create symbolfiller from properties
symbol = QgsFillSymbol.createSimple(props)

You can check the method of looking at other properties in this post: Change vector layer symbology PyQGIS 3?

| improve this answer | |
  • I can fill the rectangle with hashed lines (Qt.FDiagPattern), or a solid color, but I cannot get a linear gradient to work. I have tried with Qt.LinearGradientPattern, but cannot set the colors, leaving the rectangle blank. Do you have a suggestion? – Maxim L Sep 16 '19 at 11:21
  • @MaximL - Try using something like symbol.symbolLayer(0).setStrokeColor(QColor(255,255,1)) to set the stroke colour. – Joseph Sep 17 '19 at 9:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.