问题
I want to make select rows of a PyGTK Tree-view (coupled to a List Store) un-selectable and if possible,greyed out.
Is there a way to do this?
回答1:
This is a bit hackish minimal code, but it will make it impossible to select the middle row ('B'). If you wish that the previous selection should be remembered it ought to be quite easy to just store which rows are selected at the end of the signal-callback and overwrite current selection if a bad row was selected.
As for the individual rows and making them grey, I'm not sure...but this example here seems to deal with it: 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()
回答2:
The right way to do this is by using gtk.TreeSelection.set_select_function. Regarding how to gray out rows, it's possible to make the renderers not sensitive for them (see sensitive=1
in the example below).
An example below:
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()
来源:https://stackoverflow.com/questions/12783444/making-rows-in-a-gtk-treeview-unselectable