我正在尝试编写一个简单的应用程序,在按下按钮时旋转 png 图像。我一切正常,只是当图像旋转时,它偏离了东南方向的中心。我本以为它不是绕着中心旋转,但每旋转 45 度它就会回到原点,这很奇怪。
对于一个关键事件,我只是简单地调用:
pixmap = pixmap.transformed(QtGui.QTransform().rotate(-self.rot), QtCore.Qt.SmoothTransformation)
有没有办法设置变换的原点来阻止图像移动?
一个简单的解决方案,如果您使用的是QLabel https://srinikom.github.io/pyside-docs/PySide/QtGui/QLabel.html画出QPixmap https://srinikom.github.io/pyside-docs/PySide/QtGui/QPixmap.html,就是设置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_())
结果是:
或者,这篇文章:无法让图像在Qt中中心旋转 https://stackoverflow.com/questions/10767587/cant-get-the-image-to-rotate-in-center-in-qt/12989406#12989406,如果您正在绘制,似乎可以解决您的问题QPixmap
直接与QPainter
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)