gpt4 book ai didi

qt - 如何通过单击Qt中的qgraphicsscene获取确切位置

转载 作者:行者123 更新时间:2023-12-04 00:38:16 25 4
gpt4 key购买 nike

我正在编写代码以从文件加载图像并对图像进行一些编辑(更改某些像素值)、放大或缩小,然后保存图像。另外,我想知道与单击 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() 和原图中确切位置的关系。

最佳答案

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

此时,您可以使用 View 的 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。这应该为您提供项目局部空间中的坐标,而无需在场景中查找项目并自行转换坐标。

关于qt - 如何通过单击Qt中的qgraphicsscene获取确切位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22340627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com