Files
PDFReaderLite/pdfreaderlite/ui/signature_dialog.py
T

73 lines
2.4 KiB
Python

from __future__ import annotations
from pathlib import Path
from PySide6.QtCore import QPoint, Qt
from PySide6.QtGui import QColor, QImage, QPainter, QPen
from PySide6.QtWidgets import QDialog, QDialogButtonBox, QPushButton, QVBoxLayout, QWidget
class SignaturePad(QWidget):
def __init__(self) -> None:
super().__init__()
self.setMinimumSize(520, 220)
self.image = QImage(520, 220, QImage.Format.Format_ARGB32)
self.image.fill(Qt.GlobalColor.transparent)
self._last_point: QPoint | None = None
def clear(self) -> None:
self.image.fill(Qt.GlobalColor.transparent)
self.update()
def save(self, path: str | Path) -> None:
self.image.save(str(path), "PNG")
def paintEvent(self, event) -> None:
painter = QPainter(self)
painter.fillRect(self.rect(), QColor("#ffffff"))
painter.drawImage(0, 0, self.image)
def mousePressEvent(self, event) -> None:
if event.button() == Qt.MouseButton.LeftButton:
self._last_point = event.position().toPoint()
def mouseMoveEvent(self, event) -> None:
if self._last_point is None:
return
current_point = event.position().toPoint()
painter = QPainter(self.image)
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
painter.setPen(QPen(QColor("#111111"), 3, Qt.PenStyle.SolidLine, Qt.PenCapStyle.RoundCap))
painter.drawLine(self._last_point, current_point)
painter.end()
self._last_point = current_point
self.update()
def mouseReleaseEvent(self, event) -> None:
if event.button() == Qt.MouseButton.LeftButton:
self._last_point = None
class SignatureDialog(QDialog):
def __init__(self, parent=None) -> None:
super().__init__(parent)
self.setWindowTitle("手写签名")
self.pad = SignaturePad()
clear_button = QPushButton("清除")
clear_button.clicked.connect(self.pad.clear)
buttons = QDialogButtonBox(
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
)
buttons.accepted.connect(self.accept)
buttons.rejected.connect(self.reject)
layout = QVBoxLayout(self)
layout.addWidget(self.pad)
layout.addWidget(clear_button)
layout.addWidget(buttons)
def save_signature(self, path: str | Path) -> None:
self.pad.save(path)