hamza el hadry
hamza el hadry

Reputation: 33

Creating a browse button with PyQT5

I want to create a browse button with pyqt5, but I do not get it

from PyQt5 import QtWidgets,QtCore, QtGui

import test3 

class MyWindow(QtWidgets.QMainWindow):

    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)
        self.ui = test3.Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.pushButton_2.clicked.connect(self.getfiles)


    def getfiles(self):
        fileName = QtGui.QFileDialog.getOpenFileName(self,'Single File','C:\'','*.xlsm')
        self.ui.lineEdit.setText(fileName)


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())

Upvotes: 0

Views: 13856

Answers (2)

Ronny K
Ronny K

Reputation: 3741

This is what worked for me.

fileName, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Single File', '', '*.xlsm')

Upvotes: 0

eyllanesc
eyllanesc

Reputation: 243983

In your code there are 2 errors:

  1. QFileDialog belongs to QtWidgets

  2. The second is that the getOpenFileName function returns a tuple: (filename, filter), the first element is the filename, and the second is the filter.

For which functions you must change:

fileName = QtGui.QFileDialog.getOpenFileName(self,'Single File','C:\'','*.xlsm')

to:

fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Single File', QtCore.QDir.rootPath() , '*.xlsm')

Upvotes: 5

Related Questions