Created
December 11, 2019 16:10
-
-
Save justengel/fd50fa419af5074567ede3778f8cd4f2 to your computer and use it in GitHub Desktop.
Qt re-sizable image label.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from qtpy import QtCore, QtWidgets, QtGui | |
class QImageLabel(QtWidgets.QLabel): | |
doubleClicked = QtCore.Signal() | |
def loadFile(self, filename): | |
"""Load the image with the given filename.""" | |
pm = QtGui.QPixmap() | |
with open(filename, 'rb') as f: | |
pm.loadFromData(f.read()) | |
self.setPixmap(pm) | |
def setPixmap(self, pixmap): | |
"""Set the pixmap to display the image for.""" | |
self._pixmap = pixmap | |
super().setPixmap(pixmap) | |
def pixmapSize(self): | |
"""Get the pixmap size.""" | |
try: | |
return self._pixmap.size() | |
except: | |
return self.size() | |
def toggleMaximized(self): | |
"""Toggle the image as maximized or the normal image size.""" | |
if self.isMaximized(): | |
self.showNormal() | |
self.resize(self.pixmapSize()) | |
else: | |
self.showMaximized() | |
def mouseDoubleClickEvent(self, event): | |
self.doubleClicked.emit() | |
return super().mouseDoubleClickEvent(event) | |
def resizeEvent(self, event): | |
try: | |
size = event.size() | |
if size != super().pixmap().size(): | |
super().setPixmap(self._pixmap.scaled(size.width(), size.height(), | |
QtCore.Qt.KeepAspectRatio, | |
QtCore.Qt.SmoothTransformation)) | |
except (AttributeError, Exception): | |
pass | |
return super().resizeEvent(event) | |
if __name__ == '__main__': | |
import sys | |
FILENAME = None | |
if len(sys.argv) > 1: | |
FILENAME = sys.argv[1] | |
app = QtWidgets.QApplication([]) | |
lbl = QClickImgLabel() | |
lbl.loadFile(FILENAME) | |
lbl.show() | |
lbl.doubleClicked.connect(lbl.toggleMaximized) | |
app.exec_() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment