2

I interpolate and crop the temperature data with PyQGIS (QGIS 3.18). There is no problem so far, but I can not set style file. What can I do set style file correctly?

OS: Win10

import os, sys
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = r'C:\OSGeo4W64\apps\Qt5\plugins'
os.environ['PATH'] += r';C:\OSGeo4W64\apps\qgis\bin;C:\OSGeo4W64\apps\Qt5\bin;C:\OSGeo4W64\apps\qgis\python'

print (os.environ['PATH'])

from qgis.core import *
from qgis.core import QgsProcessing
from qgis.core import QgsApplication
from qgis.core import QgsProcessingAlgorithm
from qgis.core import QgsProcessingMultiStepFeedback
from qgis.core import QgsProcessingFeedback
from qgis.core import QgsProcessingParameterRasterLayer
from qgis.core import QgsProcessingParameterFeatureSink
from qgis.utils import *
from qgis.gui import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

# Initialize QGIS Application
QgsApplication.setPrefixPath("C:\\OSGeo4W64\\apps\\qgis", True)
qgs = QgsApplication([], False)
qgs.initQgis()
  
for alg in QgsApplication.processingRegistry().algorithms():
    print(alg.id(), "->", alg.displayName())
    #print("{}:{} --> {}".format(alg.provider().name(), alg.name(),alg.id(), alg.displayName()))  
# Append QGIS Python library to python search path
sys.path.append(r'C:\OSGeo4W64\apps\Python37')
sys.path.append(r'C:\OSGeo4W64\apps\qgis\plugins')
sys.path.append(r'C:\OSGeo4W64\apps\qgis\python\plugins')
sys.path.append(r'C:\OSGeo4W64\apps\qgis\python\plugins\processing')
# Append location of DLLs to current system PATH envrionment variable
import processing
from qgis.analysis import QgsNativeAlgorithms
from processing.core.Processing import Processing
Processing.initialize()
QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())

#running---
processing.run("qgis:idwinterpolation", {'INTERPOLATION_DATA':'E:\\GIS\\country.shp|subset=\"temperature\"  >= 0::~::0::~::6::~::0','DISTANCE_COEFFICIENT':2,'EXTENT':'24.945366085,45.353916836,35.218981812,43.628804562 [EPSG:4326]','PIXEL_SIZE':0.1,'OUTPUT':'E:\\GIS\\idw_temperature.tif'})
#running---
processing.run("gdal:cliprasterbymasklayer", {'INPUT':'E:\\GIS\\idw_temperature.tif','MASK':'E:\\GIS\\country_border.shp','SOURCE_CRS':None,'TARGET_CRS':None,'NODATA':None,'ALPHA_BAND':False,'CROP_TO_CUTLINE':True,'KEEP_RESOLUTION':False,'SET_RESOLUTION':False,'X_RESOLUTION':None,'Y_RESOLUTION':None,'MULTITHREADING':False,'OPTIONS':'','DATA_TYPE':0,'EXTRA':'','OUTPUT':'E:\\GIS\\idw_temperature_crop.tif'})
 

fileName = "E:\\GIS\\idw_temperature_crop.tif"
QML_file = "E:\\temperaturestyle1.qml"
fileInfo = QFileInfo(fileName)
baseName = fileInfo.baseName()
rlayer = QgsRasterLayer(fileName, baseName)
if rlayer.isValid():
   print ("Layer loaded!") 
QgsProject.instance().addMapLayer(rlayer)
processing.run("native:setlayerstyle", {'INPUT': fileName, 'STYLE': QML_file})   ##returns nothing........
extent = rlayer.extent()
rlayer.triggerRepaint()
qgs.exitQgis()
0

since in Python 3 strings are Unicode by default, you need to take care with hardcoded Windows file paths. There are at least three ways to make them work:

  1. substitute backslashes with double backslashes
  2. prepend an r to get a raw string (e.g. r'C:\temp')
  3. use forward slashes

Some of the paths in your script already have an r prepended but not all of them.

1
  • Thank you for your help, I made the changes you said but I need to set style file
    – ert loo
    Jul 7 at 13:05
0

Not sure but the warning is quite clear

"Logged warning: Duplicate provider native registered"

You are registering twice your providers. Comment QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms()) and also from qgis.analysis import QgsNativeAlgorithms (unneeded with first commented line) to avoid the error. Deduced from answer to Using QGIS3 Processing algorithms from standalone PyQGIS scripts (outside of GUI)

Uncertain it's this warning that cause the later error.

To debug if the error persists, run from PyQGIS within QGIS to be sure your issue is only related to standalone usage. If it fails, you know where the issue is.

import processing

processing.run("native:setlayerstyle", {'INPUT':'E:\\GIS\\idw_temperature_crop.tif','STYLE':'E:\\GIS\\temperaturestyle1.qml'})
3
  • Thank you for your time, but the "Logged warning: Duplicate provider native registered" error is not so important for me. I need to set the style file. I don't know what to do about it.
    – ert loo
    Jul 7 at 12:59
  • Does the command works in QGIS Python console? It's what I suggested to try troubleshooting but you did not answer. Result of the test, plz?
    – ThomasG77
    Jul 7 at 13:08
  • Sorry I coudnt see your post. All codes are working in qgis Pyhton command line. There is no error message now.thanks again.
    – ert loo
    Jul 7 at 13:10
0
img = QImage(QSize(800, 800), QImage.Format_ARGB32_Premultiplied)
color = QColor(0, 0, 0, 0 )
img.fill(color.rgba())
p = QPainter()
p.begin(img)
p.setRenderHint(QPainter.Antialiasing)
ms = QgsMapSettings()
ms.setBackgroundColor(color)
layer = QgsProject.instance().mapLayersByName('name')
ms.setLayers([layer[0]])
rect = QgsRectangle(ms.fullExtent())
rect.scale(1.1)
ms.setExtent(rect)
ms.setOutputSize(img.size())
render = QgsMapRendererCustomPainterJob(ms, p)
render.start()
render.waitForFinished()
p.end()


img.save(fileSavePath1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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