父子关系扩充
API
childAt(x,y)获取在指定坐标的控件
parentWidget()获取指定控件的父控件
childrenRect()获取所有子控件组成的边界矩形区域的范围
from PyQt5.Qt import *
import sys
app=QApplication(sys.argv)
window=QWidget()
window.setWindowTitle("父子关系学习")
window.resize(500,500)
label1 = QLabel(window)
label1.setText('标签1')
label2 = QLabel(window)
label2.setText('标签2')
label2.move(50,50)
label3 = QLabel(window)
label3.setText('标签3')
label3.move(100,100)
print(window.childAt(55, 55))
print(label2.parentWidget())
print(window.childrenRect())
window.show()
sys.exit(app.exec_())
运行结果
<PyQt5.QtWidgets.QLabel object at 0x000001FBF81CCAF0>
<PyQt5.QtWidgets.QWidget object at 0x000001FBF5C2F430>
PyQt5.QtCore.QRect(0, 0, 200, 130)
案例
from PyQt5.Qt import *
import sys
# class MyLabel(QLabel):
# def mousePressEvent(self, QMouseEvent):#鼠标按下时触发
# self.setStyleSheet('background-color :red;') #设置标签为背景为红色
class Window(QWidget):
def mousePressEvent(self, evt):
local_x = evt.x();
local_y = evt.y();
sub_widget = self.childAt(local_x,local_y)#获取当前点击位置的控件
if sub_widget is not None:#如果当前点击位置有控件
sub_widget.setStyleSheet('background-color :red;')
print('被点击了',local_x,local_y)
app=QApplication(sys.argv)
window=Window()
window.setWindowTitle("")
window.resize(500,500)
for i in range(1,11):
label = QLabel(window)
label.setText('标签' + str(i))
label.move(40*i,40*i)
window.show()
sys.exit(app.exec_())