关于QGraphicsScene的坐标 重

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();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值