Marvin
Marvin

Reputation: 1

PyQt5 File Dialog - the last opened file becomes the initial path for the next use of the tool

I am trying to build a GUI with PyQt5. The relevant part of the code is shown below. So i created a QTextEdit and a button. The Path to the file is shown on the QTextEdit and the button opens a file dialog to choose another file and updates the QTextEdit widget. It works good like this. The Filename is used at a couple of different places all over the tool.

I give it a initial path at the moment. But that is not what i want to do. I rather want my tool to have the last opened file as an initial path. So in the beginning the QTextEdit widget should be empty as long as i open a file. That should be saved when i close it and be the initial path when i use my tool again the next time. Does anyone have an idea how i can do that?

class Ui_MainWindow(QMainWindow):
    def __init__(self):
        super(Ui_MainWindow, self).__init__()
        self.Filename = "C:/Users/Marvin/Desktop/Kostenkontrolle Programm/Database.csv"
        self.path.setText(self.Filename)
        self.Open_Database.clicked.connect(self.open_dialog)


    def open_dialog(self):
        self.Filename = QFileDialog.getOpenFileName()
        self.path.setText(self.Filename[0])

Upvotes: 0

Views: 1762

Answers (1)

Christian Karcher
Christian Karcher

Reputation: 3641

Dialogs from QFileDialog accept "directory" as an input parameter.

So I would suggest replacing

self.Filename = QFileDialog.getOpenFileName()

by

self.Filename = QFileDialog.getOpenFileName(directory=self.path.text())

This should give you the desired effect (or at least an idea on how to get there).

If you want to store the file path somewhere else than in the program code, you could use QSettings:

from PyQt5.QtCore import QSettings

self.settings = QSettings("pyqt_settings.ini", QSettings.IniFormat)
# for saving a value to the ini
settings.setValue("LastFile", filename)
# for loading a value from the ini
self.settings.value("LastFile")

Upvotes: 1

Related Questions