简体   繁体   中英

Can't Pickle QLabel object in Python

I am trying to serialize a QLabel subclass using pickle in python but after being unpickled the text does not seem to be set. What am I doing wrong or what should I be doing instead to make this work?

class TestClass(QLabel):

    def __init__(self):
        super().__init__()
        self.setText("SomeText")

    def __getstate__(self):
        return self.__dict__.copy()

    def __setstate__(self, state):
        super().__init__()
        self.__dict__.update(state)
        tc = TestClass()
        print(tc.text())
        res = pickle.dumps(tc)
        print(f"Dumps: {res}")
        res = pickle.loads(res)
        print(f"Loads: {res}")
        print("unpickled text:", repr(res.text()))

Output:

SomeText
Dumps: b'\x80\x03ctestClass\nTestClass\nq\x00)\x81q\x01}q\x02b.'
Loads: <testClass.TestClass object at 0x0000027E64146048>
unpickled text: ''

I'd expect the text after being unpickled to be the same "SomeText" but it doesn't seem to be the case.

Your QLabel's state is not maintained by your Python object's internal __dict__ , so you must (de)serialize it explicitly:

class TestClass(QLabel):

    def __init__(self):
        super().__init__()
        self.setText("SomeText")

    def __getstate__(self):
        return {
            "__TEXT__": self.text()
        }

    def __setstate__(self, state):
        super().__init__()
        self.setText(state.get("__TEXT__", ""))

Output:

SomeText
Dumps: b'\x80\x03c__main__\nTestClass\nq\x00)\x81q\x01}q\x02X\x08\x00\x00\x00__TEXT__q\x03X\x08\x00\x00\x00SomeTextq\x04sb.'
Loads: <__main__.TestClass object at 0x7f18a90215f0>
unpickled text: 'SomeText'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM