如何找到更接近鼠标 x 或鼠标 y 坐标的 QGraphicsItem(在 QList 中)?

达文西

我试图让哪个项目更接近鼠标 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);
}
迪米特里·厄诺特

计算两点之间距离的最简单方法是使用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);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Javascript放大/缩小到鼠标的x / y坐标

Photoshop中鼠标位置的x和y坐标

如何在几个JTextField中显示鼠标的坐标?

如何获得Dygraph中鼠标光标的当前x和y位置

如何通过查看鼠标光标找到基于圆边的x,y坐标

从具有(x,y)坐标的列表中获取项目

如何增加显示的x和y坐标的位数?

如何在python中计算x,y坐标的质心

如何定义(x,y)坐标的2D数组

如何在Typescript Angular中获取鼠标移动上xy坐标的十进制值?

在网格(MATLAB)上找到最接近(x,y)坐标的点

如何使用opencv将两个鼠标坐标[[x0,y0),(x1,y1)]导出到python中的txt文件中

rbx.lua 如何在不点击的情况下找到鼠标的x,y,z(循环)

Mathematica:如何将x坐标的嵌套列表和y坐标的嵌套列表制作为(x,y)坐标的嵌套列表?

Elm如何制作自定义事件解码器以在鼠标滚轮移动时获得鼠标的x / y位置

Eclipse CDT插件-根据在编辑器中单击鼠标的X和Y位置获取AST元素

如何使用移相器找到鼠标位置x / y

如何在X,Y坐标上设置鼠标光标,单击鼠标左键并向左,向右,顶部,底部滚动

在不使用 Win API 的情况下在 Excel 中检测鼠标坐标的任何方法

用鼠标调整QGraphicsItem的大小

跟踪鼠标在QGraphicsItem上的位置

如何通过x,y值存储和访问具有x,y坐标的对象?

如何执行一拖(总部设在X,Y鼠标坐标),在Android上使用AccessibilityService?

JavaFX 如何使用鼠标光标从图表上的绘制点获取 (x, y) 坐标?

在鼠标的enter事件中如何触发鼠标中键?

我有15到30个坐标的列表。给定任何X,Y坐标,从前端侧查找列表上最接近的坐标的方法是什么?

如何获得在画布元素上单击鼠标的坐标?

如何获得单击鼠标的坐标(仅需要数学计算)

如何在相对定位的元素内获取鼠标的坐标?