Skip to content

Instantly share code, notes, and snippets.

@wention
Last active July 12, 2023 08:49
Show Gist options
  • Save wention/1f350059ad34b3b177277ec685550347 to your computer and use it in GitHub Desktop.
Save wention/1f350059ad34b3b177277ec685550347 to your computer and use it in GitHub Desktop.
Qt Utils
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
def rect_scale(source, target, aspect=Qt.IgnoreAspectRatio):
"""缩放
source 待缩放
target 目标
"""
ratio = source.width() / source.height()
tgt_ratio = target.width() / target.height()
if aspect == Qt.IgnoreAspectRatio:
width = target.width()
height = target.height()
else:
if ratio > tgt_ratio or aspect == Qt.KeepAspectRatioByExpanding:
width = target.width()
height = width / ratio
else:
height = target.height()
width = height * ratio
return QRectF(source.x(), source.y(), width, height)
def rect_align(source, target, align=Qt.AlignCenter):
src = QRectF(source)
if align & Qt.AlignHCenter:
src.moveCenter(QPointF(target.center().x(), src.center().y()))
if align & Qt.AlignVCenter:
src.moveCenter(QPointF(src.center().x(), target.center().y()))
if align & Qt.AlignLeft:
src.moveLeft(target.left())
if align & Qt.AlignTop:
src.moveTop(target.top())
if align & Qt.AlignRight:
src.moveRight(target.right())
if align & Qt.AlignBottom:
src.moveBottom(target.bottom())
return src
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment