qt 中绘制多个 QGraphicsRectItem 不能相互重叠
时间: 2024-03-17 08:45:19 浏览: 35
在 Qt 中,可以通过设置 QGraphicsItem 的属性来实现不重叠。具体来说,可以设置 QGraphicsItem 的 flag 为 QGraphicsItem::ItemIsMovable 和 QGraphicsItem::ItemSendsGeometryChanges,然后重载 QGraphicsItem 的 itemChange() 函数,在该函数中判断是否与其他 QGraphicsItem 重叠,如果重叠则将该 QGraphicsItem 移回到原来的位置。代码示例如下:
```cpp
class MyItem : public QGraphicsRectItem
{
public:
MyItem(QGraphicsItem* parent = nullptr) : QGraphicsRectItem(parent)
{
setFlags(QGraphicsItem::ItemIsMovable | QGraphicsItem::ItemSendsGeometryChanges);
}
QVariant itemChange(GraphicsItemChange change, const QVariant& value) override
{
if (change == QGraphicsItem::ItemPositionChange && scene())
{
// 判断是否与其他 QGraphicsItem 重叠
QList<QGraphicsItem*> items = scene()->items(pos(), Qt::IntersectsItemShape, Qt::AscendingOrder);
for (QGraphicsItem* item : items)
{
if (item != this && collidesWithItem(item))
{
// 移回到原来的位置
return QGraphicsRectItem::itemChange(change, value);
}
}
}
return QGraphicsRectItem::itemChange(change, value);
}
};
```
使用时,创建多个 MyItem 对象并添加到 QGraphicsScene 中即可。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)