QMainWindow动态添加按钮,添加后需要调用show(),才可以显示出来。
self.start_file_aaa = QPushButton(self)
self.start_file_aaa.setGeometry(1210, 10, 100, 30)
self.start_file_aaa.setObjectName('start')
self.start_file_aaa.setText('加载11')
self.start_file_aaa.show()
只能动态添加工具栏按钮
#coding=utf-8
import sys
from PyQt5.QtWidgets import QMainWindow, QApplication, QMenuBar, QAction, qApp, QLabel
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QCoreApplication
class Example3(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def add(self):
print('asdfsdf')
self.toolbar.addAction('bbbbb', self.add)
def initUI(self):
exitAction = QAction(QIcon('d:/1.jpg'), 'asdf', self)
exitAction.setShortcut('Ctrl+Q')
exitAction.triggered.connect(qApp.quit)
self.toolbar = self.addToolBar('Exit123')
self.toolbar.addAction(exitAction)
self.toolbar.addAction( 'asdf',self.add)
self.setGeometry(300, 300, 450, 450)
self.setWindowTitle('QMainWindow的ToolBar')
self.show()
pass
def main3():
app = QApplication(sys.argv)
example = Example3()
sys.exit(app.exec_())
pass
if __name__ == '__main__':
main3()
工具/版本
(1)安装环境:Windows7 64bit
(2)使用版本Python3.6
(3)PYQT5
(4)eric6
使用布局,请参考这篇文章
删除控件:
self.buttom.deleteLater()
关闭控件:
self.button.close()或者self.button.hide()
重新显示控件:
如果是删除,需要重新创建控件然后self.button.show()
如果是关闭,或者隐藏,self.show()
此处需注意:
如果多次创建相同名称的控件,操作创建的控件会显示异常,需要删除再创建
# coding=utf-8
from PyQt5.QtWidgets import QWidget, QApplication, QPushButton
import sys
class Example(QWidget):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.resize(550, 300)
self.setWindowTitle('动态删除增加控件测试')
self.CreatUI()
def CreatUI(self):
self.lb1 = QPushButton("按键1", self)
self.lb1.setGeometry(100, 200, 100, 50)
self.lb2 = QPushButton("按键1", self)
self.lb2.setGeometry(280, 200, 100, 50)
self.bt1 = QPushButton('删除', self)
self.bt2 = QPushButton('新建', self)
self.bt1.move(100, 20)
self.bt2.move(280, 20)
self.bt1.clicked.connect(self.deleteWidget)
self.bt2.clicked.connect(self.addWidget)
def deleteWidget(self):
self.lb1.deleteLater()
self.lb2.deleteLater()
self.bt1.deleteLater()
def addWidget(self):
self.CreatUI()
self.showWidget()
def closeWidget(self):
# self.lb1.close()
# self.lb2.close()
# self.bt1.close()
# 或者使用hide
self.lb1.hide()
self.lb2.hide()
self.bt1.hide()
def showWidget(self):
self.lb1.show()
self.lb2.show()
self.bt1.show()
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
ex.show()
sys.exit(app.exec_())