Skip to content
Advertisement

How to rotate an QImage

I want to rotate my QImage by the amount of x.

I don’t want to use QPixMap or the PaintEvent if possible.

I have already searched for possible solutions but they didn’t work.

Right now i am trying to solve it with the QTransform method:

class MainWindow(QMainWindow):

    def rotate_pdf_ui(self):
        for index, object in enumerate(self.page_objects):
            if object.push_button.isChecked():
                object.rotate(90)
        self.delete_old_position()
        self.position_push_buttons_in_grid()

    def position_push_buttons_in_grid(self):
        row = 0
        column = 0
        for page_object in self.page_objects:
            self.ui.pushButtonGrid.addWidget(page_object.push_button, row, column)
            column += 1
            if int(len(self.page_objects) / 4) is column:
                row += 1
                column = 0
        self.ui.widgetLayout.setLayout(self.ui.pushButtonGrid)

    def delete_old_position(self):
        for push_button in reversed(range(self.ui.pushButtonGrid.count())):
            button_to_remove = self.ui.pushButtonGrid.itemAt(push_button).widget()
            self.ui.pushButtonGrid.removeWidget(button_to_remove)
            button_to_remove.setParent(None)
        return self.ui.pushButtonGrid

class PageObject:

    def rotate(self, rotation):
        my_transform = QTransform()
        my_transform.rotate(rotation)
        self.img.transformed(my_transform)
        self.rotation += rotation

I don’t get any error message the image is just not rotated.

Advertisement

Answer

I found the mistake! Thank you furas: self.img = self.img.transformed(my_transform) was the first half of the solution! In PySide2 and PyQt5 you have to create the QPushButton again to get the new image displayed otherwise it is just changed but never displayed.

def rotate_pdf_ui(self):
    for index, object in enumerate(self.page_objects):
        if object.push_button.isChecked():
            object.rotate(90)
            object.rotation += 90
    self.delete_old_position()
    self.position_push_buttons_in_grid()

def rotate(self, rotation):
    my_transform = QTransform()
    my_transform.rotate(rotation)
    self.img = self.img.transformed(my_transform)
    self.rotation += rotation
    self.push_button = self.createPushButton()
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement