当前位置: 代码迷 >> QT开发 >> 关于自定义Item碰撞的判断有关问题
  详细解决方案

关于自定义Item碰撞的判断有关问题

热度:190   发布时间:2016-04-25 03:02:48.0
关于自定义Item碰撞的判断问题
我自定义了一个类Wall派生自QGraphicsItem,形状就是那个红色的半框

代码
头文件
#ifndef WALL_H_
#define WALL_H_
#include<QGraphicsItem>
#include<QPainterPath>
#include<QRectF>
#include<QPainter>
class Wall:public QGraphicsItem
{
 public:
  QPainterPath shape();
  QRectF boundingRect()const;
  void paint(QPainter*,const QStyleOptionGraphicsItem*,QWidget*);
};
#endif

然后是定义
#include"Wall.h"
QPainterPath Wall::shape()
{
  QPainterPath paths;  //路径为一个中空的方块
 // paths.addRect(0,0,100,10);
  paths.addRect(90,10,10,90);
  paths.addRect(0,10,10,90);
  paths.addRect(10,90,80,10);
  return paths;
}
QRectF Wall::boundingRect()const
{
  return QRectF(0,0,100,100);
}
void Wall::paint(QPainter* painter , const QStyleOptionGraphicsItem* , QWidget*)
{
  painter->fillPath(shape(),Qt::red);  //画出框框
}


然后我把这个Wall和另一个QGraphicsRectItem一起放到一个QGraphicsScen上,判断下碰撞的问题

#include"Wall.h"
#include<QApplication>
#include<QGraphicsScene>
#include<QGraphicsView>
#include<QGraphicsRectItem>
int main(int argc,char** argv)
{
  QApplication app(argc,argv);
  QGraphicsScene* scene = new QGraphicsScene(0,0,200,200);
  QGraphicsView* view = new QGraphicsView(scene);  //显示视图

  Wall* wall = new Wall;
  wall->setPos(50,50);  //设置wall坐标

  QGraphicsRectItem* rect = new QGraphicsRectItem(0,0,10,10);
  rect->setBrush(QBrush(Qt::black));
  rect->setPos(70,70);  //加入一个10X10的小黑框
 
  scene->addItem(rect);
  scene->addItem(wall);
 
  if(!wall->collidingItems().isEmpty())  //这里的判断问题
   view->setWindowTitle("collide");
  else view->setWindowTitle("OK");
  view->show();

 return app.exec();
}

主函数里2个Item位置(他们的QPainterPath)明明没有交集,但当我把rect放到这个wall的范围(QRectF)内,
collidingItems()就会检测出他们有碰撞


我想这2个明明QPainterPath没有交集,为什么会检测出有碰撞?
还有如果我把这个rect向上移动下,移动到wall最高点的上方,就检测出无碰撞?
------解决思路----------------------
问题的关键在于,检测是以你返回的rect为有效范围,估计你改成QRectF(0,0,0,0)就会成功。会不会导致其他问题未知哦。
QRectF Wall::boundingRect()const
{
  return QRectF(0,0,100,100);
}
  相关解决方案