我不知道類的setPos()功能是如何QGraphicsItem作業的。
我的Rect班級沒有父母,所以它的起源是相對于場景的。
在用滑鼠移動矩形后,我嘗試將矩形放回 (0, 0),但根據我移動它的位置,它被放置在不同的位置。我想這意味著場景的原點移動了,但是是什么導致了這種變化?
class Rect : public QGraphicsItem {
public:
Rect(): QGraphicsItem()
{
setFlag(ItemIsMovable);
}
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) override
{
painter->drawRect(0, 0, 20, 20);
}
void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override
{
setPos(0, 0);
update();
QGraphicsItem::mouseReleaseEvent(event);
}
QRectF boundingRect() const
{
return QRectF(0, 0, 20, 20);
}
private:
};
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsScene scene;
QGraphicsView view(&scene);
Rect obj;
scene.addItem(&obj);
view.show();
return a.exec();
}
uj5u.com熱心網友回復:
當您創建 QGraphicsView 時,您最初接受默認設定。例如,標準設定是水平居中。

另一個因素是默認區域大小可能達到最大大小。
您可以為場景設定自定義大小。你這樣做graphicsView->setSceneRect(0,0,300,300);(例如)
scene = new QGraphicsScene(this);
ui->graphicsView->setScene(scene);
ui->graphicsView->setRenderHint(QPainter::Antialiasing);
ui->graphicsView->setSceneRect(0,0, 300,300);
rectItem = new QGraphicsRectItem(0,0, 100, 100);
rectItem->setPen(QPen(Qt::darkMagenta, 2));
rectItem->setBrush(QGradient(QGradient::SaintPetersburg));
rectItem->setPos(190,10);
scene->addItem(rectItem);

總而言之:如果您想使用固定值。也許最好知道總大小。(從你的代碼中不清楚,這就是我給出這個例子的原因)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/509845.html
標籤:C qtqt5
