QRubberband pyqt5 center item breaks grab

27 Views Asked by At

Could someone help me with the following issue. I am attempting to use Qrubberband to make a crop of an image.

The following code worked well and made a small popup appear with the photo inside which I could crop perfectly. The issue is I wanted the pop up to appear in the middle of a full screen window and not the top left of my screen. Adding the following lines acheived what I wanted.

self.showMaximized()
self.setAlignment(Qt.AlignCenter)

However, now I have centered the image and backed it in a full sized window. The crop coordinates no longer work as expected. Is there a simple fix for this ?

  import sys
    from PyQt5 import QtCore, QtGui
    from PyQt5.QtWidgets import *
    from PyQt5.QtCore import *
    
    
    class Cropper (QLabel):
        def __init__(self, parentQWidget = None):
            super(Cropper, self).__init__(parentQWidget)
            self.showMaximized()
            self.initUI()
    
        def initUI (self):
            self.setPixmap(QtGui.QPixmap('dog4-300x178.png'))
            self.setAlignment(Qt.AlignCenter)
    
        def mousePressEvent (self, eventQMouseEvent):
            self.originQPoint = eventQMouseEvent.pos()
            self.currentQRubberBand = QRubberBand(QRubberBand.Rectangle, self)
            self.currentQRubberBand.setGeometry(QtCore.QRect(self.originQPoint, QtCore.QSize()))
            self.currentQRubberBand.show()
    
        def mouseMoveEvent (self, eventQMouseEvent):
            self.currentQRubberBand.setGeometry(QtCore.QRect(self.originQPoint, eventQMouseEvent.pos()).normalized())
    
        def mouseReleaseEvent (self, eventQMouseEvent):
            self.currentQRubberBand.hide()
            currentQRect = self.currentQRubberBand.geometry()
            self.currentQRubberBand.deleteLater()
            cropQPixmap = self.pixmap().copy(currentQRect)
            cropQPixmap.save('output.png')
            print("saved crop")
    
    if __name__ == '__main__':
        myQApplication = QApplication(sys.argv)
        myCropper = Cropper()
        myCropper.show()
        sys.exit(myQApplication.exec_())

Thank you :-)

0

There are 0 best solutions below