Index de l'article

Miscellaneous

Get executed QGIS Python code

In the QGIS menu: Processing/History.

In a plugin (from QGIS 3.28): Advanced/Copy as Python Command

Set projection and ellipsoid

project = QgsProject.instance()
...
crs = QgsCoordinateReferenceSystem.fromEpsgId(4326)
project.setCrs(crs)
project.setEllipsoid('EPSG:4326')

See the available process and scripts

for alg in QgsApplication.processingRegistry().algorithms():
    print("{}:{} --> {}".format(alg.provider().name(), alg.name(), alg.displayName()))

Manage the multi-execution of your script

Sometimes it is good to remove existing layers and clean your QGIS instance before to run the working code (but also read on because it is not perfect):

project = QgsProject.instance()
project.removeAllMapLayers()
project.clear()
iface.mapCanvas().refresh()

Sometimes it is good to delete all persistent variables at the begining of your code to manage the multi-execution of your script (to be able to run it, and re-run it, then re-run it... it can be useful when your work, but keep to read on because it is not perfect):

for g in globals():
    del g

OK guys, now the real solution 😃: according your working context, and especially when you create/re-create new layers and/or new directories (with a geo-process for example), it is better to do it in a function (def), then to run your function in a QTimer.singleShot, with a little delay (below 200 milliseconds):

...
def myGeoProcess():
    ...
    processing.run('qgis:anyGeoProcess', {
    ...
    })
...
QTimer.singleShot(200, myGeoProcess)
...

Find a full example in the chapter named Processing: Intersection or Processing: Buffer.

Using QGIS Buttons in Python Code

eMenu = iface.viewMenu()
eMenu.actions()[12].trigger()

Add custom text in map

project = QgsProject.instance()
iface.mapCanvas().refresh()
 
manager = project.layoutManager()
layout = QgsPrintLayout(project)
layout.initializeDefaults()
layout.setName(layoutName)
 
manager.addLayout(layout)
map = QgsLayoutItemMap(layout)
 
myBoldFont=QtGui.QFont('Verdana', 11)
myBoldFont.setBold(True)
 
TextCustom = QgsLayoutItemLabel(layout)
TextCustom.setText("Wikipédia :")
TextCustom.setFont(myBoldFont)
layout.addLayoutItem(TextCustom)
TextCustom.attemptMove(QgsLayoutPoint(230, 90, QgsUnitTypes.LayoutMillimeters))
TextCustom.attemptResize(QgsLayoutSize(60, 100, QgsUnitTypes.LayoutMillimeters))

Download a picture and add a backgound color

from PyQt5 import *
from qgis.PyQt.QtGui import QImage, QPainter, QColor
 
# Image 1
url = r'https://j4binv.master-geomatique.org/images/img_site/logos/logo2021-blanc.png'
response = requests.get(url)
image_originale1 = myPath + 'logo_master.png'
path_nouvelle_image1 = myPath + 'logo_master_fond_vert.png'
 
# Dowload image
if response.status_code == 200:
    with open(image_originale1, 'wb') as file:
        file.write(response.content)
else:
    raise Exception('Impossible de télécharger l\'image !')
 
# Set a black background
my_image = QImage(image_originale1)
largeur = my_image.width() + 40
hauteur = my_image.height() + 40
 
nouvelle_image1 = QImage(largeur, hauteur, QImage.Format_ARGB32)
nouvelle_image1.fill(QColor(21, 187, 161))
 
painter = QPainter(nouvelle_image1)
 
x_offset = (largeur - my_image.width()) // 2
y_offset = (hauteur - my_image.height()) // 2
 
painter.drawImage(x_offset, y_offset, my_image)
painter.end()
 
nouvelle_image1.save(path_nouvelle_image1)