本項目的下載下傳位址:戳此通路
上文中我們将一個圖元封裝在場景中進而顯示在GraphicsView的容器中.這一個節我們繼續操作完成16張背景圖的布局.
首先說明一下坐标系統,圖元的顯示預設是中心的對角線位置,隻有當圖元的擺放位置超過場景大小時,坐标才會從左上角初始化位置.
添加第二個圖元操作(圖檔像素為91*91)
#include "myscene.h"
myScene::myScene(QObject *parent) : QGraphicsScene(parent)
{
this->item = new myitem;//開辟堆空間
this->item->setPos(0,0);//設定坐标位置
this->addItem(this->item);//将item添加進場景中
this->item2 = new myitem;
this->item2->setPos(91,0);//設定第二個坐标位置
this->addItem(this->item2);//将item2添加進場景中
}
此時
我們添加16張圖顯然要用到循環否則一個一個寫太蠢了 .首先我們為每個位置編号
當然二維數組可以構造,但是這裡我們用一維數組仍然可以構造二維矩陣
i | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
i/4 | 1 | 1 | 1 | 1 | 2 | 2 | 2 | 2 | 3 | 3 | 3 | 3 | |||
i%4 | 1 | 2 | 3 | 1 | 2 | 3 | 1 | 2 | 3 | 1 | 2 | 3 |
這是運作程式顯示:
for(int i = 0;i<16;i++)
{
this->item[i] = new myitem;
this->item[i]->setPos(i/4 * this->item[i]->boundingRect().width(),
i%4 *this->item[i]->boundingRect().height());
this->addItem(this->item[i]);
}
下一部分來寫随機産生地鼠的程式,敬請期待.