pyqt5中completer点击选择改为双击选择,代码实现
时间: 2023-07-16 19:11:39 浏览: 45
在PyQt5中,我们可以通过`QCompleter`类实现自动完成功能。默认情况下,`QCompleter`使用单击选择项。如果要将其更改为双击选择,请使用以下代码:
```python
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import QApplication, QCompleter, QLineEdit
class DoubleClickCompleter(QCompleter):
def eventFilter(self, obj, event):
if event.type() == QEvent.KeyPress and \
obj == self.edit() and \
event.key() in (Qt.Key_Return, Qt.Key_Enter):
index = self.currentIndex()
if index.isValid():
self.activated.emit(index)
return True
return super().eventFilter(obj, event)
# Example usage:
app = QApplication([])
line_edit = QLineEdit()
completer = DoubleClickCompleter(["apple", "banana", "cherry"])
line_edit.setCompleter(completer)
line_edit.show()
app.exec_()
```
在上面的代码中,我们创建了一个名为`DoubleClickCompleter`的子类,并覆盖了`eventFilter`方法。我们在这个方法中处理`KeyPress`事件,并在用户按下`Return`或`Enter`键时触发自动完成。这个方法会检查当前选中的索引是否有效,如果是,则发出`activated`信号以触发自动完成。
然后,我们创建一个`QLineEdit`对象和一个`QCompleter`对象,并将它们关联起来。最后,我们将`DoubleClickCompleter`对象设置为`QLineEdit`的自动完成器。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)