Image Viewer GUI fails to properly map coordinates for mouse press event

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-01 14:01:06

It is better in these cases that the QRubberBand is the son of the QLabel so there will be no need to make many transformations.

On the other hand, the coordinates of the event are related to the window, so we have to convert it to the coordinates of the QLabel. For this a simple methodology is to convert the local coordinate with respect to the window to global coordinates and then the global coordinates to local coordinates with respect to the QLabel.

And finally when you scale the image you affect the coordinates since the currentQRect is relative to the scaled QLabel but the internal QPixmap is not scaled.

def mousePressEvent (self, event):
    self.originQPoint = self.imageLabel.mapFromGlobal(self.mapToGlobal(event.pos())) 
    self.currentQRubberBand = QtWidgets.QRubberBand(QtWidgets.QRubberBand.Rectangle, self.imageLabel)
    self.currentQRubberBand.setGeometry(QtCore.QRect(self.originQPoint, QtCore.QSize()))
    self.currentQRubberBand.show()

def mouseMoveEvent (self, event):
    p = self.imageLabel.mapFromGlobal(self.mapToGlobal(event.pos()))
    QtWidgets.QToolTip.showText(event.pos() , "X: {} Y: {}".format(p.x(), p.y()), self)
    if self.currentQRubberBand.isVisible() and self.imageLabel.pixmap() is not None:
        self.currentQRubberBand.setGeometry(QtCore.QRect(self.originQPoint, p).normalized() & self.imageLabel.rect())

def mouseReleaseEvent (self, event):
    self.currentQRubberBand.hide()
    currentQRect = self.currentQRubberBand.geometry()
    self.currentQRubberBand.deleteLater()
    if self.imageLabel.pixmap() is not None:
        tr = QtGui.QTransform()
        if self.fitToWindowAct.isChecked():
            tr.scale(self.imageLabel.pixmap().width()/self.scrollArea.width(), 
                self.imageLabel.pixmap().height()/self.scrollArea.height())
        else:
            tr.scale(1/self.scaleFactor, 1/self.scaleFactor)
        r = tr.mapRect(currentQRect)
        cropQPixmap = self.imageLabel.pixmap().copy(r)
        cropQPixmap.save('output.png')
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!