Frage

I have something like an instant search in PyQt4 using the textChanged signal from QLineEdit.

The search is sufficiently fast but updating the QTextEdit with the results is kind of slow (or the function i wrote, which builds the output string). Anyway is there a way of retarding the search a bit or interrupt it if a new textChanged signal is released within a certain amount of time? The goal is to avoid that the input 'hangs' when typing something into the search field at common typing speed.

Or any other suggestion to solve this issue? Maybe without threading..

Basically it looks like this

class MyApp(..):

    def __init__(self):
        ....

        self.central.editSearch.textChanged.connect(self.search_instant)

    def search_instant(self, query):
        # skip strings with less than 3 chars
        if len(query) < 3:
            return
        self.search()

    def search(self)
        ... search in lots of strings ...
        self.central.myTextEdit.setText(result)
        # reimplemented function building the output

Okay, here is what I made from the Google Example, peakxu suggested

class MyApp(..):

    def __init__(self):
        ....

        self.central.editSearch.textChanged.connect(self.search_instant)

        # Timer for instant search
        # Signal is emitted 500 ms after timer was started
        self.timer = QTimer()
        self.timer.setSingleShot(True)
        self.timer.setInterval(500)
        self.timer.timeout.connect(self.search)


    def search_instant(self, query):
        # Stop timer (if its running)
        self.timer.stop()

        # skip strings with less than 3 chars
        if len(query) < 3:
            return

        # Start the timer
        self.timer.start()    

    def search(self)
        # The search will only performed if typing paused for at least 500 ms
        # i. e. no `textChanged` signal was emitted for 500 ms
        ... search in lots of strings ...
        self.central.myTextEdit.setText(result)
        # reimplemented function building the output
War es hilfreich?

Lösung

There are several alternatives which you may want to consider.

  1. Let search run in thread, interrupt if necessary. See https://qt-project.org/forums/viewthread/16109
  2. Block signals until prior search completes. http://qt-project.org/doc/qt-4.8/qobject.html#blockSignals
  3. Write your own debounce wrapper around the search function.

First option sounds best at the moment.

Update: The Qt Google Suggest example might be a helpful reference. They use a QTimer to track time between user input.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top