Pyside6,如何在不丢失尺寸纵横比的情况下调整 QLabel 的大小?

Pyside6, How do I resize a QLabel without loosing the size aspect ratio?

我的问题与那些相关帖子中的完全一样:

唯一的区别 是我使用的是 Pyside 而不是 PyQt 而且我 已经找到了answer 但我不想把它张贴在这里以外的任何地方造成任何混乱。

Thanks to this PyQt answer !!!

通过遵循这些简单的示例步骤,我能够找到如何在 PySide6 中完美地完成同样的事情:

  • 打开pyside6-designer\Qt-designer:
1. Create a new window like this one: 2. Right-Click on label and go to "Promote to...":
3. Select Form > View Python Code.. & save it as ui_main.py

click here if you have an issue at step 3.: "Unable to Launch Qt uic"

  • 创建文件:
# custom_widgets.py

from PySide6 import QtCore, QtGui, QtWidgets


class ScaledLabel(QtWidgets.QLabel):
    def __init__(self, *args, **kwargs):
        QtWidgets.QLabel.__init__(self)
        self._pixmap = self.pixmap()
        self._resised= False
    
    def resizeEvent(self, event):
        self.setPixmap(self._pixmap)     

    def setPixmap(self, pixmap): #overiding setPixmap
        if not pixmap:return 
        self._pixmap = pixmap
        return QtWidgets.QLabel.setPixmap(self,self._pixmap.scaled(
                self.frameSize(),
                QtCore.Qt.KeepAspectRatio))
# main.py

from   PySide6.QtWidgets import *
from   PySide6           import QtCore
from   PySide6.QtGui     import QPixmap
from   PySide6.QtCore    import QPropertyAnimation
from   ui_main           import Ui_MainWindow
import sys, os


CWD = os.path.dirname(__file__) + os.sep
class MainWindow(QMainWindow): 
    def __init__(self):
        QMainWindow.__init__(self)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        self.ui.label.setPixmap(QPixmap(CWD + 'lenna.jpg'))
        self.ui.pushButton.clicked.connect(lambda: self.resizeMainWindow(1200,500))
        self.show()

    def resizeMainWindow(self, width, height):
        self.animation = QPropertyAnimation(self, b"size")
        self.animation.setLoopCount(3)
        self.animation.setDuration(3000)
        self.animation.setKeyValueAt(0   ,QtCore.QSize(self.width()  ,self.height()  ))
        self.animation.setKeyValueAt(0.25,QtCore.QSize(self.width()/2,self.height()/2))
        self.animation.setKeyValueAt(0.5 ,QtCore.QSize(self.width()/2,self.height()  ))
        self.animation.setKeyValueAt(0.75,QtCore.QSize(self.width()  ,self.height()/2))
        self.animation.setKeyValueAt(1   ,QtCore.QSize(self.width()  ,self.height()  ))
        self.animation.setEasingCurve(QtCore.QEasingCurve.InOutSine)
        self.animation.start()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    sys.exit(app.exec_())
    
    
    
"""
 * [QPixmap only works with absolute Path](
 * [Relative paths in Python](
 * [resizeMainWindow()](https://github.com/Wanderson-Magalhaes/QPropertyAnimation_PySide2_PyQt5_Widgets_Animation/blob/master/main.py#L60)
"""

如果到目前为止一切顺利,您的工作目录中也应该有一个类似的 ui_main.py 文件 like this one.

  • ✔️ 你应该有一个像左边演示的那样的工作示例:
With ScaledLabel With             QLabel