Qt5筆記之QGraphicsScene QGraphicsView QGraphicsItem
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) 前兩種方法得到的效果相同,如下:
注意:
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);