为什么 QGraphicsRectItem 对象停留在坐标 (0,0) 而不管明确提供的坐标?

Why does QGraphicsRectItem object stay at coordinate (0,0) regardless of the coordinates provided explicitly?

我是 Qt5 的新手,尝试了网上提供的所有解决方案,但大多数都是 2011 年的。我是不是遗漏了什么?它不情愿地停留在 (0,0)。

文件名:sll.cpp

    sll::sll(QWidget *parent) :
        QWidget(parent),
        ui(new Ui::sll)
    {
        ui->setupUi(this);
    
        scene = new QGraphicsScene(this);
        ui->graphicsView->setScene(scene);
        
        QBrush redbrush(Qt::red);
        QPen blackPen(Qt::black);
        blackPen.setWidth(6);
        
        rect = scene->addRect(500,500,100,50,blackPen,redbrush);
        rect->setPos(-100,-100);
    }

相关代码来自sll.h

private:
    Ui::sll *ui;


    //Graphics

    QGraphicsScene *scene;
    QGraphicsRectItem *rect;

};

输出:

原因

  1. QGraphicsView默认居中对齐场景

  2. 图形场景具有维度,例如1000x800 像素。 QGraphicsView::setSceneRectQGraphicsScene::setSceneRect 是等价的,设置这些维度。当其中一种方法未明确使用时,Qt 会根据内容的几何形状自动确定尺寸。这会导致您观察到不直观的视觉行为。

解决方案

添加

ui->graphicsView->setAlignment(Qt::AlignLeft | Qt::AlignTop);
ui->graphicsView->setSceneRect(-200, -200, 800, 800);

之后

ui->graphicsView->setScene(scene);

提示

为避免可能出现的意外情况,请不要使用矩形的xy来设置其位置,而是使用对应的QGraphicsItemsetPos方法。也就是说

const QRectF &rect(500, 500, 100, 50);
scene->addRect(rect, blackPen, redbrush);

rect = scene->addRect(0, 0, 100, 50, blackPen, redbrush);
rect->setPos(500, 500);

可能看起来他们在做同样的事情,但事实并非如此。使用第二个版本。