python combobox 没选择一项,则向lineEdit添加被选择combobox项的文本,每次用'、'隔开
时间: 2023-06-13 19:07:27 浏览: 32
你可以通过以下代码实现:
```python
from PyQt5.QtWidgets import QApplication, QComboBox, QLineEdit, QWidget, QVBoxLayout
from PyQt5.QtCore import Qt
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
vbox = QVBoxLayout(self)
self.cb = QComboBox(self)
self.cb.addItems(['Apple', 'Banana', 'Cherry'])
self.cb.currentIndexChanged.connect(self.updateLineEdit)
self.le = QLineEdit(self)
vbox.addWidget(self.cb)
vbox.addWidget(self.le)
self.setLayout(vbox)
self.setGeometry(300, 300, 300, 150)
self.setWindowTitle('ComboBox')
self.show()
def updateLineEdit(self, index):
text = self.cb.currentText()
if text:
current_text = self.le.text()
if current_text:
self.le.setText(current_text + '、' + text)
else:
self.le.setText(text)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
```
这个例子中,我们创建了一个QComboBox和一个QLineEdit,并且将它们放在一个QVBoxLayout中。我们在QComboBox的currentIndexChanged信号上连接了一个槽函数updateLineEdit。在槽函数中,我们获取当前被选择的项的文本,并且将它添加到QLineEdit中。如果QLineEdit中已经有文本,我们用'、'来隔开新旧文本。