by

How to dynamically add a button to a GUI mask in python using PyQt4

This code shows how to add some dynamic GUI controls (in this case QPushButton) to a GUI main window.
In this example when user clicks on a button, the new buttons are created and put into the main window.
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
src="https://www.snip2code.com/Embed/12155/How-to-dynamically-add-a-button-to-a-GUI?startLine=0"></iframe>
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
#!/usr/bin/python import sys from PyQt4 import QtGui import os class Test(QtGui.QMainWindow): def __init__(self): super(Test, self).__init__() self.initUI() def initUI(self): YDrive = QtGui.QAction("Y", self) YDrive.triggered.connect(self.setYDir) self.toolbar = self.addToolBar('Exit') self.toolbar.addAction(YDrive) self.setGeometry(300, 300, 250, 150) self.setWindowTitle('Message box') self.show() def buttonClicked(self): print "clicked" def setYDir(self): myWorkDrive = "/tmp" shows = os.listdir(myWorkDrive) i = 0 for elements in shows: btn1 = QtGui.QPushButton(elements, self) btn1.move(30, 50 + i) i += 30 btn1.clicked.connect(self.buttonClicked) btn1.show() self.resize(self.width(), 50 + i) if __name__ == '__main__': app = QtGui.QApplication([]) t = Test() t.show() app.exec_()
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus