I have a set of vector points, with each click on my window I add pair to the vector. I want to add an invisible radius on my point which will help me to detect if a point was clicked. The point is basically 1 pixel in size so the user is not able to click on it directly. How can I achieve this? Do I need to use any math formulas for this?
std::vector<QPoint> pointSet;
void MyWindow::mousePressEvent(QMouseEvent *event)
{
if(event->button() == Qt::LeftButton)
{
x0 = event->x();
y0 = event->y();
QPoint data;
data.setX(x0);
data.setY(y0);
pointSet.push_back(data);
}
//I want to be able to do it like below
if(event->button() == Qt::RightButton)
{
//if(pointClicked) { cout << "point with x,y clicked"; }
}
update();
}
CodePudding user response:
If I understand your question correctly, you just need to run through your vector and check if any of the saved points are within a range of the clicked point. So something like this should work:
if (event->button() == Qt::RightButton)
{
int radius = <something>
QRectF range(event->x() - radius, event->y() - radius, radius * 2, radius * 2);
for (auto &p in pointSet)
{
if (range.contains(p))
{
cout << "point with" << p.x() << "," << p.y() << "clicked";
break;
}
}
}
CodePudding user response:
You can create an off-screen bitmap the size of your window. Whenever you add a point to your vector, you can draw a filled circle with a color equal, for example, to the index of that point in your vector. Then on any mouse click event, you can get a color of the clicked point and get to your vector element.