3

I am trying to set my output parameters in a script for Qgis using QFileDialog

This is the code that I am using

parent=iface.mainWindow()

outputFn, outfnOK = QFileDialog.getSaveFileName(parent,
                        "Save File",
                        QgsProject.instance().homePath(),
                        "Shapefiles (*.shp);;GeoPackage (*.gpkg)")

The filter that I am using at the end only works to see files with the same extension in the dialog window. The format of the output is defined by the extension that the user must type. If the user does not enter any extension, then the output is gpkg by default.

Is it possible to apply the filter on the output type instead of applying it as a visibility filter?

Or is there another method that I could use so the user will be able to choose the output type without having to write the extension?

1 Answer 1

3

So, after struggling a bit...I think I was hoping for an easy answer when the only answer is to code...

I found a couple of strategies that I share here

Strategy one / make the user enter the extension

##########################################################
#Create the vector layer on which to apply the processing
##########################################################

mergedLayer = QgsVectorLayer('multipolygon','','memory')

#############################
#initialize boolean as false
#############################

extBool = False 

###################################################################
#use a while loop to check if the user entered a correct extension
###################################################################

while extBool == False:
    #Call The dialog window
    outputFn, outfnSel = QFileDialog.getSaveFileName(parent,"Save File", QgsProject.instance().homePath(),"GeoPackage (*.gpkg);;Shapefiles (*.shp)")

    if outputFn == "":
        #Warning if cancel button is hit
        QMessageBox.warning(parent,"Warning","Name is missing")
        #set boolean to True to exit loop
        extBool = True

    else:

#############################################################
#Check if the extension is correct, exit loop and create file
#############################################################

        if outputFn[-4:] == '.shp' or outputFn[-5:]=='.gpkg':
            #the extension is correct, set boolean to True and exit loop
            extBool = True
            if outputFn[-4:] == '.shp':
                #store vectore layer in output as a shapefile
                QgsVectorFileWriter.writeAsVectorFormat(mergedLayer,outputFn,'utf-8',driverName='ESRI Shapefile')
            if outputFn[-5:]=='.gpkg':
                #store vectore layer in output as a geopackage file
                QgsVectorFileWriter.writeAsVectorFormat(mergedLayer,outputFn,'utf-8')
            #load file
            iface.addVectorLayer(outputFn,'','ogr')
            #sucess message
            iface.messageBar().pushMessage("Sucess",str(outputFn)+" loaded", level=Qgis.Success)

        else:
            #give a warning if the extension is missing or incorrect
            QMessageBox.warning(parent,"Warning","Incorrect or missing extension")
            #boolean is still set as false, dialog window will pop out again

Strategy 2 / use the tupple to build the file correctly

##########################################################
#Create the vector layer on which to apply the processing
##########################################################

mergedLayer = QgsVectorLayer('multipolygon','','memory')

##########################
#Call The dialog window
##########################

outputFn, outfnSel = QFileDialog.getSaveFileName(parent,"Save File", QgsProject.instance().homePath(),"GeoPackage (*.gpkg);;Shapefiles (*.shp)","GeoPackage (*.gpkg)")

################################
#Warning if cancel button is hit
################################
    
if outputFn == "":
    QMessageBox.warning(parent,"Warning","Name is missing")

###############################################
#Using the second part of the tupple which
#stores the selection filter to create the file
###############################################

else:
    if outfnSel == 'GeoPackage (*.gpkg)':
        #store the vector layer in the output direction, default is gpkg
        QgsVectorFileWriter.writeAsVectorFormat(mergedLayer,outputFn,'utf-8')
        #add the extension to the name in order to load the file
        iface.addVectorLayer(str(outputFn)+'.gpkg','','ogr')
    if outfnSel == 'Shapefiles (*.shp)':
        #store the vector layer in the output direction specifying shapefile format
        QgsVectorFileWriter.writeAsVectorFormat(mergedLayer,outputFn,'utf-8',driverName='ESRI Shapefile')
        #add the extension to the name in order to load the file
        iface.addVectorLayer(str(outputFn)+'.shp','','ogr')
                    
    #sucess message
    iface.messageBar().pushMessage("Èxit",str(outputFn)+" loaded", level=Qgis.Success)

Personally, I prefer the second one as it uses the tupple.. Still pretty new to pyqgis so comments are of course most welcome...

1
  • update: so I was running the script on linux and and Qgis 3.16 and 3.22 and everything was working fine, but then I gave it to a colleague who works on windows, and the vector file would not load. For some reason, it works the opposite on windows and the adapted code is 'iface.addVectorLayer(str(outputFn)','','ogr')'...no need check format and to add it at the end of the file...
    – geotyr
    Apr 11, 2023 at 19:09

Your Answer

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

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