QGraphicsItem移动事件-获取绝对位置

vla*_*sch 5 qt draggable qtgui

我有一个QGraphicsEllipseItem我想移动并在移动时触发信号的功能。所以我子类QGraphicsEllipseItemQObject并推翻了itemChange触发信号的方法。一切似乎都有效,但是报告的位置似乎与该项目的旧位置有关。即使询问项目的位置似乎也只能检索相对坐标。

这是一些代码来说明我做了什么:

class MyGraphicsEllipseItem: public QObject, public QGraphicsEllipseItem
{
  Q_OBJECT

public:

  MyGraphicsEllipseItem(qreal x, qreal y, qreal w, qreal h, QGraphicsItem *parent = 0, QGraphicsScene *scene = 0)
    :QGraphicsEllipseItem(x,y,w,h, parent, scene)
  {}

  QVariant itemChange(GraphicsItemChange change, const QVariant &value);

signals:
  void itemMoved(QPointF p);
};

QVariant MyGraphicsEllipseItem::itemChange( GraphicsItemChange change, const QVariant  &value )
{ 
  // value seems to contain position relative start of moving
  if (change == ItemPositionChange){
    emit itemMoved(value.toPointF());
  }
  return QGraphicsEllipseItem::itemChange(change, value); // i allso tried to call this before the emiting
}
Run Code Online (Sandbox Code Playgroud)

这是项目的创建:

  MyGraphicsEllipseItem* ellipse = new MyGraphicsEllipseItem(someX, someY, someW, someH);
  ellipse->setFlag(QGraphicsItem::ItemIsMovable, true);
  ellipse->setFlag(QGraphicsItem::ItemSendsScenePositionChanges, true);
  connect(ellipse, SIGNAL(itemMoved(QPointF)), SLOT(on_itemMoved(QPointF)));
  graphicsView->scene()->addItem(ellipse);
Run Code Online (Sandbox Code Playgroud)

和插槽:

void MainWindow::on_itemMoved( QPointF p)
{
  MyGraphicsEllipseItem* el = dynamic_cast<MyGraphicsEllipseItem*>(QObject::sender());
  QPointF newPos = el->scenePos();
  scaleLbl->setText(QString("(%1, %2) - (%3, %4)").arg(newPos.x()).arg(newPos.y()).arg(p.x()).arg(p.y()));
}
Run Code Online (Sandbox Code Playgroud)

奇怪的是,newpos并且p几乎相等,但是包含相对于运动开始的坐标。

如何获取被拖动对象的当前位置?还有另一种方法可以实现目标吗?

ric*_*eek 6

这不是错误,而是标准行为。

构造函数要求 QRectF 来确定椭圆的大小和原点。两个常用的尺寸是 (0,0,width,height)(原点在左上角)和(-0.5 * width, -0.5 * height, width, height)(原点在中心)。

使用setPos,该原点设置在所需位置。


vla*_*sch 2

我找到了原因:构造函数QGraphicsEllipseItem::QGraphicsEllipseItem ( qreal x, qreal y, qreal width, qreal height, QGraphicsItem * parent = 0 )没有按预期工作。在使用一些 x 和 y 调用它之后,该项目仍然报告 0,0 作为其位置。给构造函数 0,0 并显式设置位置可以setPos(x,y)解决问题。

我真的很想知道这就是这种行为的意图。该文档没有对此给出任何提示。