Search code examples
pythonpyqt4qlineeditqcompleter

Fail to clear QLineEdit after selecting QCompleter item


I have a problem clearing text from QLineEdit after selecting item from QCompleter. I want to print the text of the item selected from QCompleter and then immediately clear QLineEdit, I only succeeded in printing the text, but I couldn't manage to clear the QLineEdit text afterwards.

This is my code:

import sys
from PyQt4 import QtGui, QtCore

auto_completer_words = ["chair"]


def get_data(model):
    model.setStringList(auto_completer_words)


class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        super(self.__class__, self).__init__()
        self.resize(300, 300)

        self.line_edit = QtGui.QLineEdit(self)
        self.line_edit.setGeometry(QtCore.QRect(100, 100, 100, 30))

        self.completer = QtGui.QCompleter()
        self.line_edit.setCompleter(self.completer)

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

        self.completer.activated.connect(self.get_data_in_le)


def get_data_in_le(self):
    print(self.line_edit.text())
    self.line_edit.clear()


def main():
    app = QtGui.QApplication(sys.argv)
    w = MainWindow()
    w.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

Solution

  • A better solution is:

    self.connect(self.completer, QtCore.SIGNAL("activated(const QString&)"), self.line_edit.clear, QtCore.Qt.QueuedConnection)