我正在尝试让哪个项目更接近于鼠标coord.x或coord.y,我想是类似的东西,但是尝试了很多之后再也没有得到。我让鼠标坐标起作用了,这只是QList无法获得的部分。
void findcloser()
{
QList<QGraphicsItem *> allitems = items();
QList<QGraphicsItem *> alltypedos;
foreach(auto item, allitems) {
if(item->type() == chord::Type) {
alltypedos.append(item);
}
}
getcloser(alltypedos.begin(), alltypedos.end(), mouse.x);
getcloser(alltypedos.begin(), alltypedos.end(), mouse.y);
}
答案 0 :(得分:0)
计算两点之间距离的最简单方法是使用QLineF
类:
class GraphicsView: public QGraphicsView
{
Q_OBJECT
public:
GraphicsView(QWidget* parent=nullptr): QGraphicsView(parent){}
virtual void mousePressEvent(QMouseEvent* event) override
{
// Take the position of the mouse in the scene coords
QPointF const pos = mapToScene(event->pos());
for(QGraphicsItem* item : scene()->items())
{
// Take the position of the items center
QPointF itemPos = item->mapToScene(item->boundingRect().center());
QLineF const distance(pos, itemPos);
qDebug() << pos << itemPos << distance.length();
}
qDebug() << "---";
}
};
当项目与鼠标之间有距离时,它只是在寻找最小值:
virtual void mousePressEvent(QMouseEvent* event) override
{
QPointF const pos = mapToScene(event->pos());
QList<QGraphicsItem*> items = scene()->items();
auto closest = std::min_element(items.begin(), items.end(), [pos](const QGraphicsItem* left, const QGraphicsItem* right)
{
QPointF const leftPos = left->mapToScene(left->boundingRect().center());
QPointF const rightPos = right->mapToScene(right->boundingRect().center());
QLineF const distanceLeft(pos, leftPos);
QLineF const distanceRight(pos, rightPos);
return distanceLeft.length() < distanceRight.length();
});
QGraphicsRectItem* item = dynamic_cast<QGraphicsRectItem*>(*closest);
item->setBrush(Qt::red);
}