本文介绍了PyQt - 多次使用 QLineEdit 的自动完成器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望有可能在我的 QLineEdit
中多次使用自动完成器,我找到了使用 QTextEdit
的示例,但我找不到 QLineEdit代码>.这是我使用的一段代码(非常简单):
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()
例如,如果我添加逗号,我希望完成者再次开始预测"同一 QLineEdit
中的单词.谢谢.
For example, I want the completer to "start predicting" again the words in the same QLineEdit
if I add a comma.Thanks.
推荐答案
我找到了可以帮助他人的答案,我为 Completer 创建了一个类:
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]
我在 QLineEdit 的类中使用它,例如:
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)
这篇关于PyQt - 多次使用 QLineEdit 的自动完成器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!