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.
Related
I try to read dataframe from excel file and print it after button click.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox
from PyQt5.QtGui import QIcon
from excel_reading import *
class MyWin(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.pushButton.clicked.connect(self.hello)
def hello(self):
data_input_from_file = QtWidgets.QFileDialog.getOpenFileName(self,'header','filename','Excel (*.xlsx *.xls)')
print(data_input_from_file)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
myapp = MyWin()
myapp.show()
sys.exit(app.exec_())
When I click button, I have such message:
Gtk-Message: 00:03:53.573: GtkDialog mapped without a transient parent. This is discouraged.
('', '')
How should I solve that problem?
I solved the problem:
def hello(self):
data_input_from_file = QtWidgets.QFileDialog.getOpenFileName(self, 'header', 'filename', 'Excel (*.xlsx *.xls)')
print(type(data_input_from_file))
print(data_input_from_file)
print(pd.read_excel(data_input_from_file[0]))
The Gtk warning is just what it is: a warning. You can ignore that. Qt tries to use the system native file dialogs whenever possible, which might result in some warnings in the consolle output.
Your issue is related to something else: there are rare cases for which PyQt functions don't return the same signature as reported in the official Qt (C++) documentation.
QFileDialog static methods is one of such cases, as QFileDialog.getOpenFileName() always returns a tuple: the selected file path and the selected file type filter. This is also clear from the output of your code (which I suppose is caused by cancelling the dialog):
('', '')
The first value is the selected file (in this case, none) and filter (again, none, as there was no selected file).
The solution is to assign two values for what the static returns:
filePath, filters = QtWidgets.QFileDialog.getOpenFileName(
self,'header','filename','Excel (*.xlsx *.xls)')
if filePath:
# do something
I'm trying to build an app here. I used QT Designer to build the main window (Ui_MainWindow) with buttons. I import this to a new file where I can structure the code a bit better.
Anyhow, I keep getting the error "TypeError: startfile: filepath should be string, bytes or os.PathLike, not Ui_MainWindow" whenever I try to get the filename via QFileDialog. This filename is used in the GetData -method to produce a dataframe. I'm sure I'm doing something horribly wrong here in my code. I understood that you can call methods within other methods
So I will have 3 buttons:
Open folder (which gets the filename)
Update data (which is connected to UpdateData method. This method updates the data as I want)
Calculate (a method that calculates something based on the output from updateData -method.)
So I am trying to get an output from step 1 to use as input in step 2, to get an output which then would be used as input in step 3 and then - voilá.
What am I doing wrong?
from myQTDesignerGUIfile import Ui_MainWindow
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import (QApplication, QMainWindow, QPushButton, QLabel, QFileDialog, QMessageBox)
from PyQt5.QtCore import pyqtSlot, QFileInfo
class MyApp(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
#Build instance of setpUI in Ui_MainWindow -class
self.ui = Ui_MainWindow()
self.ui.setupUi(self)
def GetFileName(self):
FileFilter = 'File (*.xlsx *.xlsm *.csv)'
FileName = QFileDialog.getOpenFileName(parent = self,
caption="Select File",
directory = 'Some Path',
filter = FileFilter)[0]
path = str(FileName)
if path:
print(path)
return path
def GetData(self):
path = self.GetFileName
return pd.read_csv(path)
def UpdateData(self):
## get data using the GetData -method
df = self.GetData()
## code to modify data is written here
return final_mod_data
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = MyApp()
w.show()
app.exec()
I wrote small program to display images from network drive. It works perfectly when is launched as .py,
but when converted to .exe file (using auto-py-to-exe as one directory) program starts but not displays images and returns error "QPixmap::scaled: Pixmap is a null pixmap".
I have already tried:
path = "\\\\ow-sql\\Users\\file scanner\\Documents\\job_scans_copy\\20206\\012252988_30-06-2020-
151531.jpg"
path = r"\\" + os.path.join("ow-sql", "Users", "file scanner", "Documents", "job_scans_copy","20206","012252988_30-06-2020-151531.jpg")
I also tried both \ and /.
I can't simply include file into the build as the files will change and new files will be added.
There is no problem with images from img. folder.
for example:
img = QPixmap("img\\image.jpg")
works perfect as an exe.
Would you advise me how to fix this problem?
Please find simplified code below:
import sys
from PyQt5 import QtCore
from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton, QLabel, QScrollArea
from PyQt5.QtGui import QPixmap
class ApplicationWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
main_widget = QWidget(self)
btn = QPushButton("Close", self)
btn.clicked.connect(self.close)
img = QPixmap("\\\\ow-sql\\Users\\file scanner\\Documents\\job_scans_copy\\20206\\012252988_30-06-2020-151531.jpg")
label = QLabel(main_widget)
pixmap_resized = img.scaled(200, 200)
label.setPixmap(pixmap_resized)
scrollArea = QScrollArea(main_widget)
scrollArea.setWidgetResizable(True)
scrollArea.setWidget(label)
l = QVBoxLayout(main_widget)
l.addWidget(scrollArea)
l.addWidget(btn)
self.setCentralWidget(main_widget)
def closeEvent(self, ce):
self.close()
if __name__ == '__main__':
app = QApplication(sys.argv)
aw = ApplicationWindow()
aw.show()
app.exec_()
I resolved my problem simply by using cx_Freeze to create an executable and everything works perfect.
For some reason pyInstaller does not want to load the image into QLabel if it's not included in build. It doesn't matter if it's a path to the file or the file is loaded as a BLOB from the database. None of them works.
cx_Freeze solved the problem without any additional code changes.
i have python class called PDFviewer that upon run the program the system display a window that handle button (open folder) witch will open a file Dialog that allow the user to choose a directory and display files inside it.
the problem is that when i try to click the button the system crash and display this error :
File
"C:\Users\test\Documents\Python_Projects\final_project\myPDFviewer.py",
line 36, in sys.exit(app.exec_()) File
"C:\Users\test\Documents\Python_Projects\final_project\myPDFviewer.py",
line 24, in setExistingDirectory options=options)
builtins.TypeError: getExistingDirectory(parent: QWidget = None,
caption: str = '', directory: str = '', options:
Union[QFileDialog.Options, QFileDialog.Option] =
QFileDialog.ShowDirsOnly): argument 1 has unexpected type 'bool'
code:
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import (QApplication, QCheckBox, QColorDialog, QDialog,
QErrorMessage, QFileDialog, QFontDialog, QFrame, QGridLayout,
QInputDialog, QLabel, QLineEdit, QMessageBox, QPushButton)
from PyQt5.QtCore import QDir, Qt
import pdfviewer
class pdfViewer(pdfviewer.Ui_PdfPreviewWindow):
def __init__(self,PdfPreviewObj ):
self.PdfPreviewObj =PdfPreviewObj
self.setupUi(PdfPreviewObj)
self.PdfPreviewObj.show()
self.pushButtonOpenFolder.clicked.connect(self.setExistingDirectory)
def setExistingDirectory(self,qf):
options = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly
directory = QFileDialog.getExistingDirectory(self,
"Open Folder",
options=options)
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
PdfPreviewWindow = QtWidgets.QMainWindow()
pdfViewerUi = pdfViewer(PdfPreviewWindow)
sys.exit(app.exec_())
i found the solution it did not work before because i wasn't refer the object dialog to self so the solution become :
def setExistingDirectory(self):
self.dialog = Dialog()
options = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly
self.directory = QFileDialog.getExistingDirectory(self.dialog, "Open Folder" ,options=options)
self.dialog.show()
Selecting files:
filepath = QtWidgets.QFileDialog.getOpenFileName(self, 'Select File')
Here, self represents the parent window usually the mainWindow.
Similarly, for selecting folder:
folderpath = QtWidgets.QFileDialog.getExistingDirectory(self, 'Select Folder')
I want my pyqt application to act as a file handler for a certain file format (with a certain suffix), that is,
I want to be able to open files from the operating system directly in my pyqt application, say by double clicking or contextual menu "open with".
Is this possible?
Thank you and best regards!
Yes, it is possible. I suggest using the
QFileDialog.getOpenFileName()
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QFileDialog
class MainWin(QMainWindow):
def __init__(self):
super().__init__()
self.setGeometry(150,150,200,150)
self.setWindowTitle("Test")
button = QPushButton('Open with', self)
button.clicked.connect(self.dialog)
button.resize(100,32)
button.move(50,50)
self.show()
def dialog(self):
# https://doc.qt.io/qtforpython-5/PySide2/QtWidgets/QFileDialog.html#PySide2.QtWidgets.PySide2.QtWidgets.QFileDialog.getOpenFileName
file, check = QFileDialog.getOpenFileName(
None,
"QFileDialog.getOpenFileName()",
"",
self.tr(
'All Files (*);;'
'Python Files (*.py);;'
'Text Files (*.txt)'))
if check:
print(file)
if __name__ == "__main__":
app = QApplication(sys.argv)
win = MainWin()
sys.exit( app.exec_() )