QGraphicsItem setPos不移动项目的位置

gpl*_*lus 0 qt qgraphicsitem

我所拥有的内容类似于以下内容:

int main(int argc, char **argv) {
  QApplication app(argc, argv);
  MainWindow appWindow;
  appWindow.show();
  return app.exec();
}
class MainWindow : public QMainWindow {
  ...
private:
  QGraphicsScene *mScene;
  QGraphicsView *mView;
  QGraphicsItem *mItem;
  QPushButton *mButton1, *mButton2;
};
MainWindow::MainWindow(...) {
  mScene = new QGraphicsScene(this);
  mScene->setItemIndexMethod(QGraphicsScene::NoIndex);
  mView = new QGraphicsView(mScene, this);
  mView->setAlignment(Qt::AlignLeft | Qt::AlignTop);
  mButton1 = new QPushButton("Create Item", this);
  QObject::connect(mButton1, SIGNAL(clicked()), ...);
  mButton2 = new QPushButton("Set Item Position");
  QObject::connect(mButton2, SIGNAL(clicked()), ...);
}
void MainWindow::button1Clicked() {
  mItem = new QGraphicsSimpleTextItem("Test Item");
  mItem->setPos(mItem->pos() + QPointF(7.0f, 7.0f));  // doesn't work
  mScene->addItem(mItem);

  // even when I move the setPos() call after QGraphicsScene::addItem,
  // the item still paints at the top-left corner (0.0f, 0.0f)
}
void MainWindow::button2Clicked() {
  mItem->setPos(mItem->pos() + QPointF(7.0f, 7.0f)); // works perfect
}
Run Code Online (Sandbox Code Playgroud)

我对Qt非常陌生,很可能误解了一个基本概念.谁能发现我在这里做错了什么?

Ste*_*Chu 5

来自QGraphicsViewdoc:

默认情况下,可视化区域在第一次显示视图时自动检测到(通过调用QGraphicsScene :: itemsBoundingRect()).

这意味着当首次显示视图时,它使用组合的项边界作为其边界.因此,当您首次添加项目时,无论项目的位置如何,它都将用作显示场景的左上角.因此,您的项目实际上已移动,但场景显示为偏移.所以它看起来像是(0,0).当你第二次移动时,它实际上已经移动了两次.

解决方案是seceneRect在显示之前将其设置为已知的rect.这将修复显示的区域.