PyQt Qstring not accepted when script run from WIndows command line, why?

306 views Asked by At

Using PyQt 4, Python 2.7, Windows 7 on a x64 machine.

I have been developing a bit of code using a Python console with PyQt4 and passing strings from QLineEdit() widgets to OS commands with no issues using os.system(cmd)

But when I tried running from the command line in Windows I get the following error,

TypeError: sequence item 0: expected string, QString found

I got around this by converting the offending string via str(cmd) but it has left me curious about, why this should happen only when the code is called from the command line and not when called within a Python console?

2

There are 2 answers

0
Hamza Abbad On

I think that this problem happens because the command line parameters are actually byte arrays and not strings, strings are encoded in Unicode, but byte arrays are not. Calling str(cmd) return the content of cmd as a string.

0
three_pineapples On

I'm not sure why this is happening exactly (given that you're just using the standard Python console), but it is possible to configure PyQt methods to return python strings rather than QStrings. I suspect that your Python console is doing this, but your script is not. Again, I really can't see why the normal python console would do this automatically, unless our definition of a normal python console is somehow different (by normal console I mean running just python.exe from a terminal). However, it is the only explanation I have short of you actually running different code in the console and not realising.

So, the PyQt documentation covers how to disable QStrings using the sip module. You just do this before importing PyQt4.

import sip
sip.setapi('QString', 2)

If you do this in your Python script, then you should get identical behaviour between the console and the command line.

You can also do a similar thing to disable QVariant and other annoying Qt types that are often pointless in Python.