Clicking A Button To Create A New Button Using Pyqt5 Python
I'm trying to create a window(UI) that have a button click action implemented using python and PyQt5. But, i want my button to create a new button when i clicked it. (i.e: clicking
Solution 1:
You need to replace button.clicked.connect (self.on_click)
with button1.clicked.connect (self.on_click)
.
and add button2.show ()
.
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
classApp(QWidget):
def__init__(self):
super().__init__()
self.initUI()
definitUI(self):
self.setWindowTitle("my window")
self.setGeometry(100, 100, 320, 300)
#creating a button to be clicked
button1 = QPushButton('Button-1', self)
button1.move(100, 70)
button1.clicked.connect(self.on_click) # button1 @pyqtSlot()defon_click(self):
print('Button-2 will be created')
button2 = QPushButton('Button-2', self)
button2.move(100, 200)
button2.show() # +++if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())
Or using layouts:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot
classApp(QWidget):
def__init__(self):
super().__init__()
self.initUI()
definitUI(self):
self.setWindowTitle("my window")
self.num = 2#creating a button to be clicked
button1 = QPushButton('Button-1', self)
# button1.move(100, 70)
button1.clicked.connect(self.on_click)
self.layout = QVBoxLayout(self)
self.layout.addWidget(button1)
@pyqtSlot()defon_click(self):
print('Button-{} will be created'.format(self.num))
button2 = QPushButton('Button-{}'.format(self.num), self)
button2.clicked.connect(lambda : print(button2.text()))
# button2.move(100, 200)
self.layout.addWidget(button2)
self.num += 1if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
ex.show()
sys.exit(app.exec_())
Post a Comment for "Clicking A Button To Create A New Button Using Pyqt5 Python"