Pyqt 动态的添加控件

时间:2022-02-24 21:08:49

Pyqt 动态的添加控件

 # -*- coding: utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import sys
'''
Pyqt 动态的添加控件
''' class DynAddObject(QDialog):
def __init__(self, parent=None):
super(DynAddObject, self).__init__(parent)
addButton = QPushButton(u"添加控件")
self.layout = QGridLayout()
self.layout.addWidget(addButton, 1, 0)
self.setLayout(self.layout)
self.connect(addButton, SIGNAL("clicked()"), self.add) def add(self):
btncont= self.layout.count()
widget = QPushButton(str(btncont), self)
self.layout.addWidget(widget) if __name__ == "__main__":
app = QApplication(sys.argv)
form = DynAddObject()
form.show()
app.exec_()

Pyqt 动态的添加控件

Pyqt 动态的添加控件

或者通过赋值self.object={}字典,将字典dict的每一个值赋值为QPushButton

 class DynAddObject(QDialog):
def __init__(self, parent=None):
super(DynAddObject, self).__init__(parent)
addButton = QPushButton(u"添加控件")
self.layout = QGridLayout()
self.layout.addWidget(addButton, 1, 0)
self.setLayout(self.layout)
self.add() def add(self):
self.button={}
print(type(self.button))
for i in range(1, 8):
self.button[i]=QPushButton(str(i))
self.layout.addWidget(self.button[i]) if __name__ == "__main__":
app = QApplication(sys.argv)
form = DynAddObject()
form.show()
app.exec_()

效果:

Pyqt 动态的添加控件

相关链接:   python动态生成变量