Alternatives to Qt.escape in PySide? - python

I am porting some code from PyQt to PySide, which includes a home-grown XML exporter. The code is peppered with lines like:
Qt.escape(textNote)
This is new to me. My PyQt book (Summerfield, 2008) writes:
The Qt.escape() function takes a QString and returns it with any XML
metacharacters properly escaped. And we...convert any
paragraph and line breaks in the notes to their Unicode equivalents.
But unfortunately for my goal of creating XML from text, escape seems to no longer be in use.
This issue is discussed at two sources I found:
http://qt-project.org/wiki/Transition_from_Qt_4.x_to_Qt5#f166611e9788f9dbdff69088d622663e
http://www.kdab.com/automated-porting-from-qt-4-to-qt-5/
Unfortunately, they both suggest to use QString.toHtmlEscaped() but this method seems to not exist in PySide (indeed, QString is not part of PySide's lexicon).
Finally, as of four years ago, it seemed escape is not something that they intended to support in PySide, as discussed at a bug report:
After a discussion with other PySide developers, we decided not export
this function, the reasons are:
This function is part of QtGui, if we create a QtGui.Qt, this will cause some headaches with QtCore.Qt.
PyQt4 also didn't export this function.
There are functions in python std lib that you can use to achieve the same goals, like xml.sax.saxutils.escape().
So, I'll mark this bug as WONTFIX.
This seems to answer my question, but it is four years old, and I am curious if it still holds. That is, is there no PySide escape functionality, so is the best option to go to saxutils? Or perhaps is there some workaround akin to toHtmlEscaped in PySide that I've overlooked?

Every time you would have used
Qt.escape(yourText)
you can get the exact same functionality with
from xml.sax.saxutils import escape as escape
escape(yourText)
It's a little less elegant, but it works. The PySide developers have remained consistent with their initial reaction to a question about this four years ago.

Related

proper replacement of QString().arg method in python3

When it comes to internationalization - using python2 and PyQt4 - the "proposed way" to format a translated string is using the QString.arg() method:
from PyQt4.QtGui import QDialog
#somewhere in a QDialog:
self.tr("string %1 %2").arg(arg1).arg(arg2)
But QString() doesn't exist in python3-PyQt4.
So my question is, what is the best way to format any translated strings in python3? Should I use the standard python method str.format() or maybe there is something more suitable?
The QString::arg method is really there as a workaround for C++'s limited string formatting support, to make sure you don't use sprintf with all the problems that entails (not handling placeholders that are in different orders in different languages, buffer overruns, etc.). Because Python doesn't have any such problems, there's no good reason to use it.
In fact, there's very little reason to ever use QString explicitly. In PyQt4, it wasn't phased out completely, but by PyQt5, it was. (Technically, PyQt4 supports "string API v2" in both Python 2.x and 3.x, but only enables it by default in 3.x; PyQt4 enables v2 by default in both, and hides the ability to switch back to v1.) See Python Strings, Qt Strings and Unicode in the documentation for some added info.
There is one uncommon, but major if it affects you, exception: If you're writing an app that's partly in Qt/C++ and partly in PyQt, you're going to have problems sharing I18N data when some of them are in "string %1 %2" format and others are in "string {1} {2}" format. (The first time you ship one of your file out to an outsourced translation company, they're going to get it wrong, guaranteed.)
Yes, just use standard python string formatting.
QString is gone because it's pretty much interchangable with python's unicode strings (which are str in python3 and unicode in python2), so PyQt takes care of converting one into the other as needed.
QString being disabled isn't limited to python3, it's just the default there. You can get the same on python2 by doing this befor importing anything from PyQt4:
import sip
sip.setapi('QString', 2)

Setting and getting "data" from PyQt widget items?

This is not so much a question as it is a request for an explanation. I'm following Mark Summerfield's "Rapid GUI Programming with Python and Qt", and I must've missed something because I cannot make sense of the following mechanism to link together a real "instance_item" which I am using and is full of various types of data, and a "widget_item" which represents it in a QTreeWidget model for convenience.
Setting:
widget_item.setData(0, Qt.UserRole, QVariant(long(id(instance_item))))
Getting
widget_item.data(0, Qt.UserRole).toLongLong()[0]
Stuff like toLongLong() doesn't seem "Pythonic" at all, and why are we invoking Qt.UserRole and QVariant? are the "setData" and "data" functions part of the Qt framework or is it a more general Python command?
There are at least 2 better solutions. In order of increasing pythonicity:
1) You don't need quite so much data type packing
widget_item.setData(0, Qt.UserRole, QVariant(instance_item))
widget_item.data(0, Qt.UserRole).toPyObject()
2) There is an alternate API to PyQt4 where QVariant is done away with, and the conversion to-from QVariant happens transparently. To enable it, you need to add the following lines before any PyQt4 import statements:
import sip
sip.setapi('QVariant', 2)
Then, your code looks like this:
widget_item.setData(0, Qt.UserRole, instance_item)
widget_item.data(0, Qt.UserRole) # original python object
Note that there is also an option sip.setapi('QString', 2) where QString is done away with, and you can use unicode instead.
All of these methods -- setData(), data(), toLongLong() are all part of Qt and were originally intended to be used in C++, where they make a lot more sense. I'm not really sure what the author is trying to do here, but if you find yourself doing something terribly un-pythonic, there is probably a better way:
## The setter:
widget_item.instance_item = instance_item
## The getter:
instance_item = widget_item.instance_item
The Qt docs can't recommend this, of course, because there are no dynamic attribute assignments in C++. There are a few very specific instances when you may have to deal with QVariant and other such nonsense (for example, when dealing with databases via QtSQL), but they are quite rare.

Basic GUI for Python? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Practical GUI toolkit?
Hi,
I'm just getting my head around Python, and have been building some stuff from tutorials, examples, etc. As my programs are getting more complex after a few weeks' tinkering, I'm getting overwhelmed by the pile of data my console is serving me (working on an app with lots of input/output currently) and would like to move into something a bit more visual to organize my feedback.
I've found a few visual modules, but it seems like tkinter is the standard/easiest to start with. I just need a configurable window, some text and basic shapes for now. Any heads up before I get my hands dirty (if it makes any difference - remember, I'm working on something that updates/redraws periodically)?
Thanks.
If you are working with scientifical data you should check Traits and Traits UI
The Traits UI package is a set of user
interface tools designed to complement
Traits. In the simplest case, it can
automatically generate a user
interface for editing a Traits-based
object, with no additional coding on
the part of the programmer-user. In
more sophisticated uses, it can
implement a Model-View-Controller
(MVC) design pattern for Traits-based
objects.
It comes in the enthough python edition together with other, more conventional, modules for data representation (ie matplotlib) storage (ie pyTables...) and gui building.
easygui is perhaps - no definitely the easiest GUI module for python I have worked with. A Google search shows that it can be downloaded from here. I installed my version a while back and don't need to use it too often and therefore am not sure whether the above download is what I have (it shouldn't matter too much), but if you have such concerns, then you can download the version I have from this page
Hope this Helps

best way to parse a language that's ALMOST Python?

I'm working on a domain-specific language implemented on top of Python. The grammar is so close to Python's that until now we've just been making a few trivial string transformations and then feeding it into ast. For example, indentation is replaced by #endfor/#endwhile/#endif statements, so we normalize the indentation while it's still a string.
I'm wondering if there's a better way? As far as I can tell, ast is hardcoded to parse the Python grammar and I can't really find any documentation other than http://docs.python.org/library/ast.html#module-ast (and the source itself, I suppose).
Does anyone have personal experience with PyParsing, ANTLR, or PLY?
There are vague plans to rewrite the interpreter into something that transforms our language into valid Python and feeds that into the Python interpreter itself, so I'd like something compatible with compile, but this isn't a deal breaker.
Update: It just occurred to me that
from __future__ import print_function, with_statement
changes the way Python parses the following source. However, PEP 236 suggests that this is syntactic window dressing for a compiler feature. Could someone confirm that trying to override/extend __future__ is not the correct solution to my problem?
PLY works. It's odd because it mimics lex/yacc in a way that's not terribly pythonic.
Both lex and yacc have an implicit interface that makes it possible to run the output from lex as a stand-alone program. This "feature" is carefully preserved. Similarly for the yacc-like features of PLY. The "feature" to create a weird, implicit stand-alone main program is carefully preserved.
However, PLY as lex/yacc-compatible toolset is quite nice. All your lex/yacc skills are preserved.
[Editorial Comment. "Fixing" Python's grammar will probably be a waste of time. Almost everyone can indent correctly without any help. Check C, Java, C++ and even Pascal code, and you'll see that almost everyone can indent really well. Indeed, people go to great lengths to indent Java where it's not needed. If indentation is unimportant in Java, why do people do such a good job of it?]

Syntax Highlighting in Cocoa TextView? Experiences? Suggestions? Ideas? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Syntax coloring for Cocoa app
I'm interested in syntax highlighting in a Cocoa TextView.
I found several resources:
approach with flex, via a flex pattern matched against textStorageDidProcessEditing
in a TextView delegate. In this approach the whole string get parsed on each input event, hence performance degrades.
CocoaDev has an own page on the topic of syntax highlighting:
Use NSTextStorageDidProcessEditingNotification, then get the edited range, and just apply the coloring there. The range might be wordboundaries or anything; this definitely improves performance.
Mentioned there: Xcode, for example, only colorizes text that's currently on-screen, and defers colorizing the rest of the document until you scroll through it. How would one implement this?
Use NSLayoutManager – via Temporary attributes [which] are used only for on-screen drawing and are not persistent in any way... as the docs say, but that doesn't color the last edited range, until a whitespace character is entered.
Custom Helper like UKSyntaxColoredDocument – nice, but language definition is done via property list; how to use additional/existing language definitions?
None of the approaches seem really extensible or robust to me (except the 4. maybe ..).
I am aware of robust existing libraries for SH like pygments; and of PyObjC.
Question: How would it be possible to use some existing library e.g. like pygments to have an extensible and performant syntax highlighting in a Cocoa TextView?
Note: I know this question is very broad (and much too long). Experiences and suggestions as well as solutions are welcome. Thanks.
Found another similar thread on that matter: Syntax coloring for Cocoa app
I would suggest taking a look at the source code to Smultron. It has very nice syntax highlighting. It uses a subclass of NSTextView to do most of the heavy lifting. The code uses the layout manager to add attributes to the text and uses some other clever tricks to only highlight as much of the document as necessary.

Categories

Resources