PyQt5重新打开我访问过的同一目录

问题描述 投票:1回答:1

我正在使用getOpenFileName来打开文件,我有3个类,我在它们之间绑定它们。例如 ,

A类()类B()类C()Main()

主要显示窗口有3个按钮:每个按钮调用三个类中的一个,每个按钮打开另一个窗口负责自己的功能;但是,C类负责从目录中获取文件。

我想要做的是使getOpenFileName记住上次访问的目录,即使我关闭了类的窗口,但仍然正在运行。换句话说,我上次打开的缓存文件路径。

下面的代码更多插图。

C()类:

def OpenFileX(self):
    self.file, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Single File', QtCore.QDir.rootPath() , '*.csv')
    self.textBrowserMS.setText(self.fileName)
    return self.fileName

def getfileOG(self):
    filePath, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Single File', QtCore.QDir.rootPath() , '*.csv')
    self.textBrowserOG.setText(filePath)
def getfileConfig(self):
    filePath, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Single File', QtCore.QDir.rootPath() , '*.csv')
    self.textEdit_config.setText(filePath) 

主类

Import C
class analysis(QtWidgets.QMainWindow, C.Ui_Dialog):
    def __init__(self,parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)
        #self.ui = C.Ui_MainWindow()
        self.setupUi(self)

任何想法我怎么能做到这一点

python pyqt pyqt5 qfiledialog
1个回答
1
投票

您必须将最后一个路径保存在持久性内存中,例如使用QSettings,为此必须设置setOrganizationName(),setOrganizationDomain()和setApplicationName()。

from PyQt5 import QtCore, QtWidgets

class C(QtWidgets.QDialog):
    def __init__(self, parent=None):
        super(C, self).__init__(parent)
        self.te = QtWidgets.QTextEdit()
        button = QtWidgets.QPushButton("Press me")
        button.clicked.connect(self.on_clicked)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(self.te)
        lay.addWidget(button)

    @QtCore.pyqtSlot()
    def on_clicked(self):
        settings = QtCore.QSettings()
        path = settings.value("Paths/csvfile", QtCore.QDir.rootPath())
        filename, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Single File', path, '*.csv')
        if filename:
            self.te.setText(filename)
            finfo = QtCore.QFileInfo(filename)
            settings.setValue("Paths/csvfile", finfo.absoluteDir().absolutePath())

class MainWindow(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.c = C()
        button = QtWidgets.QPushButton("Open C Dialog")
        button.clicked.connect(self.c.show)
        self.setCentralWidget(button)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    QtCore.QCoreApplication.setOrganizationName("MySoft")
    QtCore.QCoreApplication.setOrganizationDomain("mysoft.com")
    QtCore.QCoreApplication.setApplicationName("MyApp")
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())
© www.soinside.com 2019 - 2024. All rights reserved.