且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PyQt:数据不是JSON可序列化的

更新时间:2022-11-22 20:45:38

如果将PyQt5或Python3与PyQt4一起使用,则不会出现此类错误,因为PyQt总是会尽可能返回普通的Python类型.但是您将Python2与PyQt4结合使用,这意味着您必须明确要求该行为.

If you use PyQt5, or Python3 with PyQt4, you will not get this kind of error, because PyQt will always return ordinary Python types whenever possible. But you are using Python2 with PyQt4, which means you have to explicitly request that behaviour.

为此,请按以下步骤更改导入:

To do that, change your imports as follows:

import sip
sip.setapi('QString', 2)
sip.setapi('QVariant', 2)
from PyQt4.QtCore import *
from PyQt4.QtGui import *

(请注意,setapi调用必须必须在应用程序中首次导入任何PyQt模块之前.)

(And note that the setapi calls must go before the first import of any PyQt modules in your application).

有了这个,您还需要将代码简化为此:

With that in place, you will also need to simplify your code to this:

   def personalData(self):
      print type(self.s1_val.text())
      if not self.s1_val.text():
         print "s1 is empty"
         #self.popup_window()
      if not self.s2_val.text():
         print "s2 is empty"
      if not self.s3_val.text():
         print "s3 is empty"
      if not self.s4_val.text():
         print "s4 is empty"
      if not self.s5_val.text():
         print "s5 is empty"

      if self.s1_val.text() and self.s2_val.text():
         Data1 = {'systemID': self.s1_val.text()}
         self.personaldata = json.dumps(Data1)
         print ("personal json ready")

PS:

如果您刚开始学习Python和/或PyQt,我强烈建议您尽可能使用Python3和PyQt5.

If you're just starting out learning Python and/or PyQt, I would strongly recommend that you use Python3 and PyQt5 if at all possible.