问题描述
我正在尝试通过按钮旋转背景图像并在窗口上修剪图像,但是它不起作用,我也不知道为什么它不起作用。
但是当我按下按钮时,我的图像就消失了...
这是我的代码:
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)
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_())
解决方法
“ 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)
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)