Display last added item in ComboBox - Python - python

I have a GUI with a tool button next to a Combobox. The tool button opens a directory browser to select a file and then adds that file Name to the Combobox drop-down list.
def showFileOpenDialogLoad(self):
""" Opens dialog to get Load file path """
filename = QFileDialog.getOpenFileName(self, 'Open file',
'/home')
self.comboBoxFilePathLoad.addItem(filename)
This works perfectly, however, I then want the Combobox to directly display the last added filename. I have tried using .insertItem(0,filename)instead and then setting self.comboBoxFilePathLoad.currentIndex = -1but it still displays the first added filename even though in the Dropdown list the last added filename is now above the old and displayed one. Apparently in C# you would use cmbBox.SelectedIndex = cmbBox.Items.count -1 but Pyqt does not have a SelectedIndexmethod.
This does not seem like such a difficult question but somehow I can not find a solution to it online... The QComboBox Class Reference does not explain count and CurrentIndex either. Thank you for your help!

Related

How to correctly use File Explorer browse function - PySimpleGUI

I am trying to use the browse function in PySimpleGUI. I have used PySimpleGUI file browser specific file type to find out how to browse. However there are two file types that I want to choose from and multiple files need to be selected for this to work. My question:
How do you use the browse function for browsing two types of files? and also How do you allow multiple files to be browsed? and finally How do you tell each file apart?
I know that there is a key function for getting data but how can I do that for more than one file.
In case you are a tiny bit confused:
The user must select the browse function and must be able to choose from .txt and .Docx files while selecting more than one file. The program must be able to tell the difference between the files so a function can be run on each file separately.
My code so far:
import PySimpleGUI as sg
sg.theme('DarkAmber') # Add a touch of color
# All the stuff inside your window.
layout = [ [sg.FileBrowse(file_types=(("Text Files", "*.txt"),))],
[sg.Button('Lets GO!!!')]
]
# Create the Window
window = sg.Window('Test', layout).Finalize()
window.Maximize()
Can someone finish this code?
According to the documentation:
file_types=(("Text Files", "*.txt"),("CSV Files", "*.csv"),)
works.

How can PyQt be used to select a save location for a new Folder

I am trying to use PyQt to open a file dialog and then allow the user to select a new location to create a new directory which will be used in the program.
Currently my code looks like this:
dialog = QFileDialog()
dialog.setOption(QFileDialog.ShowDirsOnly, True)
dialog.setWindowTitle(title)
dialog.setAcceptMode(QFileDialog.AcceptOpen)
dialog.setNameFilter(nameFilter)
dialog.setFileMode(QFileDialog.Directory)
if dialog.exec_() == QFileDialog.Accepted:
return dialog.selectedFiles()[0]
However in the file dialog all the files are still shown and their is no option to select a directory if the user want to overwrite it.
The wanted outcome would show just the directories in the explorer.
Is there a way of doing this using PyQt file dialogs?

Setting QFileDialog

I am using static method:
path = QtGui.QFileDialog.getSaveFileName(self, SAVE_TO_STR, NAME_STR, 'CSV(*.csv)')
where I get path as full_path\some_name.csv
but I need to set different language to buttons and labels of dialog, so I've been looking at docs and find out that I can't do that with static method and I've come up with this code:
ddd = QtGui.QFileDialog(self, SAVE_TO_IN_OTHER_LANGUAGE_STR, NAME_STR, 'CSV(*.csv)')
ddd.setAcceptMode (QtGui.QFileDialog.AcceptSave)
ddd.setLabelText( QtGui.QFileDialog.Accept, "Save - in other language" )
ddd.setLabelText( QtGui.QFileDialog.Reject, "Cancel - in other language" )
ddd.setLabelText( QtGui.QFileDialog.LookIn, "Look in - in other language" )
if ddd.exec_():
path = QtCore.QString(ddd.selectedFiles()[0])
I am trying to set it to look like first one so my questions are:
path I get is ok, but missing .csv at the end, so it saves file with no extension.
should I manually add .csv at the end of the path?
when I choosing where to save and click on folder, "save" button turns to "open". How to change that button text to "Open" in other language?
folders list at the left side of dialog is not complex as when I use QtGui.QFileDialog.getSaveFileName() , it shows only My Computer and User, instead of modern tree with favorites and partitions under My Computer.
1) path I get is ok, but missing .csv at the end, so it saves file with
no extension. should I manually add .csv at the end of the path?
Answer: I think you shouldn't manually add .csv at the end of the path. In PyQt API have this solution to solve it, use QFileDialog.setDefaultSuffix (self, QString suffix);
pathQFileDialog = QtGui.QFileDialog(self)
pathQFileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
pathQFileDialog.setNameFilter('CSV(*.csv)')
pathQFileDialog.setDefaultSuffix('csv')
Reference: http://pyqt.sourceforge.net/Docs/PyQt4/qfiledialog.html#setDefaultSuffix
2) when I choosing where to save and click on folder, "save" button
turns to "open". How to change that button text to "Open" in other
language?
Answer: My opinion of PyQt, No. In Qt (C++) at file qfiledialog.cpp I found your problem in method void QFileDialogPrivate::_q_updateOkButton() at line between 2886 and 2888. It force "&Open" label;
button->setEnabled(enableButton);
if (acceptMode == QFileDialog::AcceptSave)
button->setText(isOpenDirectory ? QFileDialog::tr("&Open") : acceptLabel);
Reference: https://qt.gitorious.org/qt/qt/source/57756e72adf2081137b97f0e689dd16c770d10b1:src/gui/dialogs/qfiledialog.cpp#L2796-2888
3) folders list at the left side of dialog is not complex as when I use
QtGui.QFileDialog.getSaveFileName() , it shows only My Computer and
User, instead of modern tree with favorites and partitions under My
Computer.
Answer: Because on Windows, Mac OS X and Symbian^3, this static function (QtGui.QFileDialog.getSaveFileName()) will use the native file dialog and not a QFileDialog.
Reference: pyqt.sourceforge.net/Docs/PyQt4/qfiledialog.html#getSaveFileName
Regards,

Python - keeping Tkinter window open?

Right now I am using Tkinter to prompt the user for a file.
Tk().withdraw() # keep the root window from appearing
file_path = askopenfilename() # show dialog box and return file path
# check if extension is valid
If the user selected the wrong file type, I re-prompt them with a new window.
Is there a way, instead, to keep the same tkinter window open unless the file selected is valid?
so instead of this:
# 1) prompt user to open file
# 2) close file browser window
# 3) check if extension is valid
# 4) if not, print error and re-prompt user with new browser window
I want to do this:
# 1) prompt user to open file
# 2) check if extension is valid while keeping window open
# 3) if not, print error, re-prompting with same window
Any help is appreciated.
If you want the user to open a particular file type, use the filetypes argument. It takes a list of file type definitions, which you specify as a description and an extension:
filepath = askopenfilename(filetypes = [
('Text Files', '.txt'),
('Python Scripts', '.py'),
('INI Files', '.ini')
])
You could set the file browser window to only display the file type you want to user to select, but they can get around that rather easy by selecting the type drop down box. You could however on file select (user clicks OK to select the file and close the file browser window) check to see if the file extension is one of the types you desire and if it is not simple clear the file path variable and call the file browser open function again. That way they are trapped in selecting a file until they select the correct file type. This does however present the issue of them possible no knowing why they are back where they started from, so you may want to add a popup window or something before reopening the file browser window to make it a little more user friendly.

Python Qt QFileDialog::getopenFileNames - File select order

I'm writing a small Python code to join text files, and the files are selected as an user input. But it's important that I get the order of the users selection, as I want to join the files in the selected order. But I see that the list returned by getOpenFileNames does not preserve the selection order.
Does anybody have any suggestion to capture the selection order?
Thank you.
I originally wanted to suggest writing a callback for the currentChanged signal that tracks the selection, but it seems like this signal doesn't get called when using getOpenFileNames. An alternative would be displaying the dialog with show() and connecting a callback to filesSelected, which is called after the user clicks the "open" button on the dialog. The argument to the callback is a list with the selected files which seems to be in the order of their selection (just tested it on python3/pyqt4).
def callback(files):
joined_files = ''.join([open(f).read() for f in files])
do_something_with(joined_files)
dialog = QtGui.QFileDialog()
dialog.setFileMode(3) #allow selection of multiple files
dialog.filesSelected.connect(callback)
dialog.show()
One problem with this is that the order isn't indicated to the user in an easy way - the "file" textbox contains the ordered files' names, but this is messy when you select more than a few files. A better but slightly more complicated approach would be building a widget or dialog with a FileDialog for selecting files and a List/TableWidget holding the files to process, where the user could add Files one at a time. This would allow for a better overwiew as well as easy selection of files from multiple directories and better extendability (e.g. filtering, rearranging, sorting the selection).
self.filename = QtGui.QFileDialog.getOpenFileNames(
self,
"Cargar tu documento",
self.lastOpenedFile,
"*.doc;*.odt;*.pdf" )

Categories