pythonpyqtrotationpyqt5pixmap

Rotate background PYQT5


I'm trying to rotate a background image with a button and trim the image over the window, but it doesn't work and I don't know why it is not working.

This is what I expect to get

But when I hit the button my image just fades away...

And here is my code:

import sys
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QGridLayout, QPushButton
from PyQt5.QtGui import QPixmap

class myApplication(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(myApplication, self).__init__(parent)

        self.img = QtGui.QImage()
        pixmap = QtGui.QPixmap("ola.png")
    

        self.label = QLabel(self)
        self.label.setMinimumSize(600, 600)
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setPixmap(pixmap)

        grid = QGridLayout()

        button = QPushButton('Rotate 15 degrees')
        button.clicked.connect(self.rotate_pixmap)

        grid.addWidget(self.label, 0, 0)
        grid.addWidget(button, 1, 0)

        self.setLayout(grid)

        self.rotation = 0

    def rotate_pixmap(self):

        pixmap = QtGui.QPixmap(self.img)
        self.rotation += 15

        transform = QtGui.QTransform().rotate(self.rotation)
        pixmap = pixmap.transformed(transform, QtCore.Qt.SmoothTransformation)

        self.label.setPixmap(pixmap)

if __name__ == '__main__':

    app = QApplication([])

    w = myApplication()  
    w.show()    

    sys.exit(app.exec_())

Solution

  • "self.img" is an empty QImage and you are rotating that element. The idea is to rotate the QPixmap:

    class myApplication(QtWidgets.QWidget):
        def __init__(self, parent=None):
            super(myApplication, self).__init__(parent)
    
            self.rotation = 0
    
            self.pixmap = QtGui.QPixmap("ola.png")
    
            self.label = QLabel()
            self.label.setMinimumSize(600, 600)
            self.label.setAlignment(QtCore.Qt.AlignCenter)
            self.label.setPixmap(self.pixmap)
    
            button = QPushButton("Rotate 15 degrees")
            button.clicked.connect(self.rotate_pixmap)
    
            grid = QGridLayout(self)
            grid.addWidget(self.label, 0, 0)
            grid.addWidget(button, 1, 0)
    
        def rotate_pixmap(self):
            pixmap = self.pixmap.copy()
            self.rotation += 15
            transform = QtGui.QTransform().rotate(self.rotation)
            pixmap = pixmap.transformed(transform, QtCore.Qt.SmoothTransformation)
            self.label.setPixmap(pixmap)