1

I have a QgsFileWidget in my dialog that enables the choosing of a file. I need to set it to choose a folder instead. I understand that I need to use something like:

self.dlg.outputFilePathChooser.StorageMode.GetDirectory

To change this setting. However the above when placed in the run(self) function does not change the setting. I used the Plugin Builder to generate a blueprint and all my code is under the run(self) function. I've tried placing this line of code (which doesn't give any errors in the Log) in various places e.g. after if result: in the run(self) function or in the initGui(self) function.

I have tried adding QgsFileWidget before GetDirectory like so:

self.dlg.outputFilePathChooser.QgsFileWidget.StorageMode.GetDirectory

But get the error 'AttributeError: 'QgsFileWidget' object has no attribute 'QgsFileWidget''

I have also tried formatting it like at the following link, this prevents the plugin from opening, with error 'NameError: name 'GetDirectory' is not defined':

How to use QGSFileWidget to save file?

How do I format & where do I place the code to achieve my desired result (QgsFileWidget opens a dialog to pick a folder, NOT a file)?

1
  • And if you are using QTDesigner to create the layout select he QgsFileWidget and go to Property Editor > QgsFileWdget > storageMode to select the mode you need.
    – tukanium
    Commented Jan 5 at 22:58

2 Answers 2

1
    from qgis.gui import QgsFileWidget
    from qgis.PyQt.QtWidgets import QFormLayout
    # your other imports ... 
    
    def picked_directory(self, path):
        print(self.folder_widget.filePath())    

   .........
    def your_function_xy (self):
        self.folder_widget = QgsFileWidget()
        self.folder_widget.setDialogTitle('Select Directory')
        self.folder_widget.setStorageMode(QgsFileWidget.StorageMode.GetDirectory)
        self.folder_widget.fileChanged.connect(self.picked_directory)
        layout = QFormLayout() # or something else
        layout.addWidget(self.folder_widget)
        self.dlg.setLayout(layout)
        self.dlg.show()   # self.dlg -> your dialog defined somewhere else
        ... and so on
1

This is because storageMode is not the correct method.

As per QgsFileWidget documentation:

  • storageMode: Returns the widget's storage mode (i.e. file or directory)
  • setStorageMode: Sets the widget's storage mode (i.e. file or directory)

So considering this and that your widget's name is outputFilePathChooser, you can change the storage mode with this line:

self.dlg.outputFilePathChooser.setStorageMode(QgsFileWidget.GetDirectory)

It can be inserted in the run() function in the yourPluginName.py file.

Also note that methods don't have uppercase. setStorageMode and not SetStorageMode.

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.