使用JSON序列化Gtk TreeStore / ListStore

时间:2015-04-26 12:09:03

标签: json serialization gtk pygobject

我做了一个新的例子,它显示了我想做的更好。新示例给出了以下输出。有没有一种方法可以将数据放入相应的商店密钥({}括号)?

false

新示例

{
    "copy": [
        [
            [
                5.0,
                8.0,
                9.0
            ]
        ],
        [
            [
                4.0,
                0.0,
                1.0
            ]
        ]
    ],
    "name": "dataset1",
    "sets": [
        {
            "store": {},
            "type": "vector"
        },
        {
            "store": {},
            "type": "vector"
        }
    ]
}

旧例子

我目前正在弄清楚如何序列化嵌套在Gtk TreeStore中的Gtk ListStore。我有一个小例子可以工作,但我不确定这种方法是否会扩展到附加了更多数据的程序(例如,图层对象可以保存颜色或创建日期)。还有其他方法吗?

我目前的方法是自己以列表和字典形式收集数据,然后创建JSON转储。我觉得如果我需要为每个图层对象附加25个值,这将很难维护。

from gi.repository import Gtk
import json
import random

class Vector(object):

    def __init__(self, data):
        self.store = Gtk.ListStore(float, float, float)
        self.store.append([data[0], data[1], data[2]])
        self.type = "vector"

    def return_data(self):
        store_data = []

        def iterate_over_data(model, path, itr):
            row = model[path]
            store_data.append([row[0], row[1], row[2]])

        self.store.foreach(iterate_over_data)

        return store_data

class DataSet(object):

    def __init__(self, name):
        self.name = name
        self.sets = []

    def add_vector(self):
        data = [random.randint(0,9) for x in range(3)]
        self.sets.append(Vector(data))

    def to_json(self):
        self.copy = []
        for s in self.sets:
            self.copy.append(s.return_data())

        return json.dumps(self, default=lambda o: o.__dict__, 
            sort_keys=True, indent=4)

obj1 = DataSet("dataset1")
for x in range(2):
    obj1.add_vector()

print(obj1.to_json())

1 个答案:

答案 0 :(得分:3)

我有一个带有dict理解的代码的改进版本和@staticmethod,它使信号回调更具可读性和更短。然而,这并没有真正解决您的问题,因为它仍然手动生成json。如果ListStore变得更复杂,那么让DataListStore类用相应的方法生成自己的json可能会更好。

from gi.repository import Gtk, Gdk
import json


class LayerTreeView(Gtk.TreeView):

    def __init__(self, store):
        Gtk.TreeView.__init__(self, store)
        renderer = Gtk.CellRendererText()
        column = Gtk.TreeViewColumn("Name", renderer, text=0)
        self.append_column(column)


class DataTreeView(Gtk.TreeView):

    def __init__(self):
        Gtk.TreeView.__init__(self)
        renderer = Gtk.CellRendererText()
        column = Gtk.TreeViewColumn("Data", renderer, text=0)
        self.append_column(column)

class DataListStore(Gtk.ListStore):

    @staticmethod
    def from_json(*args, values=[]):
        store = DataListStore(*args)
        for value in values:
            store.append((value,))
        return store


class MainWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="TreeView Serialize")
        self.connect("delete-event", Gtk.main_quit)
        self.set_border_width(10)
        self.set_default_size(400, 300)
        vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6, expand=True)
        self.add(vbox)

        self.clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)

        hbox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
        button = Gtk.Button("Cut")
        button.connect("clicked", self.on_cut_clicked)
        hbox.pack_start(button, True, True, 0)

        button = Gtk.Button(stock=Gtk.STOCK_COPY)
        button.connect("clicked", self.on_copy_clicked)
        hbox.pack_start(button, True, True, 0)

        button = Gtk.Button(stock=Gtk.STOCK_PASTE)
        button.connect("clicked", self.on_paste_clicked)
        hbox.pack_start(button, True, True, 0)
        vbox.add(hbox)

        self.layer_store = Gtk.TreeStore(str, object)
        self.layer_view = LayerTreeView(self.layer_store)
        self.data_view = DataTreeView()

        layer_sw = Gtk.ScrolledWindow()
        layer_sw.add(self.layer_view)
        data_sw = Gtk.ScrolledWindow()
        data_sw.add(self.data_view)

        treebox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6, expand=True)
        treebox.pack_start(layer_sw, True, True, 0)
        treebox.pack_start(data_sw, True, True, 0)
        vbox.add(treebox)

        select = self.layer_view.get_selection()
        select.connect("changed", self.on_selection_changed)

        self.add_test_data()

    def add_test_data(self):
        for x in range(3):
            data_list = [str(y+x) for y in range(5)]
            self.layer_store.append(None, ["Data {}".format(x), data_list])

    def on_selection_changed(self, selection):
        """
        When layer is switched load respective data
        """
        model, treeiter = selection.get_selected()
        if treeiter != None:
            self.data_view.set_model(
                DataListStore.from_json(str, values=model[treeiter][1])
            )

    def on_cut_clicked(self, button):
        pass

    def on_copy_clicked(self, button):
        copy_list = [
            'safe-to-paste',
            {row[0]: row[1] for row in self.layer_store},
        ]
        data = json.dumps(copy_list)
        self.clipboard.set_text(data, -1)

    def on_paste_clicked(self, button):
        paste_str = self.clipboard.wait_for_text()
        try:
            parse = json.loads(paste_str)
        except:
            return

        if parse[0] != "safe-to-paste":
            return

        data_dict = parse[1]
        for x in data_dict:
            self.layer_store.append(None, [x, data_dict[x]])

win = MainWindow()
win.show_all()
Gtk.main()