为什么 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;
};
输出:
原因
QGraphicsView
默认居中对齐场景
图形场景具有维度,例如1000x800
像素。 QGraphicsView::setSceneRect
或 QGraphicsScene::setSceneRect
是等价的,设置这些维度。当其中一种方法未明确使用时,Qt 会根据内容的几何形状自动确定尺寸。这会导致您观察到不直观的视觉行为。
解决方案
添加
ui->graphicsView->setAlignment(Qt::AlignLeft | Qt::AlignTop);
ui->graphicsView->setSceneRect(-200, -200, 800, 800);
之后
ui->graphicsView->setScene(scene);
提示
为避免可能出现的意外情况,请不要使用矩形的x
和y
来设置其位置,而是使用对应的QGraphicsItem
的setPos
方法。也就是说
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);
可能看起来他们在做同样的事情,但事实并非如此。使用第二个版本。
我是 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;
};
输出:
原因
QGraphicsView
默认居中对齐场景图形场景具有维度,例如
1000x800
像素。QGraphicsView::setSceneRect
或QGraphicsScene::setSceneRect
是等价的,设置这些维度。当其中一种方法未明确使用时,Qt 会根据内容的几何形状自动确定尺寸。这会导致您观察到不直观的视觉行为。
解决方案
添加
ui->graphicsView->setAlignment(Qt::AlignLeft | Qt::AlignTop);
ui->graphicsView->setSceneRect(-200, -200, 800, 800);
之后
ui->graphicsView->setScene(scene);
提示
为避免可能出现的意外情况,请不要使用矩形的x
和y
来设置其位置,而是使用对应的QGraphicsItem
的setPos
方法。也就是说
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);
可能看起来他们在做同样的事情,但事实并非如此。使用第二个版本。