1

I'm working with QGIS 3.34.11-Prizren and have a Python script that I want to use within the Processing Toolbox. My goal is to incorporate it into a model in the Model Designer. However, I am facing an issue where the script seems to run automatically when QGIS starts, instead of just being available in the toolbox.

Details:

-I placed the script in the folder: ...\AppData\Roaming\QGIS\QGIS3\profiles\default\processing\scripts

-The script is meant to export all layouts in the current QGIS project to PDF. It prompts the user to select an output folder.

Script:

##Export Layouts to PDF=name
##Select Output Directory=folder
import os
from qgis.core import QgsProject, QgsLayoutExporter
from PyQt5.QtWidgets import QFileDialog
# Prompt user to select the output folder
output_dir = QFileDialog.getExistingDirectory(None, "Select Output Folder")
if output_dir:
 project = QgsProject.instance()
 layouts = project.layoutManager().layouts()
 # Loop through each layout and export to PDF
 for layout in layouts:
 exporter = QgsLayoutExporter(layout)
 pdf_path = os.path.join(output_dir, layout.name() + ".pdf")
 result = exporter.exportToPdf(pdf_path, QgsLayoutExporter.PdfExportSettings())
 if result != QgsLayoutExporter.Success:
 print(f"Failed to export {layout.name()} to PDF")
else:
 print("No directory selected. Export cancelled.")

Problem:

The script runs automatically when I launch QGIS, prompting the user to select an output folder immediately, which is quite disruptive.

My intent is to have it available in the Processing Toolbox so I can use it manually or in the Model Designer, but not have it run at startup.

What I've Tried:

Moving the script out of the folder temporarily stops the automatic execution but, of course, it is no longer available in the Processing Toolbox.

I added Processing Toolbox headers to the script, but the issue persists.

Desired Outcome:

I want the script to be listed in the Processing Toolbox, accessible only when I manually trigger it (or use it in the Model Designer).

I need to stop QGIS from automatically running the script on startup.

Additional Info:

QGIS Version: 3.34.11-Prizren Python Version: 3.12.6

How can I stop the automatic execution of this script while still making it accessible in the Processing Toolbox?

PolyGeo
65.5k29 gold badges115 silver badges349 bronze badges
asked Oct 17, 2024 at 11:56
1
  • 1
    It needs to be a class subclassing QgsProcessingAlgorithm docs.qgis.org/3.34/en/docs/user_manual/processing/scripts.html. What you have is not a processing algorithm. processing algs usually takes parameters and such. You have a script that can be run without adding it to the processing toolbox Commented Oct 17, 2024 at 13:19

1 Answer 1

2

After help in a comment by @Kalak, here's the revised code, in case someone wants to use it. It exports all the layouts of the project.

from qgis.core import (QgsProcessingAlgorithm, 
 QgsProcessingParameterFolderDestination, 
 QgsProcessingParameterNumber,
 QgsProject, 
 QgsLayoutExporter,
 QgsProcessingException)
import os
class ExportLayoutsToPDF(QgsProcessingAlgorithm):
OUTPUT_DIR = 'OUTPUT_DIR'
DPI = 'DPI'
def initAlgorithm(self, config=None):
 self.addParameter(
 QgsProcessingParameterFolderDestination(
 self.OUTPUT_DIR,
 'Select Output Directory'
 )
 )
 self.addParameter(
 QgsProcessingParameterNumber(
 self.DPI,
 'DPI',
 type=QgsProcessingParameterNumber.Integer,
 defaultValue=300,
 minValue=72,
 maxValue=1200
 )
 )
def processAlgorithm(self, parameters, context, feedback):
 output_dir = self.parameterAsString(parameters, self.OUTPUT_DIR, context)
 dpi = self.parameterAsInt(parameters, self.DPI, context)
 
 if not output_dir:
 raise QgsProcessingException('No output directory selected.')
 
 project = QgsProject.instance()
 layouts = project.layoutManager().layouts()
 if not layouts:
 feedback.pushInfo('No layouts found in the current project.')
 return {}
 for layout in layouts:
 try:
 exporter = QgsLayoutExporter(layout)
 pdf_path = os.path.join(output_dir, layout.name() + ".pdf")
 
 settings = QgsLayoutExporter.PdfExportSettings()
 settings.dpi = dpi
 settings.exportMetadata = True
 
 result = exporter.exportToPdf(pdf_path, settings)
 
 if result == QgsLayoutExporter.Success:
 feedback.pushInfo(f"Successfully exported {layout.name()} to {pdf_path}")
 else:
 feedback.pushInfo(f"Failed to export {layout.name()} to PDF. Error code: {result}")
 except Exception as e:
 feedback.pushInfo(f"Error exporting {layout.name()}: {str(e)}")
 return {}
def name(self):
 return 'export_layouts_to_pdf'
def displayName(self):
 return 'Export Layouts to PDF'
def group(self):
 return 'Example scripts'
def groupId(self):
 return 'examplescripts'
def createInstance(self):
 return ExportLayoutsToPDF()
def shortHelpString(self):
 return "This algorithm exports all layouts in the current project to PDF files with user-specified DPI."
def helpUrl(self):
 return "https://qgis.org/pyqgis/3.0/core/Processing/QgsProcessingAlgorithm.html"
PolyGeo
65.5k29 gold badges115 silver badges349 bronze badges
answered Oct 17, 2024 at 14:29

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.