1.概要
关于QGraphicsScene的坐标
你添加一个 0,0 位置的矩形和添加一个100,100的矩形,你会发现,他们在同一QGraphicsView个位置。
问题的关键就是,本身QGraphicsScene的坐标是相对灵活的,他一版把QGraphicsView的0,0位置设置成他的第一个图形的0,0位置。所以你设置的0,0位置的图像,会和100,100位置的图像都出现在画面中的左上角
2.代码
#include <QApplication>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsRectItem>
void readPos(QGraphicsView* view,QGraphicsScene* scene,QGraphicsRectItem* rectItem)
{
qDebug()<<view->pos();
qDebug()<<rectItem->pos();
}
void test1_4(){
// 创建场景
QGraphicsScene* scene = new QGraphicsScene(0,0,201,201);
// 创建一个矩形区域
QRectF rect(0, 0, 100, 100);
// 在场景中添加一个矩形图形项,位置和大小由QRectF指定
QGraphicsRectItem* rectItem = scene->addRect(rect, QPen(Qt::black), QBrush(Qt::blue));
int a = rectItem->rect().left();
qDebug()<<a;
// 创建视图并将场景设置给视图
QGraphicsView* view = new QGraphicsView(scene);
view->setAlignment(Qt::AlignLeft|Qt::AlignTop);
view->setGeometry(0,0,201,201);
QPointF topLeftInScene = view->mapToScene(rectItem->rect().topLeft().toPoint());
qDebug()<<topLeftInScene.x();
//rectItem->setPos(200, 200);
readPos(view,scene,rectItem);
// 显示视图
view->show();
}
void test2_4(){
// 创建场景
//QGraphicsScene* scene = new QGraphicsScene(0,0,199,199);
QGraphicsScene* scene = new QGraphicsScene();
// 创建一个矩形区域
QRectF rect(100, 100, 100, 100);
// 在场景中添加一个矩形图形项,位置和大小由QRectF指定
QGraphicsRectItem* rectItem = scene->addRect(rect, QPen(Qt::black), QBrush(Qt::blue));
int a = rectItem->rect().left();
qDebug()<<a;
// 获取子控件相对于父控件的坐标
QPointF childPosition = rectItem->mapToParent(QPoint(0, 0));
qDebug() << "Child widget position relative to parent:" << childPosition;
// 创建视图并将场景设置给视图
QGraphicsView* view = new QGraphicsView(scene);
view->setAlignment(Qt::AlignLeft|Qt::AlignTop);
view->setGeometry(0,0,201,201);
QPointF topLeftInScene = view->mapToScene(rectItem->rect().topLeft().toPoint());
qDebug()<<topLeftInScene.x();
//rectItem->setPos(200, 200);
readPos(view,scene,rectItem);
// 显示视图
view->show();
}
int main(int argc, char* argv[]) {
QApplication app(argc, argv);
//test1();
//test2();
//test1_1();
//test2_1();
//test1_2();
//test2_2();
//test1_3();
//test2_3();
test1_4();
test2_4();
//test3();
//test4();
return app.exec();
}
3.运行结果
1.不指定坐标
// 创建场景
//QGraphicsScene* scene = new QGraphicsScene(0,0,199,199);
QGraphicsScene* scene = new QGraphicsScene();

2.指定坐标
// 创建场景
QGraphicsScene* scene = new QGraphicsScene(0,0,199,199);
//QGraphicsScene* scene = new QGraphicsScene();

6051

被折叠的 条评论
为什么被折叠?



