开发者

How can I update QTextEdit as user writes on it? (on Python)

I'm working on a Python+Qt WebSMS app/script. It asks for a number and message, and sends it to Vodafone via mechanize. Since Vodafone of my country doesn't support UTF-8, at least for WebSMS and every SMS should be shorter than 160 chars, I'm using th开发者_开发百科is setup:

def setMesaj():
  global mesaj
  mesaj = unicode(self.textEdit.toPlainText().toUtf8(), "utf-8")
  mesaj = mesaj.encode("ascii", "ignore")
  if (len(mesaj)) > 159:
    print "[WARN-1] Mesaj 160 karakterden fazla?"
    i = len(mesaj) - 159
    mesaj = mesaj [:-i]
  print mesaj


QtCore.QObject.connect(self.textEdit, QtCore.SIGNAL("textChanged()"), setMesaj)

Well, It works. If message goes over 160 chars, the last letter is automatically removed, and If user tries to type any "weird" character, It's not accepted.

Here's my question: The variable 'mesaj' works perfectly, but It doesn't update the QTextEdit thing, so when It doesn't get anything over 160 chars (or Unicode), it still looks like allowed to the user. So, how can I update QTextEdit as user writes on it and make the changes appear syncronized?

Thanks,


def setMesaj(self):
  mesaj = unicode(self.toPlainText().toUtf8(), "utf-8")
  ascii = mesaj.encode("ascii", "ignore")
  if ascii != mesaj:
    self.setPlainText(ascii)

  if (len(mesaj)) > 159:
    QtGui.QMessageBox.warning(self, 'warning', "[WARN-1] Mesaj 160 karakterden fazla?")
    i = len(mesaj) - 159
    mesaj = mesaj [:-i]
    self.setPlainText(mesaj)

This would be my quick and dirty approach, however you still have to put the text cursor in the correct position after making the edits.


One way to detect the right position for the text cursor would be to use codecs.register_error to define a custom error function, one that duplicates "ignore", but also remembers how many characters in front of the cursor were deleted, and to shift the cursor that many positions to the left after encoding.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜