Qt获取多边形(QGraphicsPolygonItem)或Qt图形组件与直线(QLineF)的交点
有时需要获取直线与各种图形的交点,包括多边形和各种Qt图形框。
例如上图中,要想使连接线始终在多边形的边上,且能指向多边形中心,那么我们就要获取连线AB与多边形的交点。
1.多边形(QGraphicsPolygonItem)与直线(QLineF)的交点
QPointF A;QPointF B;QLineF lineAB(A,B); //AB连线Q普通组件 m_CommentItem;qreal commentWidth = m_CommentItem->boundingRect().width();qreal commentHeight = m_CommentItem->boundingRect().height();QPointF intersectPoint;//四个边-四条线QLineF line1(0,0,commentWidth,0);QLineF line2(0,0,0,commentHeight);QLineF line3(commentWidth,0,commentWidth,commentHeight);QLineF line4(0,commentHeight,commentWidth,commentHeight);QList<QLineF> lineList;lineList.append(line1);lineList.append(line2);lineList.append(line3);lineList.append(line4);//遍历四条线foreach(QLineF oneline,lineList){QLineF::IntersectType intersectType =oneline.intersect(lineAB, &intersectPoint);if (intersectType == QLineF::BoundedIntersection)break;}//intersectPoint 即为交点
3.可参考例子:
Qt Examples and Demos -> Graphics View ->Diagram Scene