Search code examples
python-3.xpyqt5qfiledialog

How to pre-fill the file name in a QFileDialog?


Good day,

I made a program to take measurements and plot them on a graph. The user can then export the data as .csv or the graph as .png at a custom location with a custom name thanks to QFileDialog. Below is the code, anyone feel free to use it for yourself.

My question is: how to pre-fill the file name in the dialog box so that the user can still specify a custom name, but if they don't care it's already filled with experimental parameters. Thanks in advance.

def export_picture(self):
    """Grabs the plot on the interface and saves it in a .png file at a custom location."""

    # Setup a file dialog.
    MyDialog = QFileDialog()
    MyDialog.setWindowTitle("Select a location to save your graph.")
    MyDialog.setAcceptMode(QFileDialog.AcceptSave)
#   MyDialog.a_method_to_prefill_the_file_name("name") <-- ?
    MyDialog.exec_()

    # Abort the function if somebody closed the file dialog without selecting anything.
    if len(MyDialog.selectedFiles()) == 0:
        return

    # Save the file and notify the user.
    CompleteName = MyDialog.selectedFiles()[0] + ".png"
    self.ui.Graph.figure.savefig(fname=CompleteName, dpi=254, format="png")
    Directory, File = os.path.split(FileAndPath)
    print('Graph exported as "%s.png" in the folder "%s".' %(File, Directory))

Solution

  • You can use getSaveFileName.

    import sys
    from PyQt5 import QtWidgets
    if __name__ == "__main__":
        app = QtWidgets.QApplication(sys.argv)
    
        button = QtWidgets.QPushButton('Get File Name...')
        button.show()
    
        def _get_file_name():
            save_file, _ = QtWidgets.QFileDialog.getSaveFileName(button, "Save File...", 'foo.txt')
            print(f'save_file = {save_file}')
    
        button.clicked.connect(_get_file_name)
    
        sys.exit(app.exec_())