-
Notifications
You must be signed in to change notification settings - Fork 0
/
resizable_rubber_band.py
67 lines (59 loc) · 2.83 KB
/
resizable_rubber_band.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
# Stolen from: https://stackoverflow.com/questions/55307811/select-region-from-an-image-but-resizable-qrubberband-doesnt-resize
from PyQt5 import QtCore, QtGui, QtWidgets
class ResizableRubberBand(QtWidgets.QWidget):
def __init__(self, parent=None):
super(ResizableRubberBand, self).__init__(parent)
self.setMinimumWidth(4)
self.draggable = True
self.dragging_threshold = 0
self.mousePressPos = None
self.mouseMovePos = None
self.borderRadius = 0
self.setWindowFlags(QtCore.Qt.SubWindow)
layout = QtWidgets.QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.addWidget(
QtWidgets.QSizeGrip(self), 0,
QtCore.Qt.AlignLeft | QtCore.Qt.AlignTop)
layout.addWidget(
QtWidgets.QSizeGrip(self), 0,
QtCore.Qt.AlignRight | QtCore.Qt.AlignBottom)
self._band = QtWidgets.QRubberBand(
QtWidgets.QRubberBand.Rectangle, self)
self._band.show()
self.show()
def resizeEvent(self, event):
self._band.resize(self.size())
def paintEvent(self, event):
# Get current window size
window_size = self.size()
qp = QtGui.QPainter()
qp.begin(self)
qp.setRenderHint(QtGui.QPainter.Antialiasing, True)
qp.drawRoundedRect(0, 0, window_size.width(), window_size.height(),
self.borderRadius, self.borderRadius)
qp.end()
def mousePressEvent(self, event):
if self.draggable and event.button() == QtCore.Qt.RightButton:
self.mousePressPos = event.globalPos() # global
self.mouseMovePos = event.globalPos() - self.pos() # local
super(ResizableRubberBand, self).mousePressEvent(event)
def mouseMoveEvent(self, event):
if self.draggable and event.buttons() & QtCore.Qt.RightButton:
globalPos = event.globalPos()
moved = globalPos - self.mousePressPos
if moved.manhattanLength() > self.dragging_threshold:
# Move when user drag window more than dragging_threshold
diff = globalPos - self.mouseMovePos
self.move(diff)
self.mouseMovePos = globalPos - self.pos()
super(ResizableRubberBand, self).mouseMoveEvent(event)
def mouseReleaseEvent(self, event):
if self.mousePressPos is not None:
if event.button() == QtCore.Qt.RightButton:
moved = event.globalPos() - self.mousePressPos
if moved.manhattanLength() > self.dragging_threshold:
# Do not call click event or so on
event.ignore()
self.mousePressPos = None
super(ResizableRubberBand, self).mouseReleaseEvent(event)