当前位置:网站首页>【pyqt5】自定义控件 实现能够保持长宽比地缩放子控件
【pyqt5】自定义控件 实现能够保持长宽比地缩放子控件
2022-08-01 18:22:00 【__Watson__】
需求
在窗口缩放过程中,实现控件按照一定的长宽比缩放
实现思路
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)
2. 在qt designer里设计ui时使用frame提升为上面自定义的类
将要保持长宽比的控件(需要设定初始的长宽)放入该自定义的frame中(不要添加布局)
小节
QResizeEvent
事件的传入,可以通过event访问resieze前后的widget的sizefindChild
可以找到子控件- 注意控件的
geometry属性的x,y
是相对于父级控件里的 - 移动控件可以用
setGeometry(x, y, w, h)
或者move(x, y)和resize(w, h)
- 关于控件的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()
边栏推荐
- 7月30号|来一场手把手助您打造智能视觉新爆款的技术动手实验
- ExcelPatternTool: Excel表格-数据库互导工具
- QT_QDialog dialog
- CodeTON Round 2 (Div. 1 + Div. 2, Rated, Prizes!) Solution
- How to use the Golang coroutine scheduler scheduler
- Clip-on multimeter use method, how to measure the voltage, current, resistance?
- 【Day_10 0428】井字棋
- Fuzzy query in Map pass-by-value and object pass-by-value
- B011 - 51-based multifunctional fingerprint smart lock
- Summer vacation first week wrap-up blog
猜你喜欢
随机推荐
行业沙龙第二期丨如何通过供应链数字化业务协同,赋能化工企业降本增效?
QT_Event class
阿里云的域名和ip绑定
请你说说多线程
XML配置
123123123123
Leetcode72. 编辑距离
【LeetCode】Day109-最长回文串
LeetCode 1374. Generate an odd number of each character string
The function realization of the national standard GB28181 protocol EasyGBS platform compatible with the old version of the inflow port
C language theory--a solid foundation for the written test and interview
el-form-item prop属性动态绑定不生效如何解决
QT_QThread线程
QT basic functions, signals, slots
C#/VB.NET:从 PDF 文档中提取所有表格
LeetCode 0151.颠倒字符串中的单词
暑假第二周总结博客
OnePlus 10RT appears on Geekbench, product launch also seems to be approaching
odoo+物联网
2022年 PHP面试问题记录