Wasiq Kashkari
Wasiq Kashkari

Reputation: 61

Get text as the user is typing in a gtk.TextBuffer

I was wondering if there is a way to print input from a TextBuffer while the user is typing it. I have tried using the insert_text signal but it seems to be printing out the input one character behind.

so far I have

self.__buffer.connect('insert_text', self.__inserted)
def __inserted(self, widget, iter, string, length):
    print self.__buffer.get_text(self.__buffer.get_start_iter(),self.__buffer.get_end_iter())

the above code prints out the buffer 1 character behind what is actually being typed.

The functionality I want goes something like this:

if the user inputs "hello"

output should be

h              #after h typed
he             #after he typed 
hel            #etc
hell
hello

currently it is printing

#after h typed
h             #after he typed
he            #etc
hel
hell

Upvotes: 1

Views: 1422

Answers (1)

James Henstridge
James Henstridge

Reputation: 43899

You will probably find that the missing data is found in the arguments passed to your __inserted method. The GtkTextBuffer object's default handler for the insert_text signal seems to be what is responsible for inserting the text into the buffer, and your signal handler runs before hand.

Two possible ways to work around this are:

  1. Use connect_after to hook up your signal handler. This will run after the default handler.

  2. If you just want access to the entire buffer's worth of data after each change, consider using the changed signal instead. This is emitted after the next text has been inserted into the buffer, and will also notify you of deletions.

Upvotes: 3

Related Questions