How do you remove his objectName in PyQT5?



  • How can I remove his objectName? Now, the code is making a mistake because I'm in the technique to removeWidget, but how am I supposed to do that to remove Widget?

            self.senderText = self.sender().objectName()
            self.selectedTask.setText(self.sender().text())
            font = self.selectedTask.font()
            font.setPointSize(18)
            font.setBold(True)
            self.noteText.setPlainText('')
    
        self.deletetaskButton.clicked.connect(self.deleteTask)
        self.selectdateButton.clicked.connect(self.selectDate)
    
    def deleteTask(self):
        self.tasksList.removeWidget(self.senderText)
    



  • Use findChild to search his objectName. I'll just notice that the view is only sought from the immediate descendants of the parent. In real circumstances, it might be necessary to make a fresh search.

    In the example, there are several buttons with ObjectName "button1", button2 etc. Put your name in lineedit and press the "delete by name" button. If there's a descendant, it'll be removed (maybe you introduce "button1" to remove the button or "lineedit," then the entry line will be removed)

    import sys
    from PyQt5.QtWidgets import QApplication, QMainWindow, QGridLayout, QWidget, QPushButton, QLineEdit
    from PyQt5.QtCore import QSize, QObject
    

    class MainWindow(QMainWindow):
    def btnClicked(self):
    # поиск потомка self по его имени из lineedit
    resbutton = self.findChild(QObject, self.lineedit.text())
    if resbutton:
    resbutton.deleteLater()

    def __init__(self):
        QMainWindow.__init__(self)
        self.setMinimumSize(QSize(400, 400))
        central_widget = QWidget(self)
        self.setCentralWidget(central_widget)
        self.grid_layout = QGridLayout()
        central_widget.setLayout(self.grid_layout)
    
        for i in range(1,10):
            button = QPushButton(f"i'am button{i}")
            button.setObjectName(f"button{i}")
            self.grid_layout.addWidget(button, i, 0)
        self.lineedit = QLineEdit()
        self.lineedit.setObjectName("lineedit")
        self.grid_layout.addWidget(self.lineedit, 10, 0)
        self.button = QPushButton("delete by name")
        self.grid_layout.addWidget(self.button, 10, 1)
        self.button.clicked.connect(self.btnClicked)
    

    if name == "main":
    app = QApplication(sys.argv)
    mw = MainWindow()
    mw.show()
    sys.exit(app.exec())



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2