how to create a File Dialog in python using PyQt5 - python

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')

Related

PyQt5 QFileDialog - Highlight Suggested File in the QListView Widget

I’m using PyQt5 on a Windows platform. I want to present a QFileDialog to the user with the suggested file highlighted in both the QListView and the QLineEdit widgets within the QFileDialog window. The selectFile() method adds the filename to the QLineEdit widget and highlightss it, but does not highlight the file in the QListView widget.
I tried the suggestion in How to setFocus() on QListView in QFileDialog in PyQt5?, but I could not see that the QListView had focus and could not highlight a file with selectFile().
In QFileDialog, is there a way to highlight the filename in the QistView and in the QLineEdit widgets? If not, is there a way to highlight the filename in just the QListView?
Here is a minimalized script that shows the filename highlighted in the QLineEdit widget.
import sys
from PyQt5.QtWidgets import QApplication, QFileDialog
from PyQt5.QtCore import QDir
class MyClass(QFileDialog):
def __init__(self):
super().__init__()
self.DontUseNativeDialog
self.openFile()
def openFile(self):
qdir = QDir()
qdir.setPath('C:\\Users\\Slalo\\Documents\\VideoGates\\PVRTop\\Folder')
qdir.setSorting(QDir.Name | QDir.Reversed)
qdirlist = qdir.entryList()
self.setWindowTitle('Open File')
self.setDirectory(qdir)
self.setNameFilter('All(*.*)')
self.selectFile(qdirlist[1])
if self.exec():
fname = self.selectedFiles()
print(fname)
if __name__ == '__main__':
app = QApplication(sys.argv)
dlg = MyClass()
sys.exit(app.exec())
After testing #musicamante 's patience, here is the solution. The QFileDialog window looks a little different than the native Windows dialog, but that's OK - it works as intended. Here is the corrected script.
import sys, os
from PyQt5.QtWidgets import QApplication, QFileDialog
class MyClass(QFileDialog):
def __init__(self):
super().__init__()
self.setOption(QFileDialog.DontUseNativeDialog)
self.openFile()
def openFile(self):
dirname = 'C:\\Users\\Slalo\\Documents\\VideoGates\\PVRTop\\Folder'
fileList = os.listdir(dirname)
self.setWindowTitle('Open File')
self.setDirectory(dirname)
self.setNameFilter('All(*.*)')
self.selectFile(fileList[1])
if self.exec():
fname = self.selectedFiles()
print(fname)
if __name__ == '__main__':
app = QApplication(sys.argv)
dlg = MyClass()
sys.exit(app.exec())

To turn back from 2nd window to 1st window (different files)

An application is being created with a large number of different windows.
The bottom line is that I am trying to get from the main window (by clicking button) to the client window. There is "Back" button in the clients window, which should return the user to the main window.
Both codes are in different files. The problem occurs at the stage of pressing the "Customers" button (Process finished with exit code -1073740791 (0xC0000409)).
Moreover, if everything is in one file, then everything works fine. But only here the program is not planned to be small, so I don't want to put a huge code in one file.
Welcome_Screen.py
import sys
from PyQt5.uic import loadUi
from PyQt5 import QtWidgets, QtGui
from PyQt5.QtWidgets import QDialog, QApplication
import Customers
class WelcomeScreen(QDialog):
def __init__(self):
super(WelcomeScreen, self).__init__()
loadUi('screens/welcomescreen.ui', self)
self.CustomerData.clicked.connect(self.go_to_CustomerData)
def go_to_CustomerData(self):
client = Customers.CustomerScreen()
widget.addWidget(client)
widget.setCurrentIndex(widget.currentIndex() + 1)
# main
app = QApplication(sys.argv)
app.setWindowIcon(QtGui.QIcon('Icons/MainIcon.png'))
app.setApplicationDisplayName('Bonus Program')
welcome = WelcomeScreen()
widget = QtWidgets.QStackedWidget()
widget.addWidget(welcome)
widget.setFixedWidth(600)
widget.setFixedHeight(475)
widget.show()
try:
sys.exit(app.exec_())
except:
print("Exiting")
Customers.py
import sys
from PyQt5.uic import loadUi
from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtWidgets import QDialog, QApplication, QWidget, QMessageBox, QTableWidget, QTableWidgetItem, QTableView
from PyQt5.QtSql import QSqlDatabase, QSqlTableModel, QSqlQuery
from PyQt5.QtGui import QIcon
import Welcome_Screen as ws
import sqlite3
db_path = 'Bonus_db.sqlite'
class CustomerScreen(QDialog):
def __init__(self):
super(CustomerScreen, self).__init__()
loadUi("screens/customerscreen.ui", self)
self.back_btn.setIcon(QIcon('Icons/Back.png'))
self.back_btn.setIconSize(QtCore.QSize(45, 60))
self.back_btn.clicked.connect(self.go_Back_to_WelcomeScreen)
# self.SoldTos.clicked.connect(self.gotoSoldTos)
def go_Back_to_WelcomeScreen(self):
welcome = ws.WelcomeScreen()
ws.widget.addWidget(welcome)
ws.widget.setCurrentIndex(ws.widget.currentIndex() + 1)
Customer_app = QApplication(sys.argv)
cust_window = CustomerScreen()
cust_window.show()
sys.exit(Customer_app.exec_())

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.

PyQt5 - how to bring the Qfiledialog to the front?

My code uses PyQt to open up a folder select dialog. Once a folder is selected it is minimized. I'd like for the dialog to pop up in front of any other windows. I haven't been able to find a solution yet. Any suggestions?
from sys import executable, argv
from subprocess import check_output
from PyQt5.QtWidgets import QFileDialog, QApplication
def gui_fname(directory=''):
file = check_output([executable, __file__, directory])
return file.strip()
if __name__ == "__main__":
directory = argv[1]
app = QApplication([directory])
folderpath = QFileDialog.getExistingDirectory(None, "Select folder")
I think your problem comes from the "None" in the following function.
folderpath = QFileDialog.getExistingDirectory(None, "Select folder")
The dialog modality cannot be set because it has no parent. Usually, instead of None we have self.
EDIT: Of cource app is not inheriting from QWidget. Sorry about that.
use this instead. I tested it an it work:
import sys
from subprocess import check_output
from PyQt5.QtWidgets import QFileDialog, QApplication, QWidget
def gui_fname(directory=''):
file = check_output([executable, __file__, directory])
return file.strip()
if __name__ == "__main__":
app = QApplication(sys.argv)
wid = QWidget()
folderpath = QFileDialog.getExistingDirectory(wid, "Select folder")
sys.exit(app.exec_())

how to add image with text in qlistwidget pyqt4 python?

How to add image/icon with text in a qlistwidget in pyqt4 python? I want to add an icon with text just like a chat system. thanks
I have tried this right now and it works, supposing you have a file named tick.png in the same folder as this script.
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QApplication, QDialog, QListWidgetItem, QListWidget, QIcon
def main():
app = QtGui.QApplication(sys.argv)
window = QDialog()
list = QListWidget( window )
itm = QListWidgetItem( "Tick" );
itm.setIcon(QIcon(r"tick.png"));
list.addItem(itm);
window.show( )
sys.exit(app.exec_())
if __name__ == '__main__':
main()
The chat-like-icon system may be different from this, but right now I don't see a way to have a QListWidgetItem with multiple smileys and text.
You may think of smileys as a particular case of a QListWidgetItem where the text is blank and only the icon is present.
Another solution is using a read-only QTextEdit as chatboard and have the user typing its text + icon + text (etc.) in a separate editable QTextEdit. Then, when he presses the send button, append everything he typed to the read-only QTextEdit.
import sys
from PyQt4 import QtGui, QtCore
from PyQt4.QtGui import QApplication, QDialog, QListWidgetItem, QListWidget, QIcon, QTextEdit, QTextDocumentFragment
def main():
app = QtGui.QApplication(sys.argv)
window = QDialog()
list = QListWidget( window )
textEditor = QTextEdit( window );
textEditor.setReadOnly( True )
tick_icon = QTextDocumentFragment.fromHtml(r"<img src='tick.png'>");
textEditor.insertPlainText ( " ValiumKnight writes: " )
textEditor.textCursor().insertFragment(tick_icon);
textEditor.insertPlainText ( " Hello World " )
textEditor.textCursor().insertFragment(tick_icon);
textEditor.textCursor().insertFragment(tick_icon);
textEditor.textCursor().insertFragment(tick_icon);
window.show( )
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Bye!

Categories

Resources