Pyqt 动态的添加控件
1 # -*- coding: utf-8 -*- 2 from PyQt4.QtCore import * 3 from PyQt4.QtGui import * 4 import sys 5 ''' 6 Pyqt 动态的添加控件 7 ''' 8 9 class DynAddObject(QDialog): 10 def __init__(self, parent=None): 11 super(DynAddObject, self).__init__(parent) 12 addButton = QPushButton(u"添加控件") 13 self.layout = QGridLayout() 14 self.layout.addWidget(addButton, 1, 0) 15 self.setLayout(self.layout) 16 self.connect(addButton, SIGNAL("clicked()"), self.add) 17 18 def add(self): 19 btncont= self.layout.count() 20 widget = QPushButton(str(btncont), self) 21 self.layout.addWidget(widget) 22 23 if __name__ == "__main__": 24 app = QApplication(sys.argv) 25 form = DynAddObject() 26 form.show() 27 app.exec_()
或者通过赋值self.object={}字典,将字典dict的每一个值赋值为QPushButton
1 class DynAddObject(QDialog): 2 def __init__(self, parent=None): 3 super(DynAddObject, self).__init__(parent) 4 addButton = QPushButton(u"添加控件") 5 self.layout = QGridLayout() 6 self.layout.addWidget(addButton, 1, 0) 7 self.setLayout(self.layout) 8 self.add() 9 10 def add(self): 11 self.button={} 12 print(type(self.button)) 13 for i in range(1, 8): 14 self.button[i]=QPushButton(str(i)) 15 self.layout.addWidget(self.button[i]) 16 17 18 if __name__ == "__main__": 19 app = QApplication(sys.argv) 20 form = DynAddObject() 21 form.show() 22 app.exec_()
效果:
相关链接: python动态生成变量