I'm trying to delete a button in my window/UI. Am using Python and PyQt5 to do this task, can someone notify me to delete a button if exists? Or any function to check? this is my sample code:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
class App(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.setWindowTitle("my window")
self.setGeometry(100, 100, 320, 300)
# creating a button
button1 = QPushButton('Button-1', self)
button1.move(100, 70)
#I want a function to check if other button named "button2" exists,then delete it, like below
if button2.exists:
button2.delete()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())
Usually, you keep reference to widgets by assigning them as class attributes. Then you can check for their existence and delete them:
def initUI(self):
self.setWindowTitle("my window")
self.setGeometry(100, 100, 320, 300)
self.button1 = QPushButton('Button-1', self)
self.button1.move(100, 70)
self.button2 = QPushButton('Button-2', self)
self.button2.move(100, 90)
if hasattr(self, 'button2'):
self.button2.deleteLater()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.