How to auto detect pixmap QLabel save factor without using classes?

We are creating a graphical interface using PyQt and Qt Designer. Now we need the image (pixmap) placed in QLabel to beautifully maintain the ratio when resizing the window.

I read other questions / answers, but they all use extended classes. Since we are constantly making changes to our user interface and creating it using Qt Creator, the .ui and (corresponding) .py files are automatically generated, so if I am not mistaken, using a solution class is not a good option for us, because we must manually change the class name every time we update ui.

Is there a way to autoresist pixmap in QLAbel while maintaining this ratio and avoiding the use of extended clans?

Thanks.

+4
source share
3 answers

There are several ways to do this.

First, you can promote QLabel in Qt Designer into a custom subclass written in python. Right-click QLabel and select Promote ..., then give the class a name (for example, "ScaledLabel") and set the header file in the python module from which the custom subclass class will be imported (for example, "mylib. Classes).

The custom subclass is then reimplemented resizeEventas follows:

class ScaledLabel(QtGui.QLabel):
    def __init__(self, *args, **kwargs):
        QtGui.QLabel.__init__(self)
        self._pixmap = QtGui.QPixmap(self.pixmap())

    def resizeEvent(self, event):
        self.setPixmap(self._pixmap.scaled(
            self.width(), self.height(),
            QtCore.Qt.KeepAspectRatio))

QLabel ​​ , ( ).

:

class MainWindow(QtGui.QMainWindow):
    def __init__(self):
        ...
        self._pixmap = QtGui.QPixmap(self.label.pixmap())
        self.label.installEventFilter(self)

    def eventFilter(self, widget, event):
        if (event.type() == QtCore.QEvent.Resize and
            widget is self.label):
            self.label.setPixmap(self._pixmap.scaled(
                self.label.width(), self.label.height(),
                QtCore.Qt.KeepAspectRatio))
            return True
        return QtGui.QMainWindow.eventFilter(self, widget, event)
+5

- QWidget/QLabel resizeEvent.

void QWidget:: resizeEvent ( QResizeEvent *) [ ]

, . resizeEvent(), . QResizeEvent:: oldSize().

. ( ) .

++, PyQt.

QtDesigner :

Qt Designer

+1

QSS background-image:, background-repeat: background-position . QWidget::setStyleSheet.

QSS ( ) - http://doc.qt.io/qt-5/stylesheet-reference.html

+1

All Articles