我有一个棋盘,我想在鼠标释放时访问我的项目。我知道它的位置,我想从场景中删除它或找到它的颜色。我在文档中搜索但是没有找到任何有用的东西。我的项目继承自QGraphicsPixmapItem
。
我怎么能这样做?
这是我的.cpp文件
knight::knight()
{
boundingRect();
setFlag(ItemIsSelectable);
_target=new QGraphicsPixmapItem[8];
}
QRectF knight::boundingRect()
{
return QRectF (0,0,140,140);
}
void knight::target(QPointF location)
{
for (int i=0;i<8;i++)
{
pointarray[i].setX(5);//hamintori 5 gozashtam ;
}
qreal x ,y,xarray[4],yarray[4];
{
x=location.x();
y=location.y();
xarray[0]=x+280;
xarray[1]=x-280;
xarray[2]=x+140;
xarray[3]=x-140;
yarray[0]=y+280;
yarray[1]=y-280;
yarray[2]=y+140;
yarray[3]=y-140;
}
for (int i=0;i<4;i++)
{
if (xarray[i]>=980 && xarray[i]<0)
xarray[i]=5;
if (yarray[i]>=980 && xarray[i]<0)
yarray[i]=5;
}
if (xarray[0]!=5)
{
pointarray[0].setX(xarray[0]);
pointarray[1].setX(xarray[0]);
if (yarray[2]!=5)
pointarray[0].setY(yarray[2]);
if (yarray[3]!=5)
pointarray[1].setX(yarray[3]);
}
if (xarray[1]!=5)
{
pointarray[2].setX(xarray[1]);
pointarray[3].setX(xarray[1]);
if (yarray[2]!=5)
pointarray[2].setY(yarray[2]);
if (yarray[3]!=5)
pointarray[3].setX(yarray[3]);
}
if (xarray[2]!=5)
{
pointarray[4].setX(xarray[2]);
pointarray[5].setX(xarray[2]);
if (yarray[0]!=5)
pointarray[4].setY(yarray[0]);
if (yarray[1]!=5)
pointarray[5].setX(yarray[1]);
}
if (xarray[3]!=5)
{
pointarray[6].setX(xarray[3]);
pointarray[7].setX(xarray[3]);
if (yarray[0]!=5)
pointarray[6].setY(yarray[0]);
if (yarray[1]!=5)
pointarray[7].setX(yarray[1]);
}
board _board;
QPixmap imagetarget(":/images/target.png");
for (int i=0;i<8;i++)
{
if (pointarray[i].y()!=5)
{
(_target+i)->setPixmap(imagetarget);
(_target+i)->setPos(pointarray[i]);
(_target+i)->boundingRect();
// qDebug() <<pointarray[i];
(_target+i)->setParentItem(_board.boarditem);
this->scene()->addItem(_target+i);
}
}
}
void knight::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
location=event->scenePos();
location=locationset(location);
target(location);
QGraphicsPixmapItem::mousePressEvent(event);
}
void knight::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
int contain;
for (int i=0;i<8;i++)
{
this->scene()->removeItem(_target+i);
}
targetlocation=event->scenePos();
targetlocation=locationset(targetlocation);
for (int i=0;i<8;i++)
{
if (targetlocation==pointarray[i])
contain=1;
}
if (contain==1)
this->setPos(targetlocation);
else
this->setPos(location);
}
void knight::mouseMoveEvent(QGraphicsSceneMouseEvent *event)
{
this->setPos(event->scenePos());
}
QPointF knight::locationset(QPointF location)
{
int x,y;
x=location.x();
y=location.y();
x=x/140;
x=x*140;
y=y/140;
y=y*140;
location.setX(x);
location.setY(y);
return location;
}
对我的英语和代码感到抱歉......我刚开始学习C ++和Qt以及英语:)