简体   繁体   English

在lineedit中键入值,然后通过单击按钮将其添加到comboBox? PyQt4中

[英]Type values in lineedit and then add it to a comboBox by clicking a button? PyQt4

I want to add multiple value typed in lineedit to a combobox by clicking a button (one value at one time). 我想通过单击按钮(一次一个值)将lineedit中键入的多个值添加到组合框。 My sample codes are as below: 我的示例代码如下:

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()

If anyone knows how to do it, pls let me know. 如果有人知道该怎么做,请告诉我。 Appreciated!! 感谢!

The solution is simple, the first thing you should analyze is before which event the action is done, in your case when the clicked signal is emitted, so that a slot is connected and in it we manage the logic. 解决方案很简单,您应该分析的第一件事是在哪个事件发生之前执行操作,在这种情况下,当发出喀哒声时,要连接一个插槽并在其中管理逻辑。 To get the text, use the text() method of QLineEdit , and add it to the QComboBox with the addItem() method, I added a small logic to validate and can not add non-empty text and also not to repeat the items 要获取文本,请使用QLineEdittext()方法,然后使用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)

The variables can only be accessed in the scope of the method that is created so it is not appropriate to make the widget only variables, but attributes of the class since they are accessible in any method of the class. 只能在所创建方法的范围内访问变量,因此不适合仅使窗口小部件成为变量,而使类的属性适用,因为在类的任何方法中都可以访问它们。 For this we must only put self. 为此,我们只能放自我。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM