【问题标题】:Fail to clear QLineEdit after selecting QCompleter item选择 QCompleter 项后无法清除 QLineEdit
【发布时间】:2018-02-28 12:13:50
【问题描述】:

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

【问题讨论】:

    标签: python pyqt4 qlineedit qcompleter


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      更好的解决方案是:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-14
        • 2021-07-21
        • 2016-10-31
        • 2021-04-11
        • 1970-01-01
        • 1970-01-01
        • 2019-12-08
        相关资源
        最近更新 更多