Keeping the aspect ratio of a sub-classed QWidget during resize

后端 未结 2 641
天命终不由人
天命终不由人 2021-01-11 11:36

I\'m creating a new widget, by subclassing the QWidget class. I\'d like to be able to set a ratio (for its height and its width) for this widget, which will always be mainta

2条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-11 12:16

    I have rewritten Anthony's code in Python/PySide2:

    from PySide2.QtWidgets import QBoxLayout, QSpacerItem, QWidget
    
    
    class AspectRatioWidget(QWidget):
        def __init__(self, widget, parent):
            super().__init__(parent)
            self.aspect_ratio = widget.size().width() / widget.size().height()
            self.setLayout(QBoxLayout(QBoxLayout.LeftToRight, self))
            #  add spacer, then widget, then spacer
            self.layout().addItem(QSpacerItem(0, 0))
            self.layout().addWidget(widget)
            self.layout().addItem(QSpacerItem(0, 0))
    
        def resizeEvent(self, e):
            w = e.size().width()
            h = e.size().height()
    
            if w / h > self.aspect_ratio:  # too wide
                self.layout().setDirection(QBoxLayout.LeftToRight)
                widget_stretch = h * self.aspect_ratio
                outer_stretch = (w - widget_stretch) / 2 + 0.5
            else:  # too tall
                self.layout().setDirection(QBoxLayout.TopToBottom)
                widget_stretch = w / self.aspect_ratio
                outer_stretch = (h - widget_stretch) / 2 + 0.5
    
            self.layout().setStretch(0, outer_stretch)
            self.layout().setStretch(1, widget_stretch)
            self.layout().setStretch(2, outer_stretch)
    

提交回复
热议问题