Re: [問題] PySide2 使用滑鼠旋轉圖片

作者: skyconquer (梅郭曲)   2020-05-26 15:01:33
※ 引述《janice001 ()》之銘言:
: 如標題
: 請問如何使用 PySide2
: 要如何才可以像 power point 那樣
: 可以使用滑鼠旋轉圖片?
: 感恩
: 更新補上影片
: https://i.imgur.com/iUDws4r.gif
試著寫了一些有類似效果的程式碼:
點進去可以看到動起來的樣子
程式碼在此:
# 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