I want to alter a raster layer with Python code and update the style afterwards. The style part is out of reach because I encountered the following problem:
I added a Float64 raster layer to my project using the "Create constant raster layer" processing tool. The layer is in my project's table of contents, named "Constant".
Then I run this script in the Python console:
import struct
layer = QgsProject.instance().mapLayersByName('Constant')[0]
data_provider = layer.constDataProvider()
block = data_provider.block(1, layer.extent(), layer.width(), layer.height())
new_data = struct.pack("dd", *[-99, 99]) # two double values
block.setData(new_data)
data_provider.setEditable(enabled=True)
data_provider.writeBlock(block, 1)
data_provider.setEditable(enabled=False)
The TIF file is rewritten now. If I open it manually, I see the new values in the first two pixels in the top left of the image.
But the "Constant" layer that was already in my ToC and on which I operated, still shows the same old constant value as its min and max values. I tried setting the "Min / Max Value Settings"' "Accuracy" to "Actual (slower)" with no success. I also tried data_provider.reload()
and layer.triggerRepaint()
without success.
I do not want to set the min and max values manually, but have QGIS execute whatever it does when I set the "Min / Max Value Settings"' "Accuracy" to "Actual (slower)".
How do I make QGIS recognize the new data in the layer and update its statistics?
struct
beforestruct
to pack two double values into bytes. Is there a nicer way to do that in pyqgis (maybe using Qt's functions?)?