简体   繁体   中英

PyGTK: When filtering keyboard input to an Entry widget, can't correctly set the cursor position while opening a large buffer

I am writing a program with PyGTK for navigating large (>20 MB) text files. I am using a TextViewer widget for this, which handles them quite well except it takes several seconds to finish filling the corresponding TextBuffer. Meanwhile, I also have several dialogs that require filtering on their input (only hexadecimal digits or something). I pass the characters I want to allow and the name of a signal to this function:

def FilterText(self, chars, signal):

    def Filt(entry, text, length, position):
        position = entry.get_position()
        chrs = set(chars)
        realtext = ''.join([c for c in text if c in chrs])
        if len(realtext) > 0:
            entry.handler_block_by_func(Filt)
            entry.insert_text(realtext, position)
            entry.handler_unblock_by_func(Filt)
            newPos = position + len(realtext)
            gobject.idle_add(entry.set_position, newPos)
        entry.stop_emission(signal)
    return Filt

And then connect the result to the Entry widget's handler for that signal. This works, except that while the TextBuffer is being filled, none of the entry.set_position calls that were queued up get run until it finished. The result is that the cursor is stuck at the beginning of the Entry and everything typed is backwards which is, needless to say, quite annoying. This is presumably because there is no idle time until the TextBuffer is filled. Is there any way to work around this and allow the correct behavior when typing into a filtered Entry widget? (It should be possible, as no such problem is encountered with an unfiltered one) Calling entry.set_position directly doesn't work for some reason.

Finally figured it out--change the call

gobject.idle_add(entry.set_position, newPos)

To

gobject.timeout_add(0, entry.set_position, newPos)

Since entry.set_position returns None, it will call it once immediately, then never again, doing exactly what I wanted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM