QGraphicsScene设置SceneRect

QGraphicsScene设置SceneRect简要说明QGraphicsScene场景区域,可在构造QGraphicsScene对象时设定,也可通过函数setSceneRect设定。QGraphicsScene场景区域中坐标原点的位置,会影响到图形项的坐标设定,进而影响图形项在场景中的显示位置。以将图片显示在中心位置为例,分两种情况说明。1、场景坐标原点在显示窗口左上角使用函数setSceneRect将场景区域的坐标原点设定在QGrap…

简要说明

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

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

今天的文章QGraphicsScene设置SceneRect分享到此就结束了,感谢您的阅读。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/6824.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注