Mas Bagol
Mas Bagol

Reputation: 4617

PyQt5 file dialog not showing up

I have connected a QPushButton to a method that call file dialog. The simplified code look like this:

def init_buttons(self):
    self.browse_button = QPushButton('&Browse')
    self.browse_button.clicked.connect(self.browse_file)

def browse_file(self):
    file_name = QFileDialog.getExistingDirectory()
    # Just for checking
    print(file_name)

Sometimes QFileDialog won't showing up. The process is indeed running, since the main class/widget doesn't response to my clicking. Sometimes it's showing up.

If QFileDialog doesn't show up, with pycharm, I have to stop and kill process to end the program. If I run the program directly from terminal, I have to manually end the running process to end the program. I can't figure out what causing this, since terminal not showing any exception or warning.

So, what is this?

Upvotes: 1

Views: 4268

Answers (2)

ham-sandwich
ham-sandwich

Reputation: 4050

The parameters for the getExistingDirectory were wrong. Please try this. Also, I have added further information in my pull request.

import os

def browse_file(self):
    self.save_dir = QFileDialog.getExistingDirectory(self, 
                      "Open Save Directory", os.path.expanduser('~'))
    print(self.save_dir)

Upvotes: 1

ahumblenerd
ahumblenerd

Reputation: 225

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import sys
from PyQt5.QtWidgets import (QMainWindow, QTextEdit,
    QAction,QMessageBox, QFileDialog, QApplication,QPushButton,QInputDialog,QLineEdit)
from PyQt5.QtGui import QIcon


class Example(QMainWindow):

    def __init__(self):
        super().__init__()
        self.initUI()


    def initUI(self):
        self.fileName=""
        self.text=""
        btn1 = QPushButton("Encrypt", self)
        btn1.clicked.connect(self.onBtn1)
        self.show()

    def onBtn1(self):

        self.fileName, _  = QFileDialog.getOpenFileName(self, 'Open file', '/Users/Jarvis/Desktop/')

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

Upvotes: 0

Related Questions