[pygtk] Find string within TextBuffer
Christian Becke
christianbecke at web.de
Sun Mar 15 19:40:49 WST 2009
Lupine schrieb:
> findentry = self.widgets.get_widget('find_entry').get_text()
> txtbuffer = self.widgets.get_widget('pref_hosts_txtview').get_buffer()
> start = txtbuffer.get_start_iter()
> first, last = start.forward_search(findentry, gtk.TEXT_SEARCH_TEXT_ONLY)
> line_number = str(first.get_line())
> if first:
> print 'found entry:' + line_number
>
> So, finally, now that I have it actually finding the line number of the
> searched for string, I should be able to figure out how to get the
> gtk.TextView to scroll to that line number, and highlight the found
> text.
I think you don't need to find the line number, all you need are the
gtk.TextIters returned by start.forward_search ():
textview = self.widgets.get_widget('pref_hosts_txtview')
textview.scroll_to_iter (first, 0)
Regards,
Christian
P.S.: Here is a working example:
import gtk
def on_find_clicked (tv, e):
needle = e.get_text ()
print needle
if needle:
tb = tv.get_buffer ()
s = tb.get_start_iter ()
f, l = s.forward_search (needle, gtk.TEXT_SEARCH_TEXT_ONLY)
tv.scroll_to_iter (f, 0)
w = gtk.Window ()
w.set_default_size (200, 300)
w.connect ('destroy', gtk.main_quit)
vb = gtk.VBox ()
w.add (vb)
vb.show ()
sw = gtk.ScrolledWindow ()
sw.set_policy (gtk.POLICY_NEVER, gtk.POLICY_AUTOMATIC)
vb.pack_start (sw, True, True)
sw.show ()
tv = gtk.TextView ()
sw.add (tv)
tv.show ()
hb = gtk.HBox ()
vb.pack_start (hb, False)
hb.show ()
e = gtk.Entry ()
hb.pack_start (e, True)
e.show ()
b = gtk.Button ("Find")
b.connect_object ('clicked', on_scroll_clicked, tv, e)
hb.pack_start (b, False)
b.show ()
tb = tv.get_buffer ()
f = open (__file__, 'r')
tb.set_text (f.read ())
f.close ()
w.show ()
gtk.main ()
More information about the pygtk
mailing list