-
-
Notifications
You must be signed in to change notification settings - Fork 2k
/
ImageSlipped.py
78 lines (67 loc) · 2.37 KB
/
ImageSlipped.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 2018年10月18日
@author: Irony
@site: https://pyqt.site , https://github.com/PyQt5
@email: [email protected]
@file: ImageSlipped
@description:
"""
try:
from PyQt5.QtGui import QPixmap, QPainter
from PyQt5.QtWidgets import QWidget, QApplication
except ImportError:
from PySide2.QtGui import QPixmap, QPainter
from PySide2.QtWidgets import QWidget, QApplication
class SlippedImgWidget(QWidget):
def __init__(self, bg, fg, *args, **kwargs):
super(SlippedImgWidget, self).__init__(*args, **kwargs)
# 开启鼠标跟踪
self.setMouseTracking(True)
# 背景
self.bgPixmap = QPixmap(bg)
# 前景
self.pePixmap = QPixmap(fg)
# 最小尺寸(背景右边和下方隐藏10个像素)
size = self.bgPixmap.size()
self.setMinimumSize(size.width() - 10, size.height() - 10)
self.setMaximumSize(size.width() - 10, size.height() - 10)
# 分成10份用于鼠标移动判断
self.stepX = size.width() / 10
self.stepY = size.height() / 10
# 偏移量
self._offsets = [-4, -4, -4, -4] # 背景(-4,-4),前景(-4,-4)
def mouseMoveEvent(self, event):
super(SlippedImgWidget, self).mouseMoveEvent(event)
pos = event.pos()
# 偏移量
offsetX = 5 - int(pos.x() / self.stepX)
offsetY = 5 - int(pos.y() / self.stepY)
self._offsets[0] = offsetX
self._offsets[1] = offsetY
self._offsets[2] = offsetX
self._offsets[3] = offsetY
# 刷新
self.update()
def paintEvent(self, event):
super(SlippedImgWidget, self).paintEvent(event)
# 绘制图形
painter = QPainter(self)
painter.setRenderHint(QPainter.Antialiasing)
# 左上角偏移5个像素画背景图片
painter.drawPixmap(
-5 + self._offsets[0],
-5 + self._offsets[1], self.bgPixmap)
# 右下角偏移5个像素画前景图片
painter.drawPixmap(
self.width() - self.pePixmap.width() + 5 - self._offsets[2],
self.height() - self.pePixmap.height() + 5 - self._offsets[3],
self.pePixmap
)
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = SlippedImgWidget('Data/bg1.jpg', 'Data/fg1.png')
w.show()
sys.exit(app.exec_())