114.md 1.5 KB
Newer Older
W
wizardforcel 已提交
1
# pyqt 自动补全
W
init  
wizardforcel 已提交
2 3 4

> 原文: [https://pythonbasics.org/pyqt-auto-complete/](https://pythonbasics.org/pyqt-auto-complete/)

W
wizardforcel 已提交
5
PyQt 支持自动补全。 如果输入文本框(`QLineEdit`),它可以提出建议。 从列表中推荐这些建议。
W
init  
wizardforcel 已提交
6

W
wizardforcel 已提交
7
本示例将自动补全功能添加到`QLineEdit`文本框中。
W
init  
wizardforcel 已提交
8 9 10

![auto complete QLineEdit](img/d1daeade8423826325f8b569bf16acc5.jpg)

W
wizardforcel 已提交
11
图片:在 pyqt 窗口中显示的标签。
W
init  
wizardforcel 已提交
12

W
wizardforcel 已提交
13
## 自动补全
W
init  
wizardforcel 已提交
14

W
wizardforcel 已提交
15
### `QLineEdit`自动补全示例
W
init  
wizardforcel 已提交
16 17 18 19 20 21 22

首先创建选项(名称)列表,然后创建`completer = QCompleter(names)`

使用行`self.lineedit = QLineEdit()`创建行编辑。 否则,行编辑将正常进行。

这些建议已添加到`self.lineedit.setCompleter(completer)`中。

W
wizardforcel 已提交
23
如果忘记了最后一行,则`QCompleter``QLineEdit`未连接,这意味着没有**自动补全**
W
init  
wizardforcel 已提交
24

W
wizardforcel 已提交
25
```py
W
init  
wizardforcel 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
from PyQt5.QtWidgets import *
import sys

class Window(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        layout = QGridLayout()
        self.setLayout(layout)

        # auto complete options                                                 
        names = ["Apple", "Alps", "Berry", "Cherry" ]
        completer = QCompleter(names)

        # create line edit and add auto complete                                
        self.lineedit = QLineEdit()
        self.lineedit.setCompleter(completer)
        layout.addWidget(self.lineedit, 0, 0)

app = QApplication(sys.argv)
screen = Window()
screen.show()
sys.exit(app.exec_())

```