[PyQt] binary file viewer with textEdit (PyQt)

Mark Summerfield list at qtrac.plus.com
Thu Jun 24 13:13:36 BST 2010


On 2010-06-24, sandokan wrote:
> Mark Summerfield-4 wrote:
> > One thing that slows QTextEdit down is its sophisticated layout engine.
> > If you can live without that and use a QPlainTextEdit you should get
> > some speedup straightaway.
> 
> Wow, this works perfectly fine. However, I still have a problem with 
binary
> file representation in a text field. Zeros (00h) are not visible at all
> (zeros are not represented by white space as expected). So for example:
> this:
> "2E 64 6C 6C 00 4F 4C 45" (in hex)
> should be represented as:
> ".dll OLE"
> but is represented as:
> ".dllOLE"
> 
> Maybe its because of chosen encoding but "mbcs" was only one which could
> displayed binary file in QTextEdit at all:
> s = codecs.open(self.filename,'rb','mbcs').read()
> self.ui.textEditAscii1.setPlainText(s)
> 
> Do you know any other encoding for binary files which could be used and
> handled correctly by QTextEdit or should I change my approach completely
> and try to display binary files other way?

Personally, I wouldn't take that approach at all. If the file is binary
then it isn't a text file so no encoding is correct.

So I'd do something like this (untested):

    file = QFile(self.filename)
    if file.open(QIODevice::ReadOnly):
	ba = file.readAll() # ba is a QByteArray filled with raw bytes
	for i in range(ba.count()):
	    if QChar(" ") < QChar(ba[i]) < QChar(128):
		ba[i] = ba[i].toAscii()
	self.ui.textEditAscii1.setPlainText(ba)


-- 
Mark Summerfield, Qtrac Ltd, www.qtrac.eu
    C++, Python, Qt, PyQt - training and consultancy
        "Rapid GUI Programming with Python and Qt" - ISBN 0132354187
            http://www.qtrac.eu/pyqtbook.html

                            A true story...
 I ordered a Dell netbook with Ubuntu preinstalled. It arrived with no
 OS at all and Dell's "support" said they don't supply Ubuntu any more.
           Dell gave no apology, no solution, and no refund.
                     So I do *not* recommend Dell.


More information about the PyQt mailing list