Search code examples
pythonpyqtqlineeditqcompleter

Move the cursor to the start after auto-completion


I have a small program where I used a line edit for auto-completion. After selecting the text, my cursor goes to end of the text. So how to set my cursor to the starting position?

My code:

import sys
from PyQt4.QtCore import Qt
from PyQt4.QtGui import QApplication, QCompleter, QLineEdit, QStringListModel

def get_data(model):
   model.setStringList(["completion_xxxxxxxxxx", "data_yyyyyyyyyy", "goes_ccccccccc", "here"])

if __name__ == "__main__":

    app = QApplication(sys.argv)
    edit = QLineEdit()
    edit.setCursorPosition(0)
    completer = QCompleter()
    edit.setCompleter(completer)

    model = QStringListModel()
    completer.setModel(model)
    get_data(model)

    edit.show()
    sys.exit(app.exec_())

enter image description here

But I want to show it like this:

enter image description here


Solution

  • Assuming you want the cursor to move after the completion has finished, you can use the completer's activated signal with a single-shot timer, like this:

    completer.activated.connect(
        lambda: QTimer.singleShot(0, lambda: edit.home(False)))