当前位置:网站首页>【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的size
findChild可以找到子控件- 注意控件的
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()
边栏推荐
猜你喜欢

MySQL 45 Talk | 09 How to choose common index and unique index?

JVM运行时数据区与JMM内存模型是什么

Leetcode72. Edit Distance

C语言理论--笔试面试基础稳固

OpenCV安装、QT、VS配置项目设置

odoo 编码规范(编程规范、编码指南)

B002 - Embedded Elderly Positioning Tracking Monitor

将ENS域名转化为音乐需要几步?

Prometheus的Recording rules实践

Fuzzy query in Map pass-by-value and object pass-by-value
随机推荐
Industry Salon Phase II丨How to enable chemical companies to reduce costs and increase efficiency through supply chain digital business collaboration?
ACID Characteristics and Implementation Methods of MySQL Relational Database Transactions
Map传值
国标GB28181协议EasyGBS平台兼容老版本收流端口的功能实现
MySQL关系型数据库事务的ACID特性与实现方法
C#/VB.NET: extracted from the PDF document all form
QT_QDialog dialog
B005 - STC8 based single chip microcomputer intelligent street light control system
Go GORM transaction instance analysis
7月30号|来一场手把手助您打造智能视觉新爆款的技术动手实验
EpiSci|片上系统的深度强化学习:神话与现实
电商库存系统的防超卖和高并发扣减方案
深入浅出Flask PIN
用VS2013编译带boost库程序时提示 fatal error C1001: 编译器中发生内部错误
opencv实时人脸检测
QPalette调色板、框架色彩填充
How many steps does it take to convert an ENS domain name into music?
Prometheus的Recording rules实践
【LeetCode】Day109-the longest palindrome string
golang json returns null