In Qt, there is no "QGraphicsPolylineItem", so I have to implement it form QGraphicsItem. I reimplement 'paint' and 'boundingRect' functions.In 'paint()' function, I just simply draw all lines in the polyline. It's OK without any user's interaction. For selection and movable function, I reimplement the 'QPainterPath* shape()' function like this:
QPainterPath ContourLineShape::shape() const
{
QPainterPath path;
QPointF p0=this->poly.at(0)->at(0);
path.moveTo(p0.x(),p0.y());
foreach(QPointF p,poly)
path.lineTo(p.x(),p.y());
return path;
}
but the result is wrong. when i click on a polyline ,it always selects another. Then I try to implement the selection myself, like this:
void GraphicsView::mousePressEvent ( QMouseEvent * event )
{
int x=event->pos().x();
int y=event->pos().y();
QList<QGraphicsItem *>items=this->items(x-5,y-5,10,10,Qt::IntersectsItemShape);
for(int i=items.size()-1;i>=0;i--)
{
QGraphicsItem *item=items.at(i);
if(item->type()==QGraphicsItem::UserType+4)//UserType+4 is my polyline type.
{
item->setSelected(true);
return; //one shape has been selected.
}
}
}
This solution looks like right, but it's not exact. If a polyline like this:
----------------------
|
| o<-click here |
| |
| /\ /\ |
| / \ / \ /-----------
/ V V
The click point is far from the bound lines ,but the shape still can be selected(it's not what I wanted). Even if I changed the selection mode to Qt::ContainsItemBoundingRect or Qt::ContainsItemShape.., the result is still wrong. Is there any easy way to solve this problem?Or,must I calculate the distances from 'click point' to all the segments to decide if it's selected?
Thanks!