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()))

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)