问题
I want to have the possibility to use multiple times the auto completer in my QLineEdit
, I found example using QTextEdit
but I can't find for QLineEdit
. here is a piece of code I use (very simple one) :
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
def main():
app = QApplication(sys.argv)
edit = QLineEdit()
strList = ["Germany", "Spain", "France", "Norway"]
completer = QCompleter(strList,edit)
edit.setCompleter(completer)
edit.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
For example, I want the completer to "start predicting" again the words in the same QLineEdit
if I add a comma.
Thanks.
回答1:
I've found the answer if it can help others, I created a class for Completer :
class Completer(QtWidgets.QCompleter):
def __init__(self, parent=None):
super(Completer, self).__init__(parent)
self.setCaseSensitivity(Qt.CaseInsensitive)
self.setCompletionMode(QtWidgets.QCompleter.PopupCompletion)
self.setWrapAround(False)
# Add texts instead of replace
def pathFromIndex(self, index):
path = QtWidgets.QCompleter.pathFromIndex(self, index)
lst = str(self.widget().text()).split(',')
if len(lst) > 1:
path = '%s, %s' % (','.join(lst[:-1]), path)
return path
# Add operator to separate between texts
def splitPath(self, path):
path = str(path.split(',')[-1]).lstrip(' ')
return [path]
And I use it within a class for QLineEdit like :
class TextEdit(QtWidgets.QLineEdit):
def __init__(self, parent=None):
super(TextEdit, self).__init__(parent)
self.setPlaceholderText("example : ")
self._completer = Completer(self)
self.setCompleter(self._completer)
回答2:
Solution for PyQt4:
from PyQt4 import QtCore, QtGui
class Completer(QtGui.QCompleter):
def __init__(self, *args, **kwargs):
super(Completer, self).__init__(*args, **kwargs)
self.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.setCompletionMode(QtGui.QCompleter.PopupCompletion)
self.setWrapAround(False)
# Add texts instead of replace
def pathFromIndex(self, index):
path = QtGui.QCompleter.pathFromIndex(self, index)
lst = str(self.widget().text()).split(',')
if len(lst) > 1:
path = '%s, %s' % (','.join(lst[:-1]), path)
return path
def splitPath(self, path):
path = str(path.split(',')[-1]).lstrip(' ')
return [path]
class TextEdit(QtGui.QLineEdit):
def __init__(self, parent=None):
super(TextEdit, self).__init__(parent)
words = ["alpha", "omega", "omicron", "zeta"]
self.setPlaceholderText("example : ")
self._completer = Completer(words, self)
self.setCompleter(self._completer)
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
w = TextEdit()
w.show()
sys.exit(app.exec_())
来源:https://stackoverflow.com/questions/35628257/pyqt-auto-completer-with-qlineedit-multiple-times