简体   繁体   中英

PyQt5 File open Dialog

is there any way to open a folder with pyqt5 file dialog

I tried taking the quotes, I want to open a folder or a directory with subdirectories or subfolders

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QFileDialog, QTextEdit, QPushButton, QLabel, QVBoxLayout


class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.resize(800, 600)

        self.button1 = QPushButton('Open Project Folder')
        self.button1.clicked.connect(self.get_folder)


        self.labelImage = QLabel()
        self.textEditor = QTextEdit()

        layout = QVBoxLayout()
        layout.addWidget(self.button1)
        layout.addWidget(self.labelImage)
        layout.addWidget(self.button2)
        layout.addWidget(self.textEditor)
        self.setLayout(layout)

    def get_folder(self):
        file_name, _ = QFileDialog.getOpenFileName(
            self, 'Project Data', r"", "")
        print(file_name)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = MainWindow()
    main.show()
    sys.exit(app.exec_())```

There are various static functions available for QFileDialog, if you need to open a directory, don't use getOpenFileName but getExistingDirectory() .

As you can see from the documentation, the arguments are slightly different, and if you run help(QtWidgets.QFileDialog.getExistingDirectory) from the python shell, you'll see the full argument signature and the returned value written in the python syntax.

getExistingDirectory(parent: QWidget = None, caption: str = '', directory: str = '', options: Union[QFileDialog.Options, QFileDialog.Option] = QFileDialog.ShowDirsOnly) -> str

The last part ( -> str ) means that there is only one returned value, which is the string of the selected directory (which will be empty if the user cancels the dialog).

    def get_folder(self):
        folder = QFileDialog.getExistingDirectory(
            self, 'Project Data', '')
        if folder:
            print(folder)

I suggest you to always study the documentation of each class you're using, and using the official documentation; even if it's C++ oriented, the functions have the same names on PyQt, and their arguments/returned values are the same in 99% of the cases. Whenever you've a doubt or you face a problem about wrong arguments or returned data, you can check the official PyQt documentation or just use help(class.function) in the python shell.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM