Tony Stark
Tony Stark

Reputation: 145

how i will remove widget with click button on another class (PyQt)

there is an error, how can i provide this? i want to remove widgets with remove button. is this okay self.removeButton.clicked.connect(self.removing.remove_widget) ? i tried to connect another class with a pushbutton.

from PyQt4 import QtGui, QtCore
import sys

class Main(QtGui.QMainWindow):
    def __init__(self, parent = None):
        super(Main, self).__init__(parent)

        # main button
        self.addButton = QtGui.QPushButton('button to add other widgets')
        self.addButton.clicked.connect(self.addWidget)

        self.removing=Test()
        self.removeButton=QtGui.QPushButton("remove widget")
        self.removeButton.clicked.connect(self.removing.remove_widget)

        # scroll area widget contents - layout
        self.scrollLayout = QtGui.QFormLayout()

        # scroll area widget contents
        self.scrollWidget = QtGui.QWidget()
        self.scrollWidget.setLayout(self.scrollLayout)

        # scroll area
        self.scrollArea = QtGui.QScrollArea()
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setWidget(self.scrollWidget)

        # main layout
        self.mainLayout = QtGui.QVBoxLayout()

        # add all main to the main vLayout
        self.mainLayout.addWidget(self.addButton)
        self.mainLayout.addWidget(self.removeButton)
        self.mainLayout.addWidget(self.scrollArea)

        # central widget
        self.centralWidget = QtGui.QWidget()
        self.centralWidget.setLayout(self.mainLayout)

        # set central widget
        self.setCentralWidget(self.centralWidget)

    def addWidget(self):
        self.scrollLayout.addRow(Test())


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

      self.lineEdit = QtGui.QLineEdit('I am in Test widget')

      layout = QtGui.QHBoxLayout()
      layout.addWidget(self.lineEdit)
      self.setLayout(layout)

  def remove_widget(self):
      self.lineEdit.deleteLater()




app = QtGui.QApplication(sys.argv)
myWidget = Main()
myWidget.show()
app.exec_()

Upvotes: 0

Views: 2919

Answers (1)

Cyrbuzz
Cyrbuzz

Reputation: 119

You created a new class Test, and connected the new Test then the button del it.

You could try this.

self.kod = []
self.removeButton=QtWidgets.QPushButton("remove widget")
self.removeButton.clicked.connect(self.remove_widget)
...

def addWidget(self):
    temp = Test()
    self.kod.append(temp)
    self.scrollLayout.addRow(temp)

def remove_widget(self):
    self.kod.pop().deleteLater()

Upvotes: 1

Related Questions