Qt5笔记之QGraphicsScene QGraphicsView QGraphicsItem

时间:2022-05-22 11:24:15

1. 三者之间的关系:

(1) QGraphicsScene是QGraphicsView中的场景:

使用QGraphicsView::setScene()将scene加入到view中;

(2) QGraphicsScene又是QGraphicsItem的容器:

使用QgraphicsScene::addItem()将item加入到scene中,或addRect()之类的添加图形函数,利用这些函数的返回值赋值给item即可达到相同效果;

 

2. Item加入Scene的两种方法(以向场景中添加一个可拖动的长方形为例):

(1) 使用QgraphicsScene::addItem()将item加入到scene中:

//Test.cpp
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsItem>
#include <QPen>
Test::Test(QWidget *parent)
: QWidget(parent)
{
QGraphicsView *pView = new QGraphicsView();
QGraphicsScene *pScene = new QGraphicsScene();
pScene->setSceneRect(0, 0, pView->width(), pView->height());
pView->setScene(pScene);
 
QGraphicsRectItem *rectItem = new QGraphicsRectItem(200, 100, 200, 200);
rectItem->setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable);
QPen pen = rectItem->pen();
pen.setWidth(2);
pen.setColor(QColor(111, 111, 111));
rectItem->setPen(pen);
rectItem->setBrush(QColor(111, 111, 111, 100));
pScene->addItem(rectItem);
 
QGridLayout *gridLayout = new QGridLayout(this);
gridLayout->addWidget(pView, 0, Qt::AlignCenter);
}


(2)使QgraphicsScene::addRect()将item加入到scene中:

//Test.cpp
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsItem>
#include <QPen>
Test::Test(QWidget *parent)
: QWidget(parent)
{
QGraphicsView *pView = new QGraphicsView();
QGraphicsScene *pScene = new QGraphicsScene();
pScene->setSceneRect(0, 0, pView->width(), pView->height());
pView->setScene(pScene);
 
QGraphicsRectItem *rectItem = pScene->addRect(QRectF(200, 100, 200, 200));
rectItem->setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable);
QPen pen = rectItem->pen();
pen.setWidth(2);
pen.setColor(QColor(111, 111, 111));
rectItem->setPen(pen);
rectItem->setBrush(QColor(111, 111, 111, 100));
 
QGridLayout *gridLayout = new QGridLayout(this);
gridLayout->addWidget(pView, 0, Qt::AlignCenter);
}


(3) 前两种方法得到的效果相同,如下:

Qt5笔记之QGraphicsScene QGraphicsView QGraphicsItem


注意:

1.QGraphicsItem::setFlags()方法要格外注意一下,之前new了一个QGraphicsTextItem,发现无法输入中文,就是因为调用setFlags()时没有把需要的flag都加进去,少加了一个支持其他国语言的flag,查文档可以看到关于setFlags的说明:

"Sets the item flags to flags. All flags in flags are enabled; all flags not inflags are disabled."

原来一旦调用就要把需要的flag都写进去,不然就disabled了。。
之前写的是:
setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable);
改成如下即可(ItemAcceptsInputMethod是支持不同语言的flag):
setFlags(QGraphicsItem::ItemIsSelectable | QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemIsFocusable | QGraphicsItem::ItemAcceptsInputMethod);