【发布时间】:2018-04-12 18:42:42
【问题描述】:
我有两个QGraphicsPixmapItems,两者的边缘都是透明的,它们不是矩形的。当我尝试使用QGraphicsItem::collidingItems() 时,它只检查它们的边界矩形是否发生碰撞。有没有办法只检测不透明部分的碰撞?
【问题讨论】:
标签: c++ qt qt5 collision qpixmap
我有两个QGraphicsPixmapItems,两者的边缘都是透明的,它们不是矩形的。当我尝试使用QGraphicsItem::collidingItems() 时,它只检查它们的边界矩形是否发生碰撞。有没有办法只检测不透明部分的碰撞?
【问题讨论】:
标签: c++ qt qt5 collision qpixmap
您必须将形状模式设置为QGraphicsPixmapItem::HeuristicMaskShape:
QGraphicsPixmapItem::HeuristicMaskShape
形状是通过调用 QPixmap::createHeuristicMask() 来确定的。这 性能和内存消耗和 MaskShape 差不多
your_item->setShapeMode(QGraphicsPixmapItem::HeuristicMaskShape);
例子:
main.cpp
#include <QApplication>
#include <QGraphicsPixmapItem>
#include <QGraphicsView>
#include <QDebug>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QGraphicsView w;
QGraphicsScene *scene = new QGraphicsScene;
w.setScene(scene);
QList<QGraphicsPixmapItem *> items;
for(const QString & filename: {":/character.png", ":/owl.png"}){
QGraphicsPixmapItem *item = scene->addPixmap(QPixmap(filename));
item->setShapeMode(QGraphicsPixmapItem::HeuristicMaskShape);
item->setFlag(QGraphicsItem::ItemIsMovable, true);
item->setFlag(QGraphicsItem::ItemIsSelectable, true);
items<<item;
}
items[1]->setPos(50, 22);
if(items[0]->collidingItems().isEmpty())
qDebug()<<"there is no intersection";
w.show();
return a.exec();
}
输出:
there is no intersection
完整的例子可以看下面link
【讨论】:
model->setShapeMode(QGraphicsPixmapItem::HeuristicMaskShape);我将两者都设置为启发式地图。