我想让 PyGTK 树视图(耦合到列表存储)的选定行不可选择,如果可能的话,变灰。
有没有办法做到这一点?
正确的方法是使用gtk.TreeSelection.set_select_function
. 关于如何使行变灰,可以使渲染器对它们不敏感(参见sensitive=1
下面的示例)。
下面的一个例子:
import pygtk
pygtk.require('2.0')
import gtk
def main():
"""Display treeview with one row not selectable."""
window = gtk.Window()
store = gtk.ListStore(str, bool)
for row in (('A', True), ('B', False), ('C', True)):
store.append(row)
treeview = gtk.TreeView(store)
renderer = gtk.CellRendererText()
column = gtk.TreeViewColumn('Name', renderer, text=0, sensitive=1)
treeview.append_column(column)
window.add(treeview)
selection = treeview.get_selection()
selection.set_select_function(
# Row selectable only if sensitive
lambda path: store[path][1]
)
selection.set_mode(gtk.SELECTION_MULTIPLE)
window.show_all()
gtk.main()
if __name__ == '__main__':
main()
这是一个有点骇人听闻的最小代码,但它将无法选择中间行('B')。如果您希望记住先前的选择,应该很容易只存储在信号回调结束时选择了哪些行,如果选择了错误的行,则覆盖当前选择。
至于各个行并使它们变灰,我不确定......但这里的这个例子似乎可以处理它:http ://coding.debuntu.org/python-gtk-treeview-rows-different-colors
import pygtk
pygtk.require('2.0')
import gtk
def clicked(selection):
global selection_signal
liststores, listpaths = selection.get_selected_rows()
for selected_row in xrange(len(listpaths)):
#The 1 looks for the 'B' row
if listpaths[selected_row][0] == 1:
#Blocking the handler so that the reverting doesn't invoke a callback
selection.handler_block(selection_signal)
selection.unselect_path(listpaths[selected_row])
selection.handler_unblock(selection_signal)
w = gtk.Window()
treemodel = gtk.ListStore(str)
for r in ('A', 'B', 'C'):
treemodel.append([r])
treeview = gtk.TreeView(treemodel)
w.add(treeview)
tv_cell = gtk.CellRendererText()
tv_column = gtk.TreeViewColumn("Header", tv_cell, text=0)
treeview.append_column(tv_column)
selection = treeview.get_selection()
selection_signal = selection.connect("changed", clicked)
selection.set_mode(gtk.SELECTION_MULTIPLE)
w.show_all()