问题很简单,解决过程却伤脑筋
一般添加控件的方式
layout = QVBoxLayout()
label = QLabel()
layout.addwidget(label)
但非布局的父控件无法这样添加子控件,找了半天!记录一下解决方案
下面说明一下非布局与布局的控件添加
布局控件添加:
from PyQt5.QtWidgets import QWidget, QApplication, QPushButton, QLabel
from PyQt5.Qt import QVBoxLayout
import sys
class Example(QWidget):
def __init__(self):
super().__init__()
self.resize(600, 400)
self.setWindowTitle('动态添加控件')
self.button_add = QPushButton("添加", self)
self.button_add.setGeometry(100, 150, 100, 50)
self.button_add.clicked.connect(self.add_label)
def add_label(self):
layout = QVBoxLayout(self)
label = QLabel("控件1", self)
label.setGeometry(200,200, 50,30)
layout.addWidget(label)
if __name__ == '__main__':
window = QApplication(sys.argv)
TheWin = Example()
TheWin.show()
sys.exit(window.exec_())
非布局控件添加:
from PyQt5.QtWidgets import QWidget, QApplication, QPushButton, QLabel
from PyQt5.Qt import QVBoxLayout
import sys
class Example(QWidget):
def __init__(self):
super().__init__()
self.resize(600, 400)
self.setWindowTitle('动态添加控件')
self.button_add = QPushButton("添加", self)
self.button_add.setGeometry(100, 150, 100, 50)
self.button_add.clicked.connect(self.add_label)
def add_label(self):
label = QLabel("控件1", self)
label.setGeometry(200,200, 50,30)
label.show()
if __name__ == '__main__':
window = QApplication(sys.argv)
TheWin = Example()
TheWin.show()
sys.exit(window.exec_())