【问题标题】:QGraphicsItem returns wrong position in scene. (Qt4.7.3)QGraphicsItem 在场景中返回错误的位置。 (Qt4.7.3)
【发布时间】:2013-08-26 18:52:32
【问题描述】:

我在 QGraphicsScene 中有一个 QGraphicsRectItem 项。 该项目可移动并且没有父项。 我从文件中放置项目读取位置并调用构造函数:

item = new QGraphicsRectItem (rect);

这行得通。职位符合预期。

然后我尝试通过使用

从项目中获取位置来将位置存储回文件
item->pos().toPoint()

位置错误 - 不是场景中的绝对位置。该位置相对于创建项目的最后位置。

pos() 是检索场景中项目位置的正确方法吗?

感谢您的任何提示!

附: scenePos() 返回相同的值

【问题讨论】:

    标签: qt4


    【解决方案1】:

    我也遇到了 QGraphicsRectItem 的问题。我目前的假设是这样的:

    您设置/获取的“矩形”与项目的“位置”相关,因此您可以使用其中一个(或者如果您想混淆)来控制实际绘制几何图形的位置.

    我的解决方案是这样的:

    // Given QRectF scene_rect that represents the rectangle I want drawn...
    setPos( scene_rect.topLeft() ); // Set the item's "position" relative to the scene
    scene_rect.moveTo( 0.0, 0.0 );  // ...then set the rectangle's location to (0,0)
    setRect( scene_rect );          // ...so the rectangle is drawn at (0,0) relative to the item
    

    【讨论】:

      【解决方案2】:

      我找到了您的问题,因为我正在网上搜索提示使用哪一个。

      我查看了 Qt 4.7.4 源代码:

      • QGraphicsRectItemPrivate 有一个成员 QRectF rect,您可以使用 rect() 获取并使用 setRect() 进行更改。
      • 但是,由于它是从QGraphicsItem 派生的,所以它也有一个QRectF pos
      • 函数boundingRect()返回rect按笔宽调整,表示要更新的区域一般是正确的。

      因此,正如 aldo 所说,您必须决定是使用 rect.topLeft 还是 pos 进行定位。
      为了帮助您和其他人做出决定,以下是一些优缺点:

      使用矩形的优点:

      • 您可以在一个函数调用中定义 QGraphicsRectItem 的位置和大小。
      • QGraphicsLineItem 的情况下,pos() 函数总是指向 boundingRect 的左上角,它不一定是线点之一,所以通过将 pos 留在 QPointF(0,0), QLine 点始终与场景相关。

      使用矩形的缺点:

      • 因为您不能使用 setPos(),所以没有发出 QGraphicsItem::ItemPositionChange 的函数。对我来说,这一点比优点更重要,只要您不使用 QGraphicsLineItem(如果我需要 QGraphicsLineItem,我可能会从中派生并自己发送 QGraphicsItem::ItemPositionChange)。

      如何以及何时使用两者:

      如果您同时使用 pos 和 rect,则让 pos 成为 GraphicsItem 的中心。
      想象一下图形场景中具有特定半径的标记、光标或类似物。如果您想为此使用QGraphicsRectItem,我建议:

      QPointF markerpos = GetMarkerPos();
      double r = GetMarkerRadius();
      QRectF markerrect(-r, -r, +r * 2., +r * 2.); // topleft: -radius, size: 2*radius
      setPos(markerpos);
      setRect(markerrect);
      

      这样,pos 始终指向中心,rect 仅由半径定义。

      【讨论】:

      • 谢谢您的解释
      • 非常全面的问题解释。 +1
      【解决方案3】:

      现在我找到了解决方法。如果是 Qt 的 bug 或者我对场景/视图的误解,请不要打结。

      现在我在位置 0,0 创建项目并使用 moveBy(x,y) 将它们移动到所需位置。

      item = new QGraphicsRectItem( QRect(QPoint(x,y),QSize(w,h)) );
      QPoint p = item->pos().toPoint(); //WRONG position! Relative to x,y
      
      item = new QGraphicsRectItem( QRect(QPoint(0,0),QSize(w,h)) );
      item->moveBy(x,y);
      QPoint p = item->pos().toPoint(); //Right position! Relative to 0,0 of scene
      

      有点奇怪。

      【讨论】:

        猜你喜欢
        • 2014-09-20
        • 1970-01-01
        • 2023-03-16
        • 2015-08-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多