wysiwygTextEdit.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. from PyQt5.QtGui import QImage, QTextDocument
  2. from PyQt5.QtWidgets import QTextEdit
  3. from path import Path
  4. import uuid
  5. IMAGE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.bmp']
  6. FONT_SIZES = [7, 8, 9, 10, 11, 12, 13, 14, 18, 24, 36, 48, 64, 72, 96, 144, 288]
  7. HTML_EXTENSIONS = ['.htm', '.html']
  8. class WysiwygTextEdit(QTextEdit):
  9. def __init__(self, parent):
  10. super().__init__(parent)
  11. def canInsertFromMimeData(self, source):
  12. if source.hasImage():
  13. return True
  14. else:
  15. return super(WysiwygTextEdit, self).canInsertFromMimeData(source)
  16. def insertFromMimeData(self, source):
  17. cursor = self.textCursor()
  18. document = self.document()
  19. if source.hasUrls():
  20. for u in source.urls():
  21. file_ext = Path(str(u.toLocalFile())).splitext()
  22. if u.isLocalFile() and file_ext in IMAGE_EXTENSIONS:
  23. image = QImage(u.toLocalFile())
  24. document.addResource(QTextDocument.ImageResource, u, image)
  25. cursor.insertImage(u.toLocalFile())
  26. else:
  27. # If we hit a non-image or non-local URL break the loop and fall out
  28. # to the super call & let Qt handle it
  29. break
  30. else:
  31. # If all were valid images, finish here.
  32. return
  33. elif source.hasImage():
  34. image = source.imageData()
  35. uuid_ = uuid.uuid4().hex
  36. document.addResource(QTextDocument.ImageResource, uuid_, image)
  37. cursor.insertImage(uuid)
  38. return
  39. super(WysiwygTextEdit, self).insertFromMimeData(source)