I am using the code below for opening and reading text files in pyqt.
But what I want is:
I will choose any text file on my hard disk. Then right click on it and choose open with and browse for my pyqt script and the file will be open
with my sript.
I know that I can do it using 'sys.argv' in terminal. But how to do it with gui program? Please let me know.
Current code:
import sys
from PyQt4 import QtGui
from PyQt4 import QtCore
class OpenFile(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QMainWindow.__init__(self)
self.setGeometry(300, 300, 350, 300)
self.setWindowTitle('OpenFile')
self.textEdit = QtGui.QTextEdit()
self.setCentralWidget(self.textEdit)
self.statusBar()
self.setFocus()
exit = QtGui.QAction(QtGui.QIcon('open.png'), 'Open', self)
exit.setShortcut('Ctrl+O')
exit.setStatusTip('Open new File')
self.connect(exit, QtCore.SIGNAL('triggered()'), self.showDialog)
menubar = self.menuBar()
file = menubar.addMenu('&File')
file.addAction(exit)
def showDialog(self):
filename = QtGui.QFileDialog.getOpenFileName(self, 'Open file',
'/home')
file=open(filename)
data = file.read()
self.textEdit.setText(data)
app = QtGui.QApplication(sys.argv)
cd = OpenFile()
cd.show()
app.exec_()
Related
I'm building a program which uses QWebEngineView and QUrl to display a website in my PyQt5 app (running on Windows 10). However, I now want to be able to download a CSV file from the same website, but being a noob I can't seem to figure out how.
I'm familiar with using requests, urllib.request, urllib3, etc. for downloading files, but for this, I specifically want to do it with the QWebEngineView, as the user will have authenticated the request previously in the pyqt5 window.
The code to show the website in the first place goes like this:
self.view = QWebEngineView(self)
self.view.load(QUrl(url))
self.view.loadFinished.connect(self._on_load_finished)
self.hbox.addWidget(self.view)
Does anyone have any suggestion on how this can be achieved?
In QWebEngineView by default the downloads are not handled, to enable it you have to use the downloadRequested signal of QWebEngineProfile, this transports a QWebEngineDownloadItem that you have to accept if you want the download to start:
from PyQt5 import QtCore, QtWidgets, QtWebEngineWidgets
class Widget(QtWidgets.QWidget):
def __init__(self, parent=None):
super(Widget, self).__init__(parent)
self.view = QtWebEngineWidgets.QWebEngineView()
self.view.page().profile().downloadRequested.connect(
self.on_downloadRequested
)
url = "https://domain/your.csv"
self.view.load(QtCore.QUrl(url))
hbox = QtWidgets.QHBoxLayout(self)
hbox.addWidget(self.view)
#QtCore.pyqtSlot("QWebEngineDownloadItem*")
def on_downloadRequested(self, download):
old_path = download.url().path() # download.path()
suffix = QtCore.QFileInfo(old_path).suffix()
path, _ = QtWidgets.QFileDialog.getSaveFileName(
self, "Save File", old_path, "*." + suffix
)
if path:
download.setPath(path)
download.accept()
if __name__ == "__main__":
import sys
app = QtWidgets.QApplication(sys.argv)
w = Widget()
w.show()
sys.exit(app.exec_())
If you want to make a direct download you can use the download method of QWebEnginePage:
self.view.page().download(QtCore.QUrl("https://domain/your.csv"))
Update:
#QtCore.pyqtSlot("QWebEngineDownloadItem*")
def on_downloadRequested(self, download):
old_path = download.url().path() # download.path()
suffix = QtCore.QFileInfo(old_path).suffix()
path, _ = QtWidgets.QFileDialog.getSaveFileName(
self, "Save File", old_path, "*." + suffix
)
if path:
download.setPath(path)
download.accept()
download.finished.connect(self.foo)
def foo(self):
print("finished")
I have to write a program with an option to open an image from a file. I have to use QFileDialog and display image in QLabel, using QPixmap. I am able to use them individually but I didn't manage to combine them.
I think I need to take my image name from dlg.selectedFiles but I don't know how to choose the moment when there is useful data in it. Do I need to make a loop in my main program, and constantly check if there is image to open? Can I send a signal to my label using openAction.triggered.connect(...)?
from PyQt4 import QtGui
import sys
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent = None):
super(MainWindow, self).__init__(parent)
menubar = self.menuBar()
fileMenu = menubar.addMenu('File')
dlg = QtGui.QFileDialog(self)
openAction = QtGui.QAction('Open', self)
openAction.triggered.connect(dlg.open)
fileMenu.addAction(openAction)
#label = QtGui.QLabel(self)
#pixmap = QtGui.QPixmap('')
#label.setPixmap(pixmap)
def main():
app = QtGui.QApplication(sys.argv)
win = MainWindow()
win.show()
app.exec_()
if __name__ == '__main__':
sys.exit(main())
You need to make your own slot and connect it to the openAction signal.
In your __init__ function do:
openAction.triggered.connect(self.openSlot)
In your class MainWindow define the following function:
def openSlot(self):
# This function is called when the user clicks File->Open.
filename = QtGui.QFileDialog.getOpenFileName()
print(filename)
# Do your pixmap stuff here.
I am building a simple GUI for selecting files using PYQT, and I am working with the Spyder IDE. When I try to close the GUI with the red "X" button and run the file again, a warning message pops up that says:
No Python shell is currently selected to run **readFile.py**
Please select or open a new Python interpreter and try again
How can I make the red X button reinitialize the interpreter and console without having to manually do it every time? Here is my code:
from PyQt4 import QtGui
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
vbox = QtGui.QVBoxLayout()
lbl = QtGui.QLabel('Please Choose Excel File',self)
openButton = QtGui.QPushButton('Choose File')
openButton.clicked.connect(self.showDialog)
vbox.addWidget(lbl)
vbox.addWidget(openButton)
self.setLayout(vbox)
self.setGeometry(300,300,350,300)
self.setWindowTitle('file Dialog')
self.show()
def showDialog(self):
fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '/home')
print(fname)
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I am trying to use smc.FreeImage to load a .NEF files (Nikon Camera RAW) and Display with PySide.
I found this example that loads and displays the commented .JPG file just fine, but it crashes when I replace the pixmap with a FI.Image NEF.
I added the print pixmap.getInfoHeader to make sure the .NEF actually loads which it does, I see the correct Header information in the output window.
How do I translate the read pixmap = FI.Image so that PySide understands it ? I've seen people using numpy and PIL tostring but none of those examples seems to cover this case.
import sys
from PySide import QtGui, QtCore
from smc import freeimage as FI
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
hbox = QtGui.QHBoxLayout(self)
#pixmap = QtGui.QPixmap("Somefile.jpg")
pixmap = FI.Image("Anotherfile.NEF")
print( pixmap.getInfoHeader() )
lbl = QtGui.QLabel(self)
lbl.setPixmap(pixmap)
hbox.addWidget(lbl)
self.setLayout(hbox)
self.setGeometry(300, 300, 280, 170)
self.setWindowTitle('Da window Title')
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I have tested your minimal example.
Instead of using the smc module you can simple create a new QPixmap object and giving the path to the *.nef file as constructor parameter.
pixmap = QtGui.QPixmap("Path_To_File.NEF")
lbl = QtGui.QLabel(self)
lbl.setPixmap(pixmap)
I have tested your example and it worked without any problems.
I am writing a simple code using pyqt
In the code, I invoke a QFileDialog, however when I invoke it using the static functions all works fine, but with the normal method i.e. using dialog.exec_(), I do not see any files in the file dialog window.
Only after typing the complete path of the file can I see the file in the file dialog window.
Note that this issue is only when I invoke the FileDialoghandler function, If I don't do that, no matter how I invoke the QFileDialog, everything works fine.
And also this issue is only on Linux, on Windows7 everything works ok.
I am wondering whether this is a PyQt bug or am I missing something here?
Code is as follows:
import sys
from PyQt4.QtCore import Qt
from PyQt4.QtGui import *
from PyQt4.QtCore import QAbstractFileEngine
from PyQt4.QtCore import QAbstractFileEngineHandler
from PyQt4.QtCore import QFSFileEngine
class FileDialogHandler(QAbstractFileEngineHandler):
def create(self,filename):
if str(filename).startswith(':'):
return None # Will be handled by Qt as a resource file
print("Create QFSFileEngine for {0}".format(filename))
return QFSFileEngine(filename)
class Example(QMainWindow):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
self.textEdit = QTextEdit()
self.setCentralWidget(self.textEdit)
self.statusBar()
openFile = QAction(QIcon('open.png'), 'Open', self)
openFile.setShortcut('Ctrl+O')
openFile.setStatusTip('Open new File')
openFile.triggered.connect(self.showDialog)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(openFile)
self.setGeometry(300, 300, 350, 300)
self.setWindowTitle('File dialog')
self.show()
def showDialog(self):
handler = FileDialogHandler()
#using QFileDialog.getOpenFileName works fine
fname = QFileDialog.getOpenFileName(None, 'Open file', '/home','All files (*.*)')
#dialog = QFileDialog()
#dialog.setOption(QFileDialog.DontUseNativeDialog,False)
#if dialog.exec_():
#fname = dialog.selectedFiles()
#else:
#fname = None
f = open(fname, 'r')
with f:
data = f.read()
self.textEdit.setText(data)
def main():
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
I encountered a similar problem not long ago with the getOpenFilename. For me the solution was to change the backend from native to Qt's own implementation of the dialog. This can be achieved withan extended calling syntax which looks like:
filename = QtGui.QFileDialog.getOpenFileName(self,
'Open file',
'/home',
'All files (*.*)',
options=QtGui.QFileDialog.DontUseNativeDialog)
After I changed to this calling syntax I never had any problems again.
Encountered the same problem in Windows 10 running the code from command prompt without any IDE. Including options=QtGui.QFileDialog.DontUseNativeDialog did solve the problem. (with python 3.10). For Example:
self.path_open, _ = QFileDialog.getOpenFileName(self, "Open file", "", "e-documents (*.docx *.pdf)",
options=QFileDialog.DontUseNativeDialog)