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

yipeiwu_com5年前Python基础

本文研究的主要是PyQt5主窗口动态加载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)          #在状态栏显示文件地址 
 
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主窗口动态加载Widget实例代码的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

相关文章

python实现播放音频和录音功能示例代码

python实现播放音频和录音功能示例代码

音频预处理 这一讲主要介绍些音频基本处理方式,为接下来的语音识别打基础。 三种播放音频的方式 使用 python 播放音频有以下几种方式: os.system() os.sys...

Python列表(List)知识点总结

序列是Python中最基本的数据结构。序列中的每个元素都分配一个数字 - 它的位置,或索引,第一个索引是0,第二个索引是1,依此类推。 Python有6个序列的内置类型,但最常见的是列...

简单上手Python中装饰器的使用

Python的装饰器可以实现在代码运行期间修改函数的上下文, 即可以定义函数在执行之前进行何种操作和函数执行后进行何种操作, 而函数本身并没有任何的改变。 这个看起来很复杂, 实际上应用...

使用Python编写一个模仿CPU工作的程序

今天早上早些时候,在我的Planet Python源中,我读到了一篇有趣的文章"开发CARDIAC:纸板计算机(Developing upwards: CARDIAC: The Card...

python使用urllib2实现发送带cookie的请求

本文实例讲述了python使用urllib2实现发送带cookie的请求。分享给大家供大家参考。具体实现方法如下: import urllib2 opener = urllib2.b...