[PyQt] binary file viewer with textEdit (PyQt) [correction]

Mark Summerfield list at qtrac.plus.com
Thu Jun 24 16:26:27 BST 2010


On 2010-06-24, sandokan wrote:
> Mark Summerfield-4 wrote:
> > [snip]
> > 
> > Actually I meant:
> >     file = QFile(self.filename)
> > 	
> >     if file.open(QIODevice::ReadOnly):
> > 	ba = file.readAll() # ba is a QByteArray filled with raw bytes
> > 	hexbytes = []
> > 	
> > 	for i in range(ba.count()):
> > 	    if QChar(" ") < QChar(ba[i]) < QChar(128):
> > 		hexbytes.append(ba[i].toAscii())
> > 		
> > 	    else:
> > 		hexbytes.append(ba[i].toHex())
> > 		# the above might need to be:
> > 		# hexbytes.append(QByteArray(ba[i]).toHex())
> > 		# or even:
> > 		# hexbytes.append(str(QByteArray(ba[i]).toHex()))
> > 	
> > 	self.ui.textEditAscii1.setPlainText("".join(hexbytes))
> > 
> > Still untested though!
> 
> Hmm, this appending approach is very slow again :( Moreover, I need to be
> able to print out also non-printable ASCII characters (0-32) and not to
> show them as hex.
> However thank you for you comments, I will try to think about different
> solution...if you have any other idea then please let me know
> 
> T.

Well here's one last sketch of an idea (and this will work well no
matter how big the file).

- Create a plain QWidget and lay it out with a vertical scrollbar.
- Set the QWidget's font to be fixed width.
- Use QFontMetrics for the fixed width font to calculate how many
  characters wide the widget is and how many lines high.
- Instead of reading the entire file, just read enough to occupy the
  space available and in the QWidget's paintEvent() use drawText() to
  draw them. 
- Set the scroll bar proportional to the size of the file and how much
  can be displayed.
- If the user scrolls read in what's needed and repaint.

This approach is a lot more work but potentially it could be very fast
and also use the least amount of memory.

Good luck!

-- 
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
    C++, Python, Qt, PyQt - training and consultancy
        "Advanced Qt Programming" - ISBN 0321635906
            http://www.qtrac.eu/aqpbook.html


More information about the PyQt mailing list