0

我正在尝试腌制 PyQt5 的 QStandardItem 对象,

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()

但它报告这个错误TypeError: can't pickle QStandardItem objects

然后我将代码更改为:

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()

它可以被腌制,但我加载了挑选的对象,它报告:

RuntimeError:从未调用过 myStandardItem 类型的超类init ()

上面的代码有什么问题?如何与孩子一起腌制 QstandardItem?并重新加载成功?

谢谢。

4

0 回答 0