pyside6 QLineEdit内嵌入combobox 且combobox获得焦点时QLineEdit获得焦点,combobox失去焦点,QLineEdit失去焦点
时间: 2025-06-23 19:26:54 浏览: 18
在PySide6中,要在`QLineEdit`内部嵌入`QComboBox`并实现当`QComboBox`获取焦点时`QLineEdit`失去焦点,以及反之的情况,你可以这样做:
首先,你需要创建一个自定义的`QWidget`作为容器,并将`QLineEdit`和`QComboBox`添加到这个容器里。然后,利用`QObject.connect()`函数连接它们的信号和槽。
```python
from PySide6.QtWidgets import QWidget, QVBoxLayout, QLineEdit, QComboBox, QApplication, QLabel
from PySide6.QtGui import QAction
from PySide6.QtCore import Qt
class CustomWidget(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
layout = QVBoxLayout()
self.setLayout(layout)
self.line_edit = QLineEdit("Default text")
self.combo_box = QComboBox()
# 添加一些选项到组合框
for i in range(5):
self.combo_box.addItem(f"Option {i}")
# 创建一个信号槽机制,当组合框聚焦时,隐藏LineEdit
self.combo_box.currentIndexChanged.connect(self.handle_focus_change)
# 当LineEdit失去焦点时,显示组合框
self.line_edit.textChanged.connect(self.handle_text_change)
layout.addWidget(self.line_edit)
layout.addWidget(QLabel("Focus on ComboBox to activate:", self))
layout.addWidget(self.combo_box)
def handle_focus_change(self, index):
if self.combo_box.hasFocus():
self.line_edit.setDisabled(True)
self.combo_box.showPopup() # 显示组合框菜单
else:
self.line_edit.setEnabled(True)
def handle_text_change(self):
self.line_edit.clearFocus() # 当文本改变时,让焦点转移到组合框上
if __name__ == "__main__":
app = QApplication([])
widget = CustomWidget()
widget.show()
app.exec_()
```
在这个例子中,当你点击`QComboBox`或者按下键盘时,组合框会获得焦点,此时`QLineEdit`会被禁用,并显示组合框的列表。当用户从组合框选择一个项或者再次点击`QLineEdit`时,组合框会消失,焦点回到`QLineEdit`上。
阅读全文
相关推荐
















