Skip to content Skip to sidebar Skip to footer

How Create A Square At Any Position Of Canvas That Can Be Moved At Any Position On The Canvas

I have created a square at random position in canvas, but I don't know how do I move it to somewhere else in canvas by dragging it to desired position, please suggest some edits or

Solution 1:

The logic of creating a dynamic element is to indicate a set of specific characteristics that by modifying these, the element is modified.

In this case you could use the center of the square, the dimensions of the square, etc. and that data must be implemented through a data structure that can be created from scratch for example by creating a class that has the information of the rectangle, but in Qt it is not necessary to create that element since it already exists and is QRect.

Now that that element has been identified, you can create a QRect whose top-left is random when the button is pressed, and use that QRect to paint it.

For dragging the procedure is:

  • Get the mouse click position.
  • Verify that the click is inside the rectangle.
  • Calculate the position relative to the rectangle.
  • When moving the mouse, the position of the rectangle must be updated based on the position of the mouse press.

Considering all of the above, the solution is:

import random
import sys

from PyQt5 import QtCore, QtGui, QtWidgets


class Window(QtWidgets.QMainWindow):
    def __init__(self):
        super(Window, self).__init__()

        self.rect = QtCore.QRect()
        self.drag_position = QtCore.QPoint()

        button = QtWidgets.QPushButton("Add", self)
        button.clicked.connect(self.on_clicked)

        self.resize(640, 480)

    @QtCore.pyqtSlot()
    def on_clicked(self):
        if self.rect.isNull():
            self.rect = QtCore.QRect(
                QtCore.QPoint(*random.sample(range(200), 2)), QtCore.QSize(100, 100)
            )
            self.update()

    def paintEvent(self, event):
        super().paintEvent(event)
        if not self.rect.isNull():
            painter = QtGui.QPainter(self)
            painter.setRenderHint(QtGui.QPainter.Antialiasing)
            painter.setPen(QtGui.QPen(QtCore.Qt.black, 5, QtCore.Qt.SolidLine))
            painter.drawRect(self.rect)

    def mousePressEvent(self, event):
        if self.rect.contains(event.pos()):
            self.drag_position = event.pos() - self.rect.topLeft()
        super().mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if not self.drag_position.isNull():
            self.rect.moveTopLeft(event.pos() - self.drag_position)
            self.update()
        super().mouseMoveEvent(event)

    def mouseReleaseEvent(self, event):
        self.drag_position = QtCore.QPoint()
        super().mouseReleaseEvent(event)


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    Rect = Window()
    Rect.show()
    sys.exit(app.exec_())

Post a Comment for "How Create A Square At Any Position Of Canvas That Can Be Moved At Any Position On The Canvas"