简体   繁体   中英

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()

The problem is that the activated QCompleter signal is triggered before assigning a value so that at the end clear() works but cleans the QLineEdit when it is empty. The solution is to clean up an instant later for it QTimer can be used:

def get_data_in_le(self):
    print(self.line_edit.text())
    QtCore.QTimer.singleShot(0, self.line_edit.clear)

更好的解决方案是:

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

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