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

后端 未结 1 990
别那么骄傲
别那么骄傲 2021-01-07 03:45

I am trying to piece together PyQt5 based image viewer Python code from various sources and extend capability to crop regions of interest (ROI) within loaded images. The iss

相关标签:
1条回答
  • 2021-01-07 04:16

    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')
    
    0 讨论(0)
提交回复
热议问题