c++ - 通过QGraphicsScene中鼠标位置获取QGraphicsItem

标签 c++ qt qgraphicsscene qgraphicsitem

我正在尝试通过直线连接两个QGraphicsItems(QGraphicsLineItem);通过在第一个对象上单击鼠标中键,然后将鼠标悬停在第二个对象上,释放它后,它应该在它们之间画线。

这是应该连接这些项目的函数。

void GraphicsBlock::connectBlocks(GraphicsBlock *block)
{
    GraphicsConnect *connection = new GraphicsConnect(); //Class with QGraphicsLineItem
    connection->line->setLine(QLineF(this->pos(), block->pos()));
}

我正在处理一个场景,但在通过鼠标位置查找第二个 block 时遇到问题。函数 mousePressEvent 应该使用以下代码:

if(event->button() == Qt::MiddleButton)
    Connecting == true;

然后是mouseReleaseEvent

if(Connecting)
{
    //Get object by mouse position here
    //this.connectBlocks(..)
    Connecting = false;
}

我尝试了scene->itemsAt(mouse.x(), mouse.y(), QTransform())

scene->items(QPointF(mouse.x(),mouse.y()) 但它总是返回空列表

编辑: 这就是应用程序应该如何工作,蓝色椭圆被单击端口,现在我应该拖动(仍然按下鼠标)到另一个端口并释放鼠标。

Application image

最佳答案

我解决了这个问题

QGraphicsItem *item = scene.itemAt(mapToScene(event->pos()), QTransform());

在函数mouseReleaseEvent

关于c++ - 通过QGraphicsScene中鼠标位置获取QGraphicsItem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50134082/

相关文章:

android - Qt 小部件和安卓 : Can't find some widgets/style not fitting

qt - 从场景中删除QGraphicsProxyWidget后崩溃

c++ - 混合 C 和 C++ 文件操作

c++ - g++ 32 位与 64 位编译中的动态与静态链接差异

c++ - 递归快速排序导致段错误(不是溢出)

qt - 有没有办法将 Qt 的源代码构建复制到另一个位置?

c++ - 如何在不复制 QGraphicsScene 的情况下显示 QImage

qt - QGraphicsView/QGraphicsScene 大小匹配

c++ - vector<string> x; 之间的区别和 vector<string> x(const string& s) {}

c++ - 在 C++ 中将一个 vector 转换为另一个具有不同大小的 vector