当前位置: 首页 PyQt5基类QObject属性和方法 PyQt5对象之间的父子关系继承与查找
add-vip

PyQt5对象之间的父子关系继承与查找

一、学习指导

我们在实例化对象的时候往往不止一个,而这些对象都会有一定的继承关系,PyQt5也不例外,而且在这点PyQt5做的比其他GUI框架更加优秀。PyQt5对象之间的父子关系继承与查找设置起来很简单。我们先看一下下面的代码:

二、代码演示

from PyQt5.Qt import *
import sys
 
class Window(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("父子关系")
        self.resize(600,500)
        self.func_list()
 
    def func_list(self):
        self.func()

    def func(self):
        obj1 =QObject()
        print('obj1',obj1)
        obj2 =QObject()
        print('obj2', obj2)
        obj3 =QObject()
        print('obj3', obj3)
        obj2.setParent(obj1)
        obj3.setParent(obj2)
        print(obj2.parent())
        print(obj2.children())
 
        print(obj1.findChild(QObject))
        print(obj1.findChildren(QObject))
 
if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = Window()
 
    window.show()
    sys.exit(app.exec_())


这里给大家注释一下


        obj1.setParent(obj2)  # 把obj2设置为obj1的父对象
        obj3.setParent(obj1)  # 把obj1设置为obj3的父对象
        print(obj1.parent())  # 获取父对象
        print(obj2.children()) # 获取obj2的子对象
        print(obj2.findChild(QObject))   # 获取直接的子对象
        print(obj2.findChildren(QObject))   # 获取所有的子对象


相关文章