QRectF rect(0.0, 0.0, 100.0, 50.0); rect.moveTop(rect.top() - 10.0);
void MyWidget::mousePressEvent(QMouseEvent* event) { // Save starting position of mouse m_startPos = event->pos(); // Check if mouse is within rectangle if (m_rect.contains(m_startPos)) { // Remember old position of rectangle m_oldRect = m_rect; } } void MyWidget::mouseMoveEvent(QMouseEvent* event) { if (!m_oldRect.isNull()) { // Compute new position of rectangle QPointF diff = event->pos() - m_startPos; m_rect = m_oldRect.translated(0.0, diff.y()); m_rect = m_rect.normalized(); update(); } } void MyWidget::paintEvent(QPaintEvent*) { QPainter painter(this); painter.fillRect(m_rect, Qt::red); } QRectF m_rect(50.0, 50.0, 100.0, 50.0); QRectF m_oldRect; QPoint m_startPos;In this example, we implement mouse press, mouse move, and paint events to move a rectangle using mouse input. We save the starting position of the mouse in mousePressEvent and check if it's within the rectangle. If it is, we remember the old position of the rectangle. Then in mouseMoveEvent, we compute the difference in mouse position from the starting position, and use moveTop (through translated) to move the rectangle by that amount on the y-axis. We also call normalized to ensure that the rectangle has positive width and height. In paintEvent, we simply draw the rectangle using a QPainter. This example uses Qt library.