0

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_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
hamza el hadry
  • 33
  • 1
  • 2
  • 6

2 Answers2

5

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')
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • hi I'm also trying the same but getting an error code:- self.pushButton_browse.clicked.connect(self.browsefiles)# def browsefiles(self): fname=QFileDialog.getOpenFileName(self, 'Open file',QtCore.QDir.rootPath(), 'Images (*.png, *.xmp *.jpg)') self.lineEdit_file_loc.setText(fname[0]) – Education 4Fun Jan 06 '21 at 04:19
  • error:- error:- Traceback (most recent call last): File "c:/Users/thota/OneDrive/Desktop/VET/OVE.py", line 195, in browsefiles fname=QFileDialog.getOpenFileName(self, 'Open file',QtCore.QDir.rootPath(), 'Images (*.png, *.xmp *.jpg)')# TypeError: getOpenFileName(parent: QWidget = None, caption: str = '', directory: str = '', filter: str = '', initialFilter: str = '', options: Union[QFileDialog.Options, QFileDialog.Option] = 0): argument 1 has unexpected type 'Ui_Form' – Education 4Fun Jan 06 '21 at 04:21
  • @Education4Fun Please read https://stackoverflow.com/questions/46544780/qtdesigner-changes-will-be-lost-after-redesign-user-interface – eyllanesc Jan 06 '21 at 04:22
0

This is what worked for me.

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

Ronny K
  • 3,641
  • 4
  • 33
  • 43