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_())
Related
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())
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')
Currently I can open a folder by using
dirPath = os.path.dirname(os.path.abspath(self.oVidPath))
QDesktopServices.openUrl(QUrl.fromLocalFile(dirPath))
I want to know if there is anyway I can open folder with a file preselected?
I am okay if it only works on linux systems (nautilus is preferred)
edit : This application is only going be for linux systems
For windows
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.Qt import QProcess
if __name__ == '__main__':
app = QApplication(sys.argv)
command = "explorer /e, /select, c:\\windows\\regedit.exe"
process = QProcess()
process.start(command)
sys.exit(app.exec_())
For Linux
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.Qt import QProcess
if __name__ == '__main__':
app = QApplication(sys.argv)
command = "nautilus /var/log/dpkg.log"
process = QProcess()
process.start(command)
sys.exit(app.exec_())
FYI https://askubuntu.com/a/82717/249546
This example creates a single QListWidget with its items right-click enabled.
Right-click brings up QMenu. Choosing a menu opens a OS File Browser in a current user's home directory.
After a File Browser is closed QMenu re-appears which is very annoying.
How to avoid this undesirable behavior?
import sys, subprocess
from os.path import expanduser
from PyQt4 import QtGui, QtCore
class Window(QtGui.QWidget):
def __init__(self):
QtGui.QWidget.__init__(self)
layout = QtGui.QVBoxLayout(self)
self.listWidget = QtGui.QListWidget()
self.listWidget.addItems(('One','Two','Three','Four','Five'))
self.listWidget.setContextMenuPolicy(QtCore.Qt.CustomContextMenu)
self.listWidget.connect(self.listWidget,QtCore.SIGNAL('customContextMenuRequested(QPoint)'),self.showMenu)
self.menu=QtGui.QMenu()
menuItem=self.menu.addAction('Open Folder')
self.connect(menuItem,QtCore.SIGNAL('triggered()'),self.openFolder)
layout.addWidget(self.listWidget)
def showMenu(self, QPos):
parentPosition=self.listWidget.mapToGlobal(QtCore.QPoint(0, 0))
menuPosition=parentPosition+QPos
self.menu.move(menuPosition)
self.menu.show()
def openFolder(self):
if sys.platform.startswith('darwin'):
subprocess.call(['open', '-R',expanduser('~')])
if sys.platform.startswith('win'):
subprocess.call(['explorer','"%s"'%expanduser('~')])
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())
Two ideas come to my mind:
Try adding self as a constructor parameter when defining QMenu(), passing your QWidget as a parent.
Call self.menu.hide() in the openFolder() method.
Tip: instead of using subprocess to open up explorer, there's an arguably better, cross platform solution in Qt called QDesktopServices - see http://pyqt.sourceforge.net/Docs/PyQt4/qdesktopservices.html
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!