1

从 QCompleter 选择项目后,我从 QLineEdit 清除文本时遇到问题。我想打印从 QCompleter 中选择的项目的文本,然后立即清除 QLineEdit,我只成功打印了文本,但之后我无法清除 QLineEdit 文本。

这是我的代码:

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

2 回答 2

3

问题是QCompleter在分配值之前触发了激活的信号,以便最终clear()工作但QLineEdit在它为空时清除。解决方法是稍后清理一下,因为它QTimer可以使用:

def get_data_in_le(self):
    print(self.line_edit.text())
    QtCore.QTimer.singleShot(0, self.line_edit.clear)
于 2018-02-28T14:56:55.110 回答
2

更好的解决方案是:

self.connect(self.completer, QtCore.SIGNAL("activated(const QString&)"), self.line_edit.clear, QtCore.Qt.QueuedConnection)
于 2018-06-01T16:05:55.610 回答