使用QGraphicsView在很多折线中进行选择并不能正常工作

时间:2010-08-31 19:17:38

标签: c++ qt graphics

在Qt中,没有“QGraphicsPolylineItem”,所以我必须从QGraphicsItem实现它。 我重新实现'paint'和'boundingRect'函数。在'paint()'函数中,我只是简单地绘制折线中的所有直线。 没有任何用户的互动就可以了。 对于选择和可移动功能,我重新实现'QPainterPath * shape()'函数,如下所示:

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;
  }

但结果是错误的。当我点击折线时,它总是选择另一个。 然后我尝试自己实现选择,如下:

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.
        }
    }
}

这个解决方案看起来很合适,但并不准确。如果是这样的折线:

      ----------------------
     |
     |      o<-click here   |
     |                      |
     |  /\   /\             |
     | /  \ /  \ /-----------
      /    V    V

点击点远离绑定线,但仍然可以选择形状(这不是我想要的)。即使我将选择模式更改为Qt :: ContainsItemBoundingRect或Qt :: ContainsItemShape ..,结果仍然是错误的。 有没有简单的方法可以解决这个问题?或者,我必须计算从“点击点”到所有段的距离来决定它是否被选中?

谢谢!

1 个答案:

答案 0 :(得分:0)

调用setFlags(QGraphicsItem::ItemClipsToShape)有帮助吗?