程序主要由OneBox、BoxGroup和MyView三個類構成,分別實現了小正方形,方塊圖形和遊戲場景。
class OneBox:public QGraphicsObject
{
public:
OneBox(const QColor &color=Qt::red);
QRectF boundingRect() const;
void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget);
QPainterPath shape() const;
private:
QColor brushColor;
};
OneBox::OneBox(const QColor &color)
{
}
QRectF OneBox::boundingRect() const
{
qreal penWdith=1;
return QRectF(-10-penWdith/2,-10,-penWdith/2,
20+penWdith,20+penWdith);
}
void OneBox::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
//爲小方框使用貼圖
painter->drawPixmap(-10,-10,,20,20,QPixmap(":/myimage/5.jpg"));
painter->setBrush(brushColor);
QColor penColor=brushColor;
penColor.setAlpha(20);
painter->setPen(penColor);
painter->drawRect(-10,-10,20,20);
}
QPainterPath OneBox::shape() const
{
QPainterPath path;
path.addRect(-9.5,-9.5,19,19);
return path;
}
爲了使用碰撞檢測函數時不會將方塊組中兩個相鄰的小方塊檢測爲發生了碰撞,這裏將小方塊的形狀設置爲比實際大小小0.5像素。因爲檢測碰撞時是使用shape()返回形狀,所以它們不會被檢測發生碰撞。
函數詳解:
QRectF:
該類在一個平面定義一個矩形,使用浮點型的精度。
#include <QRect>
公共函數:
QRectF ( float x, float y, float width, float height )
qreal等同於double