#LineEdit添加历史记录功能,按下回车添加至历史中 class LineEditWithHistory(QtWidgets.QLineEdit): def __init__(self, parent ,inputList=[]): super(LineEditWithHistory, self).__init__(parent) #用于存放历史记录的List self.inputList = inputList #LineEdit设置QCompleter,用于显示历史记录 self.completer = QtWidgets.QCompleter(self) self.listModel = QtCore.QStringListModel(self.inputList, self) self.completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive) self.completer.setModel(self.listModel) self.completer.activated.connect(self.Slot_completer_activated) self.setCompleter(self.completer) #输入完成按下回车后去重添加到历史记录中 self.returnPressed.connect(self.Slot_editingFinished) def Slot_editingFinished(self): content = self.text() if content != "": if content not in self.inputList: self.inputList.append(content) self.listModel.setStringList(self.inputList) self.completer.setCompletionMode(QtWidgets.QCompleter.PopupCompletion) #按下回车后恢复显示模式 https://doc.qt.io/qt-5/qcompleter.html#activated def Slot_completer_activated(self,text): self.completer.setCompletionMode(QtWidgets.QCompleter.PopupCompletion) def event(self, event): #按下Tab键时弹出所有记录 if event.type() == QtCore.QEvent.KeyPress and event.key() == QtCore.Qt.Key_Tab: #设置不过滤显示 https://doc.qt.io/qt-5/qcompleter.html#completionMode-prop self.completer.setCompletionMode(QtWidgets.QCompleter.UnfilteredPopupCompletion) self.completer.complete() self.completer.popup().show() return True return super().event(event)
原文:https://www.cnblogs.com/Summerio/p/11733976.html