473,327 Members | 1,892 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,327 software developers and data experts.

PyQt4 trouble with save and load file dialogs...

blazedaces
284 100+
I'm designing a GUI for autonomous robot interaction, but that's not so important. To figure out the ins and outs of a certain aspect of PyQt I usually just do what I did when I learning Qt, I grab an example from the site and literally copy the code.

Unfortunately, PyQt isn't written exactly word-for-word as Qt is written in C++, obviously. So there's a slight conversation that I do to make it work. This can lead to errors at times. I've done it many times before, but now I'm having trouble.

So anyway, to get to the point, I'm programming this Application Example and the GUI actually starts up fine. Text can be typed, cut, copied and pasted with "Ctr+C", "Ctr+X", "Ctrl+V", even though the actual buttons for those do not work (in the toolbars and in the menu bars) that's not the problem I want to tackle at the moment.

When I try to open a file, it pops up with an error message, even though it should be possible to open a normal .txt file. If I try to save a file, it pops up with the same error message (which is reported as unknown).

Here's the code for the loadFile and saveFile methods where there's an if statement where if the file does not meet certain requirements an error message should arise:

Expand|Select|Wrap|Line Numbers
  1.     def loadFile(self, fileName):
  2.         file = QtCore.QFile(fileName)
  3.         if ~file.open(QtCore.QIODevice.ReadOnly | QtCore.QIODevice.Text):
  4.             QtGui.QMessageBox.warning(self, 'Application', QtCore.QString('Cannot read file %1:\n%2.').arg(fileName).arg(file.errorString()))
  5.             return
  6.  
  7.         _in = QtCore.QTextStream(file)
  8.         QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
  9.         self.textEdit.setPlainText(_in.readAll())
  10.         QtGui.QApplication.restoreOverrideCursor()
  11.  
  12.         self.setCurrentFile(fileName)
  13.         self.statusBar().showMessage('File loaded', 2000)
  14.  
  15.     def saveFile(self, fileName):
  16.         file = QtCore.QFile(fileName)
  17.         if ~file.open(QtCore.QIODevice.WriteOnly | QtCore.QIODevice.Text):
  18.             QtGui.QMessageBox.warning(self, 'Application', QtCore.QString('Cannot write file %1:\n%2.').arg(fileName).arg(file.errorString()))
  19.             return False
  20.  
  21.         _out = QtCore.QTextStream(file)
  22.         QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
  23.         _out.operator<<(self.textEdit.toPlainText())
  24.         QtGui.QApplication.restoreOverrideCursor()
  25.  
  26.         self.setCurrentFile(fileName)
  27.         self.statusBar().showMessage('File saved', 2000)
  28.         return True
If anyone can help me identify why, even though everything looks fine, it still pops up with an error every time, I would be very grateful.

Also, for more information, after I save, if I look in the directory where it was supposed to be saved a file exists there, but when trying to open the file, it shows up blank, as in it never contains the text that was supposed to be saved.

I've attempted to debug this slightly and I know it never leaves the inside of the if statement (it exits the method at "return" or "return False") as it makes sense it should if an error message comes up.

Thanks for your help,
-blazed
Aug 27 '08 #1
2 7062
blazedaces
284 100+
If no one can help me with this can someone please tell me what would be a good source for this problem?

Thanks a bunch,

-blazed
Aug 28 '08 #2
blazedaces
284 100+
Alright, I found a solution to the problem:

While it's nice to be able to use PyQt's I/O capabilities python has its own, so I used those instead and it worked just as needed:

Expand|Select|Wrap|Line Numbers
  1. def loadFile(self, fileName):
  2.         try:
  3.             file = open(fileName, 'r')
  4.         except IOError, (filename, message):
  5.             QtGui.QMessageBox.warning(self, 'Application', QtCore.QString('Cannot read file %1:\n%2.').arg(filename).arg(message))
  6.         except:
  7.             print "Unexpected error:", sys.exc_info()[0]
  8.             raise
  9.         else:
  10.             QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
  11.             self.textEdit.setPlainText(string.join(file.readlines()))
  12.             QtGui.QApplication.restoreOverrideCursor()
  13.  
  14.             self.setCurrentFile(fileName)
  15.             self.statusBar().showMessage('File loaded', 2000)
  16.         finally:
  17.             file.close()
  18.  
  19.     def saveFile(self, fileName):
  20.         try:
  21.             file = open(fileName, 'w')
  22.         except IOError, (filename, message):
  23.             QtGui.QMessageBox.warning(self, 'Application', QtCore.QString('Cannot write file %1:\n%2.').arg(filename).arg(message))
  24.         except:
  25.             print "Unexpected error:", sys.exc_info()[0]
  26.             raise
  27.         else:
  28.             QtGui.QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
  29.             file.write(self.textEdit.toPlainText())
  30.             QtGui.QApplication.restoreOverrideCursor()
  31.  
  32.             self.setCurrentFile(fileName)
  33.             self.statusBar().showMessage('File saved', 2000)
  34.             return True
  35.         finally:
  36.             file.close()
Works great.

Anyway, now my issue is the one I mentioned earlier with the cut/copy/paste mechanisms of Qt's textEditor.

I've noticed something odd that maybe will give someone a clue: of the three commands, only "cut" partially works. You see, paste does not paste from the clipboard and copy does not copy the selected text onto the clipboards. On the other hand, cut, for whatever reason, does indeed put the selected text onto the clipboard, but it does not remove the text selected (it doesn't cut, it copies), though the cursor itself moves, as in it no longer selects the text it previously did.

This might sound a bit confusing. I hope someone might be able to help, thanks guys.

-blazed
Aug 29 '08 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

7
by: Martin | last post by:
Again drawing on the groups experience:- 1. For general file opening and file saving, using VB6, are there any issues with using the FileOpen and FileSave Common Dialog Boxes? 2. Is using the...
0
by: Glenn M | last post by:
i have a web form with the following on load event Dim xml As New XPathDocument(XML_LOCATION + XML_FILE) Dim xslt As New XslTransform Dim SelectedTransform As String SelectedTransform = New...
2
by: Harshad | last post by:
Hi, I'm writing a program using Python 2.4 and PyQt4. The aim is to implement drag and drop from filesystem and display a list of files dragged on to the listWidget. This function will later...
2
by: ahynes | last post by:
HI folks, I need a script to open a .txt file, insert pre-defined text into the start and end of the file, then close teh saved file with a .nc extension. I'd like to have this so I can run it...
2
by: jiang.haiyun | last post by:
Hi, I am having some serious problems with PyQT4, when i run pyqt script, I always get 'Segmentation fault'. the script is simple: ====================== %less qttest.py from PyQt4 import...
2
by: paludi | last post by:
Hello, I export data to word using a template. then I want to save the template as word file. to set the file name i use the following code: With appWord.Dialogs(wdDialogFileSummaryInfo) ...
0
by: ppardi | last post by:
I'm developing an addin for Word 2007 and I need to determine whether a user saves a Word 2007 document in an older format (97-2003) after a save as is done. The scenario is that the user starts...
7
by: Pierre-Alain Dorange | last post by:
Hello, I'm new to python and i'm deelopping a small game with pygame. I got lot of fun with python. Trying to implement a config file to save user score and config. Reading doc and some...
5
matheussousuke
by: matheussousuke | last post by:
Hello, I'm using tiny MCE plugin on my oscommerce and it is inserting my website URL when I use insert image function in the emails. The goal is: Make it send the email with the URL...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.