您的当前位置:首页PyQt5主窗口动态加载Widget实例代码

PyQt5主窗口动态加载Widget实例代码

来源:小侦探旅游网
PyQt5主窗⼝动态加载Widget实例代码

PyQt是⼀个创建GUI应⽤程序的⼯具包。它是Python编程语⾔和Qt库的成功融合。Qt库是⽬前最强⼤的库之⼀。PyQt是由Phil Thompson 开发。

我们通过Qt Designer设计两个窗⼝,命名为主窗⼝(MainForm)和⼦窗⼝(ChildrenForm)。我们在主窗⼝的空⽩中央添加⼀个栅格布局并命名为MaingridLayout,等会需要将ChildrenForm放进去。编写代码

1 from PyQt5 import QtWidgets

2 from MainForm import Ui_MainForm 3 from Children import Ui_Form 4

5 from PyQt5.QtWidgets import QFileDialog 6

7 class MainForm(QtWidgets.QMainWindow,Ui_MainForm): 8 def __init__(self):

9 super(MainForm,self).__init__() 10 self.setupUi(self) 11

12 self.child=ChildrenForm() #self.child = children()⽣成⼦窗⼝实例self.child 13 self.fileOpen.triggered.connect(self.openMsg) #菜单的点击事件是triggered 14 self.fileClose.triggered.connect(self.close)

15 self.actionTst.triggered.connect(self.childShow) #点击actionTst,⼦窗⼝就会显⽰在主窗⼝的MaingridLayout中 16

17 def childShow(self):

18 self.MaingridLayout.addWidget(self.child) #添加⼦窗⼝ 19 self.child.show() 20 def openMsg(self):

21 file,ok=QFileDialog.getOpenFileName(self,\"打开\",\"C:/\",\"All Files (*);;Text Files (*.txt)\") 22 self.statusbar.showMessage(file) #在状态栏显⽰⽂件地址 23

24 class ChildrenForm(QtWidgets.QWidget,Ui_Form): 25 def __init__(self):

26 super(ChildrenForm,self).__init__() 27 self.setupUi(self) 28

29 if __name__==\"__main__\": 30 import sys 31

32 app=QtWidgets.QApplication(sys.argv) 33 myshow=MainForm() 34 myshow.show()

35 sys.exit(app.exec_())

因篇幅问题不能全部显示,请点此查看更多更全内容