I wrote a processing script that creates a layer and adds it to the current project:
class TestAlgorithm(QgsProcessingAlgorithm):
def initAlgorithm(self, config=None):
self.addParameter(QgsProcessingParameterFileDestination('output_layer', 'Save Output Layer', fileFilter='GeoPackage (*.gpkg *GPKG)'))
def processAlgorithm(self, parameters, context, model_feedback):
# Use a multi-step feedback, so that individual child algorithm progress reports are adjusted for the
# overall progress through the model
feedback = QgsProcessingMultiStepFeedback(1, model_feedback)
results = {}
outputs = {}
root = QgsProject.instance().layerTreeRoot()
Layer_1= QgsVectorLayer("Point", "Layer_1", "memory")
Layer_1.dataProvider().addAttributes([
QgsField("Field_1", QVariant.String),
QgsField("Field_2", QVariant.String)
])
Layer_1.updateFields()
CRS = QgsCoordinateReferenceSystem("EPSG:25832")
Layer_1.setCrs(CRS)
layer_list = [Layer_1]
params = {'LAYERS': layer_list,
'OUTPUT': parameters['output_layer'],
'OVERWRITE': False,
'SAVE_STYLES': False,
'SAVE_METADATA': True,
'SELECTED_FEATURES_ONLY': False}
ALG_1 = processing.run("native:package", params, is_child_algorithm=True)
layer_list = [l.GetName() for l in ogr.Open(ALG_1['OUTPUT'])]
for layer in layer_list:
source= os.path.join(ALG_1['OUTPUT'] + "|layername=" + layer)
export = QgsVectorLayer(source, 'export_layer', "ogr")
QgsProject.instance().addMapLayer(export, False)
root.insertLayer(0, export)
feedback.setCurrentStep(1)
if feedback.isCanceled():
return {}
return results
def name(self):
return 'Test'
def displayName(self):
"""
Returns the translated algorithm name, which should be used for any
user-visible display of the algorithm name.
"""
return 'Test'
def createInstance(self):
return TestAlgorithm()
After the layer has been added to the project, I want to add the following custom action to the context menu of this layer, to be able to switch quickly between different styles:
act = QAction(u"Load MyStyle1")
act2 = QAction(u"Load MyStyle2")
def run1():
layer = QgsProject.instance().mapLayersByName('export_layer')[0]
style_1 = '[folder path to my_style_1.qml]'
layer.loadNamedStyle(style_1)
layer.triggerRepaint()
act.triggered.connect(run1)
def run2():
layer = QgsProject.instance().mapLayersByName('export_layer')[0]
style_2 = '[folder path to my_style_2.qml]'
layer.loadNamedStyle(style_2)
layer.triggerRepaint()
act2.triggered.connect(run2)
layer = QgsProject.instance().mapLayersByName('export_layer')[0]
iface.addCustomActionForLayerType(act,'Load MyStyle1',QgsMapLayerType.VectorLayer,False)
iface.addCustomActionForLayerType(act2,'Load MyStyle2',QgsMapLayerType.VectorLayer,False)
iface.addCustomActionForLayer(act,layer)
iface.addCustomActionForLayer(act2,layer)
Both scripts work on their own, but I haven't succeeded to combine them into one. The problem seems to be that the export_layer has to exist before the actions can be added. Where do I have to put the second part to make it work? Within the processing algorithm class or outside of it?

act1 = QAction("Load MyStyle1", iface.mainWindow())and then call it withact1.triggered.connect(run1)? Theiface.mainWindow()is passed toQActionto register the action with the QGIS interface.iface.mainWindow()what I was missing.