效果如下:
我通过重写一个继承自QGraphicitem的类来实现上述功能,绘制重叠区域主要通过QPainterPath来实现,核心代码如下:
void myGraphicRectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
QPen mPen= QPen(Qt::yellow);
painter->setPen(mPen);
//绘制旋转后的矩形
painter->drawPolygon(m_oldRectPolygon);
//绘制旋转圆形
mPen.setWidth(2);
mPen.setColor(Qt::green);
painter->setPen(mPen);
QPointF pf = getSmallRotateRectCenter(m_oldRectPolygon[0],m_oldRectPolygon[1]);
QRectF rect = QRectF(pf.x()-10,pf.y()-10,20,20);
painter->drawEllipse(rect);//绘制圆形
painter->drawPoint(pf);//绘制点
//有重叠的情况
if(!this->scene()->collidingItems(this).isEmpty())
{
QPainterPath path,pathOthers;
QList<QGraphicsItem *> lstcolliItems = this->scene()->collidingItems(this);
int nColliNum = lstcolliItems.count();
for(int i = 0;i<nColliNum;i++)
{
QGraphicsItem* pTempItem = this->scene()->collidingItems(this)[i];
QPainterPath tempPath = pTempItem->shape();
tempPath.translate(pTempItem->pos());//转换到view中的坐标
pathOthers += tempPath;//记录与本item重叠的item的路径
}
path.addPolygon(m_oldRectPolygon);
path.translate(this->pos());//转换到view中的坐标
path &= pathOthers;//计算重叠部分的路径path
path.translate(-this->pos().x(),-this->pos().y());//转换回本Item中的坐标
QBrush brush(Qt::cyan);
mPen.setColor(Qt::blue);
painter->setPen(mPen);
painter->setBrush(brush);
painter->drawPath(path);//绘制重叠区域
}
}