pySQLite与pyGtk树视图集成

4 投票
1 回答
1694 浏览
提问于 2025-04-16 05:38

有没有简单的方法可以把sqlite数据库整合进gtk.TreeModel(树形视图)里呢?

我想要的是把数据库里的数据展示在树形视图中,如果我在数据库里改了什么,树形视图也能看到变化,反过来也一样。

1 个回答

3

假设你把所有的数据都放在了一个叫 itemlist 的地方:

cur.execute('''select * from warehouse''')
itemlist = cur.fetchall()

如果你想获取列的属性列表,可以这样做:

cur.execute('''PRAGMA table_info(warehouse)''')

如果你只想要列的名字,可以这样操作:

colnames = [ i[1] for i in cur.fetchall() ]

之后,你可能需要在 ListStore 中设置类型,以便用于你的 TreeView,可以这样做:

coltypes = [ i[2] for i in cur.fetchall() ]
for index, item in enumerate(coltypes):
    if (item == 'char'):
        coltypes[index] = str
    elif (item == 'integer'):
        coltypes[index] = int

然后把你数据库里的所有信息放到 TreeView 中:

store = gtk.ListStore(*coltypes)
for act in itemlist:
    store.append(act)

现在为 TreeView 创建列(假设它叫 'tree'):

for index, item in enumerate(colnames):
rendererText = gtk.CellRendererText()
column = gtk.TreeViewColumn(item, rendererText, text=index)
column.set_sort_column_id(index)
tree.append_column(column)

完成后,你应该会得到一个自动生成的 TreeView 组件,里面有正确的列和所有数据。来源:PyGTK中的高级组件

撰写回答