[英]Type values in lineedit and then add it to a comboBox by clicking a button? PyQt4
我想通过单击按钮(一次一个值)将lineedit中键入的多个值添加到组合框。 我的示例代码如下:
import os, sys
import PyQt4
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class Example(QWidget):
def __init__(self, parent = None):
super().__init__()
self.grid = QGridLayout()
self.setLayout(self.grid)
btn = QPushButton()
le = QLineEdit()
combo = QComboBox()
self.grid.addWidget(btn, 0, 0)
self.grid.addWidget(le, 0 , 1)
self.grid.addWidget(combo, 0, 2)
self.show()
def main():
app = QApplication(sys.argv)
main = Example()
main.show()
sys.exit(app.exec_())
main()
如果有人知道该怎么做,请告诉我。 感谢!
解决方案很简单,您应该分析的第一件事是在哪个事件发生之前执行操作,在这种情况下,当发出喀哒声时,要连接一个插槽并在其中管理逻辑。 要获取文本,请使用QLineEdit
的text()
方法,然后使用addItem()
方法将其添加到QComboBox
。我添加了一个小的逻辑来验证并且不能添加非空文本,也不要重复这些项目
class Example(QWidget):
def __init__(self, parent = None):
super().__init__()
self.grid = QGridLayout()
self.setLayout(self.grid)
self.btn = QPushButton()
self.le = QLineEdit()
self.combo = QComboBox()
self.grid.addWidget(self.btn, 0, 0)
self.grid.addWidget(self.le, 0 , 1)
self.grid.addWidget(self.combo, 0, 2)
self.btn.clicked.connect(self.onClicked)
def onClicked(self):
text = self.le.text()
# the text is not empty
if text != "":
# get items of combobox
items = [self.combo.itemText(i) for i in range(self.combo.count())]
# Add if there is no such item
if text not in items:
self.combo.addItem(text)
只能在所创建方法的范围内访问变量,因此不适合仅使窗口小部件成为变量,而使类的属性适用,因为在类的任何方法中都可以访问它们。 为此,我们只能放自我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.