我一直在使用这里找到的代码:
How to limit number of decimal places to be displayed in Gtk CellRendererText
几年来成功地格式化了Treeview数字列。但是当我使用循环插入列时,列显示的是第一列中的数据,而不是我希望从ListStore中获取的数据。为什么会这样?我已经为此挣扎了一段时间了,这可能是一个非常简单的解决方案,但我相当无知!!非常感谢你。下面是一个可以说明我的问题的有效示例:
from gi.repository import Gtk, Gdk
class myClass:
def __init__(self):
# Setup
self.iListstore = Gtk.ListStore(str, float, float, float, float)
self.iListstore.append(['abc',209.8967,568.56432, 1, 2])
self.iListstore.append(['def',2409.846,559.534, 3, 4])
self.window = Gtk.Window()
self.iTreeView = Gtk.TreeView(self.iListstore)
# Column 0
lblr= Gtk.CellRendererText()
lcol = Gtk.TreeViewColumn('Row Label')
self.iTreeView.append_column(lcol)
lcol.pack_start(lblr, True)
lcol.add_attribute(lblr, 'text',0)
# Column 1
cr = Gtk.CellRendererText(xalign=1)
myCol = Gtk.TreeViewColumn('Col1')
myCol.set_sort_column_id(1)
self.iTreeView.append_column(myCol)
myCol.pack_start(cr, True)
myCol.add_attribute(cr, 'text',1)
myCol.set_cell_data_func(cr,lambda column, cell, model, iter, unused:cell.set_property("text","{0:.2f}".format(round(model.get(iter,1)[0],2))))
# Column 2
myCol = Gtk.TreeViewColumn('Col2')
myCol.set_sort_column_id(2)
self.iTreeView.append_column(myCol)
myCol.pack_start(cr, True)
myCol.add_attribute(cr, 'text',2)
myCol.set_cell_data_func(cr,lambda column, cell, model, iter, unused:cell.set_property("text","{0:.2f}".format(round(model.get(iter,2)[0],2))))
# The above works but the following does not. Col3 has the same value as Col4. Can someone tell me the reason a loop can not be used with the code?
colNames=['Col3','Col4']
for i in range(3,5):
myCol = Gtk.TreeViewColumn(colNames[i-3]) # I realize this is a bit of a fudge
myCol.set_sort_column_id(i)
self.iTreeView.append_column(myCol)
myCol.pack_start(cr, True)
myCol.add_attribute(cr, 'text',i)
myCol.set_cell_data_func(cr,lambda column, cell, model, iter, unused:cell.set_property("text","{0:.2f}".format(round(model.get(iter,i)[0],2))))
# Window
self.window.add(self.iTreeView)
self.window.show_all()
def main(self):
Gtk.main()
p=myClass()
p.main()
我真的尝试过使用Libeforce的链接来运行lambda函数(再次感谢!)但解决不了。根据What do (lambda) function closures capture?,“诀窍是记住循环不会创建新的作用域”,因此下一列永远不会更改。我中断了函数,代码现在可以工作了:
相关问题 更多 >
编程相关推荐