我通过绘制均匀分布的水平和垂直线在像素图上绘制了一个网格,我正在尝试制作每个矩形网格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 :(得分: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