pyside6 QLineEdit()获得焦点时,自动打开QComboBox()的下拉列表
时间: 2025-06-21 09:29:41 浏览: 11
### 实现Pyside6 QLineEdit 获得焦点时自动触发 QComboBox 展开
为了实现在 `QLineEdit` 控件获得焦点时,使 `QComboBox` 自动展开其下拉列表的效果,可以利用信号槽机制来连接这两个控件的行为。具体来说,可以通过监听 `QLineEdit.focusInEvent()` 事件,在该事件发生时调用 `QComboBox.showPopup()` 方法。
下面是一个完整的代码示例:
```python
from PySide6.QtWidgets import QApplication, QWidget, QVBoxLayout, QLineEdit, QComboBox
class MyWidget(QWidget):
def __init__(self):
super().__init__()
layout = QVBoxLayout()
self.setLayout(layout)
self.lineEdit = QLineEdit(self)
self.comboBox = QComboBox(self)
self.comboBox.addItems(["Option 1", "Option 2", "Option 3"])
# 将lineEdit的focusInEvent与comboBox显示弹出窗口的方法关联起来
self.lineEdit.installEventFilter(self)
layout.addWidget(self.lineEdit)
layout.addWidget(self.comboBox)
def eventFilter(self, obj, event):
if obj == self.lineEdit and event.type() == event.FocusIn:
self.comboBox.showPopup() # 当line edit获取到焦点时展示组合框的内容[^1]
return True
return False
if __name__ == "__main__":
app = QApplication([])
widget = MyWidget()
widget.resize(200, 150)
widget.show()
app.exec_()
```
这段程序定义了一个自定义的小部件类 `MyWidget` ,其中包含了两个子组件——一个 `QLineEdit` 和一个 `QComboBox` 。通过重写 `eventFilter` 函数并安装过滤器给 `QLineEdit` 来捕获它的聚焦进入事件;一旦检测到此事件,则立即执行 `showPopup()` 操作让 `QComboBox` 显示可用的选择项[^2]。
阅读全文
相关推荐


















