I'm trying to change the style of all my DXF layers using the QgsProject layersAdded
signal while adding the layers to QGIS 3.28.1 (Windows).
For this purpose I wrote some lines of Python macro code and inserted it into one of my projects:
from qgis.utils import iface
from qgis.core import QgsProject
def loadDxfStyle(layers):
style = 'C:/OSGeo4W/styles/dxf.qml'
for lay in layers:
if '.dxf' in lay.source():
print(lay.source())
lay.loadNamedStyle(style)
lay.triggerRepaint()
iface.layerTreeView().refreshLayerSymbology(lay.id())
def openProject():
QgsProject.instance().layersAdded.connect(loadDxfStyle)
def saveProject():
pass
def closeProject():
QgsProject.instance().layersAdded.disconnect(loadDxfStyle)
The layer sources are always printed to the console, but the style is never changed.
What am I doing wrong here?
UPDATE:
I changed the code to use the processing algorithm native:setlayerstyle
, but this doesn't change anything. When I pause the script after setting the style, I can see that the style was changed. But after the timer ends the style changes are automatically overwritten.
from qgis.utils import iface
from qgis.core import QgsProject
from qgis.PyQt.QtCore import QTimer,QEventLoop
import processing
def wait():
loop = QEventLoop()
QTimer.singleShot(5000,loop.quit)
loop.exec_()
def loadDxfStyle(layers):
style = 'C:/OSGeo4W/styles/dxf.qml'
for lay in layers:
if '.dxf' in lay.source():
processing.run("native:setlayerstyle",{"INPUT":lay.id(),"STYLE":style})
wait()
def openProject():
QgsProject.instance().layersAdded.connect(loadDxfStyle)
def saveProject():
pass
def closeProject():
QgsProject.instance().layersAdded.disconnect(loadDxfStyle)
Is it perhaps possible to run the processing alg in another thread using asyncio after the layer import is finished?
layersAdded
signal is a bit weird as it triggers not really after the layers are "fully" added to QGIS but at some earlier stage.