如何从Qt中的qgraphicsscene点击获得确切的位置

时间:2014-03-12 02:11:42

标签: qt qgraphicsscene qpixmap mousepress

我正在编写代码以从文件加载图像并对此图像进行一些编辑(更改某些像素的值),放大或缩小然后保存图像。 此外,我想知道与qgraphicsscen上的点击相关联的原始图像中的位置。到目前为止,我找不到任何有用的功能。

我的加载图片代码:

qgraphicsscene = myqgraphicsview->getScene();
qgraphicsscene->setSceneRect(image->rect());
myqgraphicsview->setScene(qgraphicsscene);
qgraphicsscene->addPixmap(QPixmap::fromImage(*image)); // this is the original image

我的编辑代码:

mousePressEvent(QMouseEvent * e){
QPointF pt = mapToScene(e->pos());
scene->addEllipse(pt.x()-1, pt.y()-1, 2.0, 2.0,
QPen(), QBrush(Qt::SolidPattern));}

我想知道e-> pos()与原始图像中的确切位置之间的关系。

1 个答案:

答案 0 :(得分:3)

在GraphicsView中接收mousePressEvent意味着在MouseEvent上调用pos()将返回视图坐标空间中的一个点。

此时,您可以使用视图 mapToScene 功能将坐标转换为场景空间,然后使用场景的 itemAt 功能找到被选中的项目。

使用返回的项目,场景坐标可以映射到使用项目 mapFromScene 功能单击的项目的本地坐标。

所以,在GraphicsView中: -

mousePressEvent(QMouseEvent * e)
{
    // get scene coords from the view coord
    QPointF scenePt = mapToScene(e->pos());

    // get the item that was clicked on
    QGraphicsItem item* = qgraphicsscene->itemAt(pt, transform());

    // get the scene pos in the item's local coordinate space
    QPointF localPt = item->mapFromScene(scenePt);
}

对于带有图像的项目的本地位置,只需将其比例映射到原始图像。

虽然你可以这样做,但另一个选择是继承Qt类,它存储图像并在那里处理mousePressEvent。这应该为您提供项目本地空间中的坐标,而无需在场景中查找项目并自行转换坐标。

相关问题