0

I would like to add and modify and expression for Opacity in a QGraphicsLineItem

when I have the item QGraphicsLineItem, it not have a variable to modify the opacity expression

Code to get the item:

QgsProject.instance().layoutManager().layouts()[0].items()[0]
3
  • QGraphicsLineItem doesn't have a direct method to set opacity. Opacity is controlled via the QPen used to draw the line. Commented Aug 14, 2023 at 18:24
  • @iskandarblue, I understand you, but how can I modify a qgsexpression by PyQGIS in this case ? Commented Aug 14, 2023 at 18:27
  • @iskandarblue, the QGraphicsLineItem is a child of QGraphicsItem, that have the opacity attribute, right ? Commented Aug 14, 2023 at 18:28

2 Answers 2

1

I found the solution to read and modify the opacity expression for any item of the Layout in the following way:

items = QgsProject.instance().layoutManager().layouts()[0].items()

for item in items:
    # Visualize the current expression
    expression = item.dataDefinedProperties().property(QgsLayoutObject.Opacity).asExpression()
    print(expression)

    # Modify the previous expression of Opacity
    item.dataDefinedProperties().property(QgsLayoutObject.Opacity).setExpressionString('if(@atlas_pagename = 6, 100, 0)')

    # Visualize the modified expression
    print(item.dataDefinedProperties().property(QgsLayoutObject.Opacity).asExpression())
0

You could try this:

from PyQt6.QtGui import QPen, QColor
from PyQt6.QtWidgets import QGraphicsLineItem

line_item = QgsProject.instance().layoutManager().layouts()[0].items()[0]

pen = line_item.pen()

color = pen.color()
color.setAlpha(128)  # Set to 50% opacity

pen.setColor(color)
line_item.setPen(pen)
1
  • You may change your imports e.g from qgis.PyQt.QtGui import QPen, QColor and from qgis.PyQt.QtWidgets import QGraphicsLineItem for portability among QGIS 3.x versions and associated Qt installed versions.
    – ThomasG77
    Commented Aug 14, 2023 at 19:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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