Check if cursor is near a widget's edges
-
What would be the best way to go around checking if the cursor is near a widget's edges and determining which direction it is, without the use of massive if-blocks?
This is one way:
void mouseMoveEvent(QMouseEvent *event) { QRect r = rect() - QMargins(20, 20, 20, 20); // ^^^ assumes the client area is big enough to shrink 40 pixels. Example only. const bool nearEdge = !r.contains(event->pos()); // ^^^ near any edge const bool nearEdgeL = nearEdge && (event->pos().x() < r.left()); const bool nearEdgeR = nearEdge && (event->pos().x() > r.right()); const bool nearEdgeT = nearEdge && (event->pos().y() < r.top()); const bool nearEdgeB = nearEdge && (event->pos().y() > r.bottom()); // ^^^ More than one of these can true at the same time in corners qDebug() << nearEdge << nearEdgeL << nearEdgeR << nearEdgeT << nearEdgeB; QWidget::mouseMoveEvent(event); }
-
This is one way:
void mouseMoveEvent(QMouseEvent *event) { QRect r = rect() - QMargins(20, 20, 20, 20); // ^^^ assumes the client area is big enough to shrink 40 pixels. Example only. const bool nearEdge = !r.contains(event->pos()); // ^^^ near any edge const bool nearEdgeL = nearEdge && (event->pos().x() < r.left()); const bool nearEdgeR = nearEdge && (event->pos().x() > r.right()); const bool nearEdgeT = nearEdge && (event->pos().y() < r.top()); const bool nearEdgeB = nearEdge && (event->pos().y() > r.bottom()); // ^^^ More than one of these can true at the same time in corners qDebug() << nearEdge << nearEdgeL << nearEdgeR << nearEdgeT << nearEdgeB; QWidget::mouseMoveEvent(event); }
-