【问题标题】:Rotate background PYQT5旋转背景 PYQT5
【发布时间】:2024-05-29 20:40:02
【问题描述】:

我正在尝试使用按钮旋转背景图像并在窗口上修剪图像,但它不起作用,我不知道为什么它不起作用。

但是当我按下按钮时,我的图像就消失了......

这是我的代码:

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_())

【问题讨论】:

    标签: python pyqt rotation pyqt5 pixmap


    【解决方案1】:

    "self.img" 是一个空的 QImage 并且您正在旋转该元素。这个想法是旋转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)
    

    【讨论】:

    • @felipeM 注意:如果您已将 QLabel 更改为 QGraphicsScene,那么这意味着这是另一个问题,因此您应该创建另一个帖子。这些是 SO 规则。