简要说明
QGraphicsScene场景区域,可在构造QGraphicsScene对象时设定,也可通过函数setSceneRect设定。QGraphicsScene场景区域中坐标原点的位置,会影响到图形项的坐标设定,进而影响图形项在场景中的显示位置。以将图片显示在中心位置为例,分两种情况说明。
1、场景坐标原点在显示窗口左上角
使用函数setSceneRect将场景区域的坐标原点设定在QGraphicsView显示窗口的左上角,区域为QGraphicsView整个显示窗口。代码如下:
#include "SceneRect.h"
#include <QGraphicsPixmapItem>
SceneRect::SceneRect(QWidget *parent): QMainWindow(parent), m_pMyScene(NULL), m_pPixmapItem(NULL)
{ui.setupUi(this);ui.graphicsView->setStyleSheet("QGraphicsView{background-color: rgb(80, 80, 80);}");m_pMyScene = new QGraphicsScene(ui.graphicsView);ui.graphicsView->setScene(m_pMyScene);connect(ui.pushButton, SIGNAL(clicked()), this, SLOT(loadPixmap()));
}SceneRect::~SceneRect()
{if (m_pPixmapItem){delete m_pPixmapItem;m_pPixmapItem = NULL;}if (m_pMyScene){delete m_pMyScene;m_pMyScene = NULL;}
}void SceneRect::loadPixmap()
{QRect viewRect = ui.graphicsView->geometry();m_pPixmapItem = new QGraphicsPixmapItem(QPixmap("picture.bmp"));m_pMyScene->setSceneRect(1, 1, viewRect.width() - 2, viewRect.height() - 2); //将坐标原点设在显示窗口的左上角m_pMyScene->addRect(1, 1, viewRect.width() - 4, viewRect.height() - 4, QPen(Qt::red)); //红色方框标明场景区域m_pPixmapItem->setPos((viewRect.width() - m_pPixmapItem->pixmap().width()) / 2,(viewRect.height() - m_pPixmapItem->pixmap().height()) / 2); //设定图片在场景中的坐标m_pMyScene->addItem(m_pPixmapItem);
}
效果如下:

(0,0)为场景坐标原点
2、场景坐标原点在显示窗口中心点
使用函数setSceneRect将场景区域的坐标原点设定在QGraphicsView显示窗口的中心点,区域为QGraphicsView整个显示窗口。代码如下:
void SceneRect::loadPixmap()
{QRect viewRect = ui.graphicsView->geometry();m_pPixmapItem = new QGraphicsPixmapItem(QPixmap("picture.bmp"));m_pMyScene->setSceneRect(-viewRect.width() / 2, -viewRect.height() / 2, viewRect.width() - 2, viewRect.height() - 2); //将坐标原点设在显示窗口的中心点m_pMyScene->addRect(-viewRect.width() / 2, -viewRect.height() / 2, viewRect.width() - 4, viewRect.height() - 4, QPen(Qt::red)); //红色方框标明场景区域m_pPixmapItem->setPos(- m_pPixmapItem->pixmap().width()/ 2,- m_pPixmapItem->pixmap().height() / 2); //设定图片在场景中的坐标m_pMyScene->addItem(m_pPixmapItem);
}
效果如下:

图形项QGraphicsPixmapItem自身的坐标系是以图像左上角为坐标原点,x、y轴分别向右、向下递增,故设定图像在场景中的坐标,其实是设定图像左上角在场景中的坐标。
稍加整理方便大家参考,如有错误请指正,谢谢!


















