PySide中的Unicode支持

时间:2014-06-08 07:19:02

标签: qt unicode pyside

我正在使用PyCharm 3.1和Python 2.7.6处理PySide 1.21和Qt 4.85。我希望我的应用程序支持unicode,所以在代码的开头我输入:

#--coding: utf-8 --

from PySide.QtCore import *
from PySide.QtGui import *
import sys
import math

class Form(QDialog):

    def __init__(self,parent=None):
        super(Form,self).__init__(parent)

        self.resultsList = QTextBrowser()
        self.resultsInput = QLineEdit("Enter an expression and press return key")
        layout = QVBoxLayout()

        layout.addWidget(self.resultsList)
        layout.addWidget(self.resultsInput)

        self.setLayout(layout)
        self.resultsInput.selectAll() # or
        self.resultsInput.setFocus()

        self.resultsInput.returnPressed.connect(self.compute)

    def compute(self):
        try:
            text = self.resultsInput.text()
            self.resultsList.append("{0} =<b>{1}</b>".format(text, eval(text)))

        except:
            self.resultsList.append("<font color=red><b>Expression Invalid</b></font>")
            # self.resultsList.append("<font color=red><b>格式错误</b></font>") ## unicode

app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()

当我使用unicode替换except块中的代码时,unicode在程序中没有正确显示。我哪里弄错了?问题是PySide,Qt还是一些设置错误?任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

最后我把它排序了。很简单,在python 2.7中,当你想支持unicode时,你需要声明:

#--coding: utf-8 --

在程序开始时,也就是在应用程序中进行硬编码时,需要在代码前面写“u”。例如:

 self.resultsList.append("<font color=red><b>Expression Invalid</b></font>")

需要写为:

self.resultsList.append(u"<font color=red><b>格式错误</b></font>") 

只是一点点“你”,问题就解决了。

相关问题