对象的父子关系API

parent() 获取父对象
setParent() 设定父对象

chirldren() 获取子对象(包含多个)
findChild() 查找子对象,若有多个子对象符合查找条件,找到第一个符合条件的子对象就返回,即即使有多个子对象符合,但只返回一个子对象
findChildren() 查找子对象,若有多个子对象符合查找条件,则返回所有符合条件的子对象,查找范围为直接子对象和间接子对象

使用示例

# -*- coding: utf-8 -*-
from PyQt5.Qt import *


obj0 = QObject()
obj1 = QObject()
obj2 = QObject()
obj3 = QObject()
obj4 = QObject()
obj5 = QObject()
print("obj0:" , obj0)
print("obj1:" , obj1)
print("obj2:" , obj2)
print("obj3:" , obj3)
print("obj4:" , obj4)
print("obj5:" , obj5)

obj1.setParent(obj0)
obj2.setParent(obj0)
obj3.setParent(obj1)
obj4.setParent(obj2)
obj5.setParent(obj2)

print(obj4.parent()) # 返回obj4的父对象obj2,不返回obj0
print(obj0.children()) # 返回obj0的子对象obj1和obj2,不返回它们各自的子对象

obj1.setParent(obj2)
print(obj1.parent()) #返回obj1新的父对象obj2,obj0已不是父对象
obj1.setParent(obj0) #将obj1的父对象重新设定为obj0


print(obj0.findChild(QObject)) #返回obj0的QObject类型的子对象,只返回查到的一个直接子对象
print(obj0.findChild(QObject, '5')) #返回obj0的QObject类型且objectName是5的子对象,该子对象也可以是obj0的间接子对象
print(obj0.findChild(QObject, '5',Qt.FindDirectChildrenOnly)) #返回obj0的QObject类型且objectName是5的子对象,该子对象只能是obj0的直接子对象
print(obj0.findChildren(QObject)) #返回obj0的QObject类型的子对象,返回所有查到的直接子对象

猜你喜欢

转载自www.cnblogs.com/shiliye/p/12132191.html
今日推荐