我正在将一些代码从 PyQt 移植到 PySide,其中包括一个本地开发的 XML 导出器。代码中充满了这样的行:
Qt.escape(textNote)
这对我来说是新的。我的 PyQt 书(萨默菲尔德,2008 年)写道:
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.
但不幸的是,对于我从文本创建 XML 的目标,escape 似乎不再被使用。
这个问题在我发现的两个来源中进行了讨论:
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/
不幸的是,他们都建议使用QString.toHtmlEscaped(),但是这个方法在 PySide 中似乎不存在(事实上,QString 不是 PySide 词典的一部分)。
最后,截至四年前,escape 似乎不是他们打算在 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.
这似乎回答了我的问题,但它已有四年历史了,我很好奇它是否仍然有效。也就是说,没有PySide的转义功能,那么去saxutils是最好的选择吗?或者可能有一些类似于我忽略的 PySide 中的 toHtmlEscaped 的解决方法?
请您参考如下方法:
每次你都会用
Qt.escape(yourText)
您可以获得完全相同的功能
from xml.sax.saxutils import escape as escape
escape(yourText)
它有点不太优雅,但它确实有效。 PySide 开发人员与他们的 initial reaction to a question 保持一致。关于这个四年前。
