您必须重写 pathFromIndex 方法,以便当您选择一些文本时,在 QLineEdit 中写入适当的选项,并且要更改弹出窗口中显示的内容,应使用委托。
from PyQt5 import QtCore, QtGui, QtWidgets
def create_model(d):
model = QtGui.QStandardItemModel()
for key, value in d.items():
for val in value:
it = QtGui.QStandardItem(key)
it.setData(val, QtCore.Qt.UserRole)
model.appendRow(it)
return model
class StyledItemDelegate(QtWidgets.QStyledItemDelegate):
def initStyleOption(self, option, index):
super(StyledItemDelegate, self).initStyleOption(option, index)
option.text = index.data(QtCore.Qt.UserRole)
class Completer(QtWidgets.QCompleter):
def __init__(self, parent=None):
super(Completer, self).__init__(parent)
QtCore.QTimer.singleShot(0, self.change_delegate)
@QtCore.pyqtSlot()
def change_delegate(self):
delegate = StyledItemDelegate(self)
self.popup().setItemDelegate(delegate)
def pathFromIndex(self, index):
return index.data(QtCore.Qt.UserRole)
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
d = {
"George": ["Washington", "Bush"],
"Languages": ["Python", "C++"]
}
model = create_model(d)
w = QtWidgets.QLineEdit()
completer = Completer(w)
completer.setModel(model)
w.setCompleter(completer)
w.show()
sys.exit(app.exec_())