我正在尝试编写一个简单的应用程序,该应用程序在按下按钮时会旋转png图像。除了图像旋转时,它在东南方向偏离中心之外,其他一切工作正常。我以为它没有绕其中心旋转,但它每旋转45度就会返回原点,这很奇怪。
在关键事件上,我只是打电话给:
pixmap = pixmap.transformed(QtGui.QTransform().rotate(-self.rot), QtCore.Qt.SmoothTransformation)
Run Code Online (Sandbox Code Playgroud)
有没有一种方法可以设置转换的原点以停止图像移动?
如果使用QLabel绘制QPixmap,一个简单的解决方案是将QLabel的对齐方式设置为AlignCenter。此外,为了避免在图像旋转的前45度期间对QLabel进行初始调整,可以将QLabel的最小大小设置为像素图对角线的值。然后,图像应绕其中心正确旋转,而不会发生不必要的来回平移。
下面,我演示如何在一个简单的应用程序中完成此操作:
import sys
from PyQt4 import QtGui, QtCore
import urllib
class myApplication(QtGui.QWidget):
def __init__(self, parent=None):
super(myApplication, self).__init__(parent)
#---- Prepare a Pixmap ----
url = ('http://sstatic.net/stackexchange/img/logos/' +
'careers/careers-icon.png?v=0288ba302bf6')
self.img = QtGui.QImage()
self.img.loadFromData(urllib.urlopen(url).read())
pixmap = QtGui.QPixmap(self.img)
#---- Embed Pixmap in a QLabel ----
diag = (pixmap.width()**2 + pixmap.height()**2)**0.5
self.label = QtGui.QLabel()
self.label.setMinimumSize(diag, diag)
self.label.setAlignment(QtCore.Qt.AlignCenter)
self.label.setPixmap(pixmap)
#---- Prepare a Layout ----
grid = QtGui.QGridLayout()
button = QtGui.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):
#---- rotate ----
# Rotate from initial image to avoid cumulative deformation from
# transformation
pixmap = QtGui.QPixmap(self.img)
self.rotation += 15
transform = QtGui.QTransform().rotate(self.rotation)
pixmap = pixmap.transformed(transform, QtCore.Qt.SmoothTransformation)
#---- update label ----
self.label.setPixmap(pixmap)
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
instance = myApplication()
instance.show()
sys.exit(app.exec_())
Run Code Online (Sandbox Code Playgroud)
结果是:
或者,此帖子:无法使图像在Qt中居中旋转,如果QPixmap直接用绘制,似乎可以解决您的问题QPainter。