作者skyconquer (梅郭曲)
标题Re: [问题] PySide2 使用滑鼠旋转图片
时间Tue May 26 15:01:33 2020
※ 引述《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()
如果有更好的实作方法,希望版友们不吝指教分享,谢谢。
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 140.135.253.172 (台湾)
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/Python/M.1590476495.A.63D.html
※ 编辑: skyconquer (140.135.253.172 台湾), 05/26/2020 15:11:56
1F:推 janice001: 先跪谢了 05/26 19:35
2F:→ skyconquer: 不会 06/03 20:38