PyQt: Add qpushbutton dynamically
Asked Answered
A

2

6

I am trying to figure out how to create QPushButton by pressing another QPushbutton so that I can ultimately create buttons dynamically. It seems like the initial method for creating buttons doesn't work in a function.

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize   



class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)


    self.setMinimumSize(QSize(300, 200))    

    pybutton = QPushButton('Create a button', self)
    pybutton.clicked.connect(self.clickMethod)
    pybutton.resize(100,100)
    pybutton.move(100, 100)        

def clickMethod(self):
    print('Clicked')
    newBtn = QPushButton('New Button', self)
    newBtn.move(0, 0)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWin = MainWindow()
    mainWin.show()
    sys.exit( app.exec_() )
Amice answered 20/4, 2018 at 19:44 Comment(0)
F
9

When a window is displayed, it invokes the show() method of its children, so the children are visible. If you want the buttons that you add afterwards to be visible you must call the show() method of the button

def clickMethod(self):
    print('Clicked')
    newBtn = QPushButton('New Button', self)
    newBtn.move(0, 0)
    newBtn.show()

enter image description here

Flatling answered 20/4, 2018 at 20:3 Comment(0)
D
0

you just need show() , but better if you make it in the list to controll it later , like this :

import sys
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget
from PyQt5.QtWidgets import QPushButton
from PyQt5.QtCore import QSize   



class MainWindow(QMainWindow):
    def __init__(self):
     QMainWindow.__init__(self)
     self.i=0
     self.y=0
     self.btn=[]
     self.setMinimumSize(QSize(300, 200))    
 
     pybutton = QPushButton('Create a button', self)
     pybutton.clicked.connect(self.clickMethod)
     pybutton.resize(100,100)
     pybutton.move(100, 100)        

    def clickMethod(self):
     print('Clicked')
     self.btn.append( QPushButton('New Button', self))
     
     self.btn[-1].move(self.i, self.y)
     self.i=self.i+50
     self.y=self.y+50
     self.btn[-1].show()


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    mainWin = MainWindow()
    mainWin.show()
    sys.exit( app.exec_() )
Dorcus answered 21/3, 2023 at 14:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.