2014-06-30 27 views
0

我已經通過繪製均勻分佈的水平和垂直線繪製在一個像素映像的網格,並且我試圖使每個矩形網格件selectable.使圖像的某些區域選擇性

換句話說,如果一個用戶點擊網格中的某個矩形,然後將其存儲爲單獨的像素圖。我曾嘗試使用QRubberBand

但我不知道如何限制選擇到被選中的特定部分。有沒有辦法使用PyQt來做到這一點?

這裏是我的畫格到像素映射代碼:

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() 

回答

0

擴展您的QWidget派生類重寫mousePressEvent,然後根據實際的鼠標位置找到瓷磚和存儲像素圖的一部分你想存儲。只需將以下方法添加到您的課堂並填寫您的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 
+0

另請參見[Python的 - PyQt4中如何檢測的任何地方在窗口中單擊鼠標的位置?](http://stackoverflow.com/questions/19825650/python-pyqt4-how-to-detect-the-鼠標點擊位置的任何地方,在最窗口) – Trilarion