选择图像的某些区域

2024-05-19 14:30:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我在pixmap上画了一个等距的水平线和垂直线,并试图使每个矩形网格块selectable.

换句话说,如果用户单击网格中的某个矩形,那么它将被存储为一个单独的pixmap。我尝试过使用QRubberBand。在

但我不知道如何将选择限制在所选的特定部分。有没有使用PyQt的方法?在

以下是我在pixmap上绘制网格的代码:

class imageSelector(QtGui.QWidget):

    def __init__(self):
        super(imageSelector,self).__init__()
        self.initIS()

    def initIS(self):
        self.pixmap = self.createPixmap()

        painter = QtGui.QPainter(self.pixmap)
        pen = QtGui.QPen(QtCore.Qt.white, 0, QtCore.Qt.SolidLine)
        painter.setPen(pen)

        width = self.pixmap.width()
        height = self.pixmap.height()

        numLines = 6
        numHorizontal = width//numLines
        numVertical = height//numLines
        painter.drawRect(0,0,height,width)

        for x in range(numLines):
            newH = x * numHorizontal
            newV = x * numVertical
            painter.drawLine(0+newH,0,0+newH,width)
            painter.drawLine(0,0+newV,height,0+newV)

        label = QtGui.QLabel()
        label.setPixmap(self.pixmap)
        label.resize(label.sizeHint())

        hbox = QtGui.QHBoxLayout()
        hbox.addWidget(label)

        self.setLayout(hbox)
        self.show()          

    def createPixmap(self):
        pixmap = QtGui.QPixmap("CT1.png").scaledToHeight(500)
        return pixmap

def main():
    app = QtGui.QApplication(sys.argv)
    Im = imageSelector()
    sys.exit(app.exec_())

if __name__== '__main__':
    main()

Tags: self网格maindefwidthlabelheightpainter
1条回答
网友
1楼 · 发布于 2024-05-19 14:30:54

扩展您的QWidget派生类以覆盖mousePressEvent,然后根据实际鼠标位置找到图块并存储您要存储的pixmap部分。只需将以下方法添加到类中,并为您的pixmap剪切和存储填充特定的代码。在

def mousePressEvent(event):
  """
    User has clicked inside the widget
  """
  # get mouse position
  x = event.x()
  y = event.y()
  # find coordinates of grid rectangle in your grid
  # copy and store this grid rectangle

如果你想的话,你甚至可以显示一个从一个矩形跳到另一个矩形的矩形橡皮筋。对于此重写mouseMoveEvent。在

^{pr2}$

相关问题 更多 >