Search code examples
pysideqlineeditqpushbutton

Erase all the inputs with a button


I use for loop to create several QLineEdits, and going to create a button which can erase everything written in all the QLineEdits. It means if I type something in every QLine, and click the button can clear all the lines. My question is how to write the button function like this.

Here is my simplified version code.

from PySide import QtGui
from PySide import QtCore
from PySide.QtCore import Signal as pyqtSignal
from PySide.QtCore import Slot as pyqtSlot
import sys

class example(QtGui.QWidget):
    def __init__(self, parent= None):
        super(example, self).__init__()

        grid = QtGui.QGridLayout()
        grid.setSpacing(10)

        self.widget = QtGui.QWidget()

        # set the widget as parent of its own layout
        self.layout = QtGui.QGridLayout(self.widget)

        for i in range(5):
            line = QtGui.QLineEdit()
            self.layout.addWidget(line,i,0)

        btn = QtGui.QPushButton("Clear All")
        self.layout.addWidget(btn,i+1,0)
        btn.clicked.connect(self.all_clear)

        self.scroll = QtGui.QScrollArea()
        # need this so that scrollarea handles resizing
        self.scroll.setWidgetResizable(True)
        # these two lines may not be needed now
        self.scroll.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
        self.scroll.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)

        self.scroll.setWidget(self.widget)

        grid.addWidget(self.scroll, 3, 0)
        self.setLayout(grid)

    def all_clear(self):
        pass





if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    dialog = example()
    dialog.show()
    sys.exit(app.exec_())

I have no idea how to write the button function. If anyone can help, thanks in advance.


Solution

  • As @Pratham stated, store each QLineEdit in a list:

    self.edits = []
    for i in range(5):
        line = QtGui.QLineEdit()
        self.layout.addWidget(line,i,0)
        self.edits.append(line)
    

    and have all_clear() call clear() on each of them:

    def all_clear(self):
        for edit in self.edits:
            edit.clear()
    

    The clear() method is also a slot, so you could also do it without defining a new method by connecting the clicked() signal to it:

    btn = QtGui.QPushButton("Clear All")
    self.layout.addWidget(btn,i+1,0)
    
    for i in range(5):
        line = QtGui.QLineEdit()
        self.layout.addWidget(line,i,0)
        btn.clicked.connect(line.clear)