I have troubles with saving note(text from QPlainTextEdit). I need only saving in txt format. After typing text and clicking button program displays error 'expected string or bytes-like object not nonetype'.Notepad's program starts from class fileeki till class fileush. I use Python 3.7, PyQt5 and QtDesigner for creating interface.Opening works well, but not saving.Please download all elements of my project. Also there is modules, which you must install.Thanks for trying.
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QPlainTextEdit
from PyQt5.QtWidgets import QLabel, QPushButton, QMessageBox, QFileDialog
from PyQt5.QtGui import QPixmap
class fileeki(QWidget):
def __init__(self, *args, **kwargs):
super().__init__()
uic.loadUi('uineweki.ui', self)
self.path = None
self.pushButton.clicked.connect(self.opening_run)
self.pushButton_2.clicked.connect(self.saving_run)
self.pushButton_3.clicked.connect(self.saveac)
self.pushButton_5.clicked.connect(self.new_run)
def dialog_critical(self, s):
dlg = QMessageBox(self)
dlg.setText(s)
dlg.setIcon(QMessageBox.Critical)
dlg.show()
def opening_run(self):
path, _ = QFileDialog.getOpenFileName(self, "Open file", "", "Text files (*.txt)")
if path:
try:
with open(path, 'rU') as f:
text = f.read()
except Exception as e:
self.dialog_critical(str(e))
else:
self.path = path
self.plainTextEdit.setPlainText(text)
def saving_run(self):
if self.path is None:
return self.saveac()
self._save_to_path(self.path)
def saveac(self):
path = QFileDialog.getSaveFileName(self, "Save file", "", "Text files (*.txt)")
if not path:
return
self._save_to_path(self.path)
def _save_to_path(self, path):
text = self.plainTextEdit.toPlainText()
try:
with open(path, 'w') as f:
f.write(text)
except Exception as e:
self.dialog_critical(str(e))
else:
self.path = path
def new_run(self):
self.plainTextEdit.clear()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = fileeki()
ex.show()
sys.exit(app.exec())
Link to my project on github: https://github.com/iMAGA07/notepadd
The error is because you are not actually using the returned data from the file dialog:
def saveac(self):
path = QFileDialog.getSaveFileName(self, "Save file", "", "Text files (*.txt)")
if not path:
return
self._save_to_path(self.path) # <-- here!
Also, the getSaveFileName static returns a tuple composed of file path and selected filter strings, and both of them could be empty if the dialog is cancelled, so if not path would always fail.
Check the returned data and call the _save_to_path accordingly:
def saveac(self):
path, filter = QFileDialog.getSaveFileName(self, "Save file", "", "Text files (*.txt)")
if not path:
return
self._save_to_path(path)
Related
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 am trying to create my own browser using Python QWebEngineView . I have followed a tutorial that worked on an previous version of PyQt5 (around 2015), but due to its recent updates, some parts of the previous code no longer work.
I have fixed most errors but I am unable to perform html file opening/saving. I always receive a system error when I click on the save button. The following is my code for file saving:
(QMainWindow class)
save_file_action = QAction(QIcon("disk--pencil.png"), "Save Page As...", self)
save_file_action.setStatusTip("Save current page to file")
file_menu.addAction(save_file_action)
(save_file function)
def save_file(self):
filename, _ = QFileDialog.getSaveFilename(self, "Save Page As", "",
"Hypertext Markup Language (*.htm *.html);;"
"All files(*.*)")
if filename:
html = self.browser.page().mainFrame().toHtml()
with open(filename, 'w') as f:
f.write(html)
Thank you.
the toHtml() function of QtWebEngine is asynchronous, so it does not return anything directly, but you have to pass it a callback so that in that function returns the html, to convert that process asynchronous to synchronous we use a QEventLoop with the help of a signal :
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *
class Browser(QMainWindow):
htmlFinished = pyqtSignal()
def __init__(self, *args, **kwargs):
QMainWindow.__init__(self, *args, **kwargs)
self.mHtml = ""
self.view = QWebEngineView()
self.setCentralWidget(self.view)
self.view.setUrl(QUrl("http://www.google.com/"))
file_menu = QMenu(self.menuBar())
file_menu.setTitle("File")
save_file_action = QAction(QIcon("disk--pencil.png"), "Save Page As...",self)
file_menu.addAction(save_file_action)
self.menuBar().addAction(file_menu.menuAction())
save_file_action.triggered.connect(self.save_file)
def callback(self, html):
self.mHtml = html
self.htmlFinished.emit()
def save_file(self):
filename, _ = QFileDialog.getSaveFileName(self, "Save Page As", "", "Hypertext Markup Language (*.htm *.html);;" "All files(*.*)")
if filename:
self.view.page().toHtml(self.callback)
loop = QEventLoop()
self.htmlFinished.connect(loop.quit)
loop.exec_()
with open(filename, 'w') as f:
f.write(self.mHtml)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Browser()
w.show()
sys.exit(app.exec_())
I'm trying to add a default name to QFileDialog() the images below illustrate.
This is what I get (no filename)
and this is what I want to achieve without having to input it manually, I want to pass the file_name threw a function and have that name show up there.
This is the code im trying to make to work:
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5 import *
import sys
class mainwindowUI(QMainWindow):
def __init__(self):
super(mainwindowUI, self).__init__()
self.exportFiles('test.mp3')
def exportFiles(self,file_name):
filename, _ = QFileDialog.getSaveFileName(self, "Save audio file", "", "Audio Files (*.mp3)")
if filename:
print(filename)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = mainwindowUI()
app.exec_()
I tried to add options:
filename, _ = QFileDialog.getSaveFileName(self, "Save audio file", "", "Audio Files (*.mp3)", options=QFileDialog.setLabelText(file_name))
But this is incorrect and i have no idea how to make it work...
Anyone know how to add a file name to save file dialog?
The third argument indicates the initial name:
def exportFiles(self, file_name):
default_dir ="/home/qt_user/Documents"
default_filename = os.path.join(default_dir, file_name)
filename, _ = QFileDialog.getSaveFileName(
self, "Save audio file", default_filename, "Audio Files (*.mp3)"
)
if filename:
print(filename)
First create a save-as action
self.saveas=QAction(QtGui.QIcon('saveas.png'),'save-as')
Add the save-as action to toolbar
toolbar=self.addToolbar('toolbar');
toolbar.addAction(self.saveas);
Sub this for your QFileDialog code
Fn, _=QFileDialog.getSaveFileName(self,'export pdf',file_name,'Pdf files(.pdf);;All files()');
when connecting the signal to the slot do this
Self.Saveas.toggled.connect(self.exportfiles('name of default file');
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 am trying to create my own browser using Python QWebEngineView . I have followed a tutorial that worked on an previous version of PyQt5 (around 2015), but due to its recent updates, some parts of the previous code no longer work.
I have fixed most errors but I am unable to perform html file opening/saving. I always receive a system error when I click on the save button. The following is my code for file saving:
(QMainWindow class)
save_file_action = QAction(QIcon("disk--pencil.png"), "Save Page As...", self)
save_file_action.setStatusTip("Save current page to file")
file_menu.addAction(save_file_action)
(save_file function)
def save_file(self):
filename, _ = QFileDialog.getSaveFilename(self, "Save Page As", "",
"Hypertext Markup Language (*.htm *.html);;"
"All files(*.*)")
if filename:
html = self.browser.page().mainFrame().toHtml()
with open(filename, 'w') as f:
f.write(html)
Thank you.
the toHtml() function of QtWebEngine is asynchronous, so it does not return anything directly, but you have to pass it a callback so that in that function returns the html, to convert that process asynchronous to synchronous we use a QEventLoop with the help of a signal :
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *
class Browser(QMainWindow):
htmlFinished = pyqtSignal()
def __init__(self, *args, **kwargs):
QMainWindow.__init__(self, *args, **kwargs)
self.mHtml = ""
self.view = QWebEngineView()
self.setCentralWidget(self.view)
self.view.setUrl(QUrl("http://www.google.com/"))
file_menu = QMenu(self.menuBar())
file_menu.setTitle("File")
save_file_action = QAction(QIcon("disk--pencil.png"), "Save Page As...",self)
file_menu.addAction(save_file_action)
self.menuBar().addAction(file_menu.menuAction())
save_file_action.triggered.connect(self.save_file)
def callback(self, html):
self.mHtml = html
self.htmlFinished.emit()
def save_file(self):
filename, _ = QFileDialog.getSaveFileName(self, "Save Page As", "", "Hypertext Markup Language (*.htm *.html);;" "All files(*.*)")
if filename:
self.view.page().toHtml(self.callback)
loop = QEventLoop()
self.htmlFinished.connect(loop.quit)
loop.exec_()
with open(filename, 'w') as f:
f.write(self.mHtml)
if __name__ == '__main__':
app = QApplication(sys.argv)
w = Browser()
w.show()
sys.exit(app.exec_())