QGraphicsScene设置SceneRect

简要说明

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轴分别向右、向下递增,故设定图像在场景中的坐标,其实是设定图像左上角在场景中的坐标。

稍加整理方便大家参考,如有错误请指正,谢谢!

  • 17
    点赞
  • 44
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值