from PyQt5.QtWidgets import QApplication, QLineEdit, QCompleter app = QApplication([]) line_edit = QLineEdit() completer = QCompleter(["apple", "banana", "cherry"], line_edit) completer.setCompletionMode(QCompleter.PopupCompletion) # 设置双击选择 line_edit.setCompleter(completer) line_edit.show() app.exec_() 实现多层级选择
时间: 2023-07-14 11:13:21 浏览: 78
要实现多层级选择,可以使用QStandardItemModel类作为QCompleter的模型,并添加多个层级的QStandardItem对象。以下是一个示例代码:
```
from PyQt5.QtWidgets import QApplication, QLineEdit, QCompleter, QTreeView
from PyQt5.QtGui import QStandardItem, QStandardItemModel
app = QApplication([])
# 创建模型
model = QStandardItemModel()
root_item = model.invisibleRootItem()
# 添加第一级选项
for i in range(3):
item = QStandardItem("Item {}".format(i))
root_item.appendRow(item)
# 添加第二级选项
for j in range(2):
child_item = QStandardItem("Child Item {}".format(j))
# 添加第三级选项
for k in range(4):
grandchild_item = QStandardItem("Grandchild Item {}".format(k))
child_item.appendRow(grandchild_item)
item.appendRow(child_item)
# 创建QCompleter和QLineEdit
line_edit = QLineEdit()
completer = QCompleter(model, line_edit)
completer.setCompletionMode(QCompleter.PopupCompletion)
# 设置QTreeView以显示多层级选项
completer.view().setModel(model)
completer.view().setRootIsDecorated(False)
completer.view().setItemsExpandable(False)
completer.view().setAllColumnsShowFocus(True)
# 将completer设置为line_edit的补全器
line_edit.setCompleter(completer)
line_edit.show()
app.exec_()
```
在这个例子中,我们创建了一个三层的选项列表。第一级选项有三个,每个有两个子选项,每个子选项有四个孙选项。我们使用QStandardItemModel来创建这个列表,并将它作为QCompleter的模型。我们还使用QTreeView来显示多层级选项。最后,我们将QCompleter设置为QLineEdit的补全器。
阅读全文