How to pickle QStandardItem Objects

271 views Asked by At

I am trying to pickle QStandardItem objects of PyQt5,

import sys
from PyQt5.Qt import QStandardItem, QStandardItemModel
from PyQt5.QtWidgets import  QTreeView, QApplication, QMainWindow
import shelve

app = QApplication(sys.argv)

Level1 = QStandardItem("Level1")
Level2 = QStandardItem("Level2")
Level3 = QStandardItem("Level3")

Level1.appendRow(Level2)
Level2.appendRow(Level3)

dbs = shelve.open("dbs")
dbs["Level1"] = Level1
dbs.close()

but it report this error TypeError: can't pickle QStandardItem objects

Then I changed to code to :

import sys
from PyQt5.Qt import QStandardItem, QStandardItemModel
from PyQt5.QtWidgets import  QTreeView, QApplication, QMainWindow
import shelve

app = QApplication(sys.argv)

class myStandardItem(QStandardItem):
    def __init__(self, *kargs):
        QStandardItem.__init__(self, *kargs)

    def __getstate__(self):
        return self.__dict__

Level1 = myStandardItem("Level1")
Level2 = myStandardItem("Level2")
Level3 = myStandardItem("Level3")

Level1.appendRow(Level2)
Level2.appendRow(Level3)

dbs = shelve.open("dbs")
dbs["Level1"] = Level1
dbs.close()


dbs_new = shelve.open("dbs")
Level1_new = dbs_new["Level1"]

if Level1.hasChildren() :
    print("Level 1 has children")

if Level1_new.hasChildren():
    print("Level 1 new has children")


dbs_new.close()

it can be pickled, but I load the picked object, it reports:

RuntimeError: super-class init() of type myStandardItem was never called

what's wrong with the above code? How to pickle QstandardItem with children? and reload successfully?

Thanks.

0

There are 0 answers