Re: [问题] PySide2 使用鼠标旋转图片

楼主: skyconquer (梅郭曲)   2020-05-26 15:01:33
※ 引述《janice001 ()》之铭言:
: 如标题
: 请问如何使用 PySide2
: 要如何才可以像 power point 那样
: 可以使用鼠标旋转图片?
: 感恩
: 更新补上影片
: https://i.imgur.com/iUDws4r.gif
试着写了一些有类似效果的程式码:
https://imgur.com/MGyyvV0 点进去可以看到动起来的样子
程式码在此:
# This Python file uses the following encoding: utf-8
# Made by Yu Tso (Roy) for answering the question on PTT:
# 文章代码(AID): #1UnZPCVa (Python) [ptt.cc] [问题] PySide2 使用鼠标旋转图
import sys
from PySide2.QtWidgets import QApplication, QMainWindow
from PySide2.QtWidgets import QGraphicsView, QGraphicsItem
from PySide2.QtWidgets import QGraphicsScene, QGraphicsPixmapItem
from PySide2.QtGui import QPixmap, QImage
from PySide2 import QtCore
import numpy as np
class GraphicsScene(QGraphicsScene):
def __init__(self):
QGraphicsScene.__init__(self)
self.clickPos = QtCore.QPointF(0.0, 0.0)
def mouseMoveEvent(self, e):
QGraphicsScene.mouseMoveEvent(self,e)
for i in self.selectedItems():
centerPoint = (i.boundingRect().topLeft() +
i.boundingRect().bottomRight())/2
i.setTransformOriginPoint(centerPoint)
v1 = self.clickPos - centerPoint
v2 = e.scenePos() - centerPoint
l1 = np.linalg.norm([v1.x(), v1.y()])
l2 = np.linalg.norm([v2.x(), v2.y()])
sine = np.cross([v1.x(),v1.y()], [v2.x(),v2.y()])/(l1*l2)
new_angle = np.arcsin(sine)
i.setRotation(i.rotation() + new_angle)
def mousePressEvent(self,e):
QGraphicsScene.mousePressEvent(self, e)
self.clickPos = e.scenePos()
def mouseReleaseEvent(self,e):
QGraphicsScene.mouseReleaseEvent(self,e)
self.clickPos = QtCore.QPointF(0.0, 0.0)
def addItem(self, item):
QGraphicsScene.addItem(self, item)
self.items()[-1].setFlags(QGraphicsItem.ItemSendsScenePositionChanges
| QGraphicsItem.ItemIsSelectable)
if __name__ == "__main__":
app = QApplication([])
image = QImage("fox1.jpeg")
item = QGraphicsPixmapItem(QPixmap().fromImage(image))
scene = GraphicsScene()
scene.addItem(item)
view = QGraphicsView(scene)
view.resize(500,500)
view.show()
如果有更好的实作方法,希望版友们不吝指教分享,谢谢。
作者: janice001 (真理)   2020-05-26 19:35:00
先跪谢了
楼主: skyconquer (梅郭曲)   2020-06-03 20:38:00
不会

Links booklink

Contact Us: admin [ a t ] ucptt.com