程序主要由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