Python 使图像的某些区域可选择

Python 使图像的某些区域可选择,python,image,grid,pyqt,Python,Image,Grid,Pyqt,我已经通过绘制均匀分布的水平线和垂直线在像素地图上绘制了一个网格,并且我正在尝试使每个矩形网格块可选择。 换句话说,如果用户单击网格中的某个矩形,那么它将存储为单独的pixmap。我试过使用QRubberBand 但我不知道如何将选择限制在选定的特定工件上。有没有一种方法可以使用PyQt实现这一点 以下是我在pixmap上绘制网格的代码: class imageSelector(QtGui.QWidget): def __init__(self): super(imag

我已经通过绘制均匀分布的水平线和垂直线在像素地图上绘制了一个网格,并且我正在尝试使每个矩形网格块
可选择。

换句话说,如果用户单击网格中的某个矩形,那么它将存储为单独的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()

扩展您的
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

def mouseMoveEvent(event):
  """
    Mouse is moved inside the widget
  """
  # get mouse position
  x = event.x()
  y = event.y()
  # find coordinates of grid rectangle in your grid
  # move rectangular rubber band to this grid rectangle
也看到