I am trying to run a processing script without a user defined layer output. The example below should create a vector layer with one point. The script runs without any error but the layertree is empty. If you run an other script afterwards, for example "Buffer" the layer is available and you can buffer the result from the script below.
What do I miss to make the created layer available for the layertree? My guess is that QgsProject.instance().addMapLayer(vl) does not work with the alg class? I know that the correct usage of the processing script would be using a QgsFeatureSink, but I am trying to do it the way below to get more control over the result layer.
from qgis.processing import alg
from qgis.PyQt.QtCore import QVariant
from qgis.core import QgsProject, QgsFeature, QgsField, QgsGeometry, QgsPointXY, QgsVectorLayer
@alg(name="test123", label=alg.tr("test123"), group="geophysics", group_label=alg.tr("Geophysics"))
@alg.output(type=alg.NUMBER, name="OUTPUT", label='Number of features processed')
def test123(instance, parameters, context, feedback, inputs):
"""
tries to add a vectorlayer through a processing script
"""
vl = QgsVectorLayer("Point", "Hello", "memory")
pr = vl.dataProvider()
pr.addAttributes([QgsField("name", QVariant.String),
QgsField("field1", QVariant.Int),
QgsField("field2", QVariant.Double)])
vl.updateFields()
f = QgsFeature()
f.setGeometry(QgsGeometry.fromPointXY(QgsPointXY(20,20)))
f.setAttributes(["Hello QGIS", 100, 10.1])
pr.addFeature(f)
vl.updateExtents()
QgsProject.instance().addMapLayer(vl)
if vl.isValid():
QgsProject.instance().addMapLayer(vl)
out = 1
else:
out = 0
return {"OUTPUT":out}

iface.mapCanvas().refresh()but I think the problem is more on the side of your v1 layer. Is your v1 layer is valid? – Vincent Bré Dec 16 '19 at 07:36@algdecorator style of processing script- I am accustomed to the older style of sub-classingQgsProcessingAglorithm, where you can re-implement theflags()method... – Ben W Dec 17 '19 at 08:06NoThreadingflag. It must be possible to do the same with the new style of script (which I think Nathan Woodrow developed) but I'm not sure how! – Ben W Dec 17 '19 at 08:08