本文研究的主要是PyQt5主窗口動態(tài)加載Widget的代碼示例,具體如下。
我們通過Qt Designer設計兩個窗口,命名為主窗口(MainForm)和子窗口(ChildrenForm)。我們在主窗口的空白中央添加一個柵格布局并命名為MaingridLayout,等會需要將ChildrenForm放進去。

編寫代碼
from PyQt5 import QtWidgets from MainForm import Ui_MainForm from Children import Ui_Form from PyQt5.QtWidgets import QFileDialog class MainForm(QtWidgets.QMainWindow,Ui_MainForm): def __init__(self): super(MainForm,self).__init__() self.setupUi(self) self.child=ChildrenForm() #self.child = children()生成子窗口實例self.child self.fileOpen.triggered.connect(self.openMsg) #菜單的點擊事件是triggered self.fileClose.triggered.connect(self.close) self.actionTst.triggered.connect(self.childShow) #點擊actionTst,子窗口就會顯示在主窗口的MaingridLayout中 def childShow(self): self.MaingridLayout.addWidget(self.child) #添加子窗口 self.child.show() def openMsg(self): file,ok=QFileDialog.getOpenFileName(self,"打開","C:/","All Files (*);;Text Files (*.txt)") self.statusbar.showMessage(file) #在狀態(tài)欄顯示文件地址 class ChildrenForm(QtWidgets.QWidget,Ui_Form): def __init__(self): super(ChildrenForm,self).__init__() self.setupUi(self) if __name__=="__main__": import sys app=QtWidgets.QApplication(sys.argv) myshow=MainForm() myshow.show() sys.exit(app.exec_())
以上就是本文關于PyQt5主窗口動態(tài)加載Widget實例代碼的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
新聞熱點
疑難解答