当前位置:   article > 正文

【pyqt5】自定义控件 实现能够保持长宽比地缩放子控件_pyqt5 resizeevent

pyqt5 resizeevent

需求

在窗口缩放过程中,实现控件按照一定的长宽比缩放

实现思路

1. 继承QFrame类, 重写resizeEvent方法

代码
from PyQt5 import QtCore, QtWidgets, QtGui
from PyQt5.QtWidgets import QFrame

class KeepRatioFrame(QFrame):
    def __init__(self, parent, flags=QtCore.Qt.WindowType.Widget) -> None:
        super().__init__(parent, flags)
        self.resize_init = False
        self.childWidget = None
        self.wh_ratio = 1

    def resizeEvent(self, event: QtGui.QResizeEvent) -> None:
        if not self.resize_init:
            self.resize_init = True
            # 获取子控件
            self.childWidget: QtWidgets.QLabel = self.findChild(QtWidgets.QLabel)
            # 计算ui初始宽长比
            self.wh_ratio = self.childWidget.width() / self.childWidget.height()
        # 获取当前frame的宽和长
        frame_w, frame_h = event.size().width(), event.size().height()
        # frame宽度不够 以此来计算child的高度
        if frame_w / frame_h <= self.wh_ratio:
            child_w, child_h = frame_w, round(frame_w / self.wh_ratio)
            child_x, child_y = 0, round(frame_h/2 - child_h/2)
        # frame高度不够 以此来计算child的宽度    
        else:
            child_w, child_h = round(frame_h * self.wh_ratio), frame_h
            child_x, child_y = round(frame_w/2 - child_w/2), 0
        # 更新子控件位置尺寸
        self.childWidget.setGeometry(child_x, child_y, child_w, child_h)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

2. 在qt designer里设计ui时使用frame提升为上面自定义的类
将要保持长宽比的控件(需要设定初始的长宽)放入该自定义的frame中(不要添加布局)
在这里插入图片描述

小节

  1. QResizeEvent事件的传入,可以通过event访问resieze前后的widget的size
    在这里插入图片描述
  2. findChild可以找到子控件
  3. 注意控件的geometry属性的x,y是相对于父级控件里的
  4. 移动控件可以用setGeometry(x, y, w, h)或者move(x, y)和resize(w, h)
  5. 关于控件的geometry
包含Window Title
  • widget.x()、widget.y()
  • widget.pos().x()widget.pos().y()
  • widget.frameGeometry().width()widget.frameGeometry().height()
不包含Window Title的(Client Area)
  • widget.geometry()
    -widget.geometry().x()widget.geometry().y()widget.geometry().width()widget.geometry().height()
  • widget.width()widget.height()
    在这里插入图片描述
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/秋刀鱼在做梦/article/detail/838931
推荐阅读
相关标签
  

闽ICP备14008679号