How to draw a rectangle and adjust its shape by drag and drop in PyQt5

后端 未结 1 1855
时光取名叫无心
时光取名叫无心 2020-12-09 07:20

I\'m trying to draw a rectangle on GUI created by PyQt5 by drag and drop. I managed to do that, but the rectangle is drawn when the mouse left key is released.

What

相关标签:
1条回答
  • 2020-12-09 07:27

    You do not have to use the mouseReleaseEvent function, but the mouseMoveEvent function that is called each time the mouse is moved, and I have modified the code to make it simpler.

    class MyWidget(QtWidgets.QWidget):
        def __init__(self):
            super().__init__()
            self.setGeometry(30,30,600,400)
            self.begin = QtCore.QPoint()
            self.end = QtCore.QPoint()
            self.show()
    
        def paintEvent(self, event):
            qp = QtGui.QPainter(self)
            br = QtGui.QBrush(QtGui.QColor(100, 10, 10, 40))  
            qp.setBrush(br)   
            qp.drawRect(QtCore.QRect(self.begin, self.end))       
    
        def mousePressEvent(self, event):
            self.begin = event.pos()
            self.end = event.pos()
            self.update()
    
        def mouseMoveEvent(self, event):
            self.end = event.pos()
            self.update()
    
        def mouseReleaseEvent(self, event):
            self.begin = event.pos()
            self.end = event.pos()
            self.update()
    
    0 讨论(0)
提交回复
热议问题