qtqgraphicsscenemousepress

Drawing line in QGraphicsScene with Qt


I have a problem with drawing lines. It works well when the mouse moves slowly, but when the mouse is moved faster, there are some gaps and I don't have any idea why. This is the code:

if(QEvent::MouseButtonPress&&event->buttons()==Qt::LeftButton){
QPointF pt=mapToScene(event->pos());
        band->setGeometry(0,0,0,0);
         band->hide();
        band->update();
         this->scene()->addLine(pt.x(),pt.y(),pt.x(),pt.y(),QPen(color, size));
    qDebug()<<event->pos();
}

Here is a screenshot:

enter image description here

Left is drawed slower, right faster.


Solution

  • So it is really interesting question. I do the same in my computer and get same issue. I don't read deeply your code, because it seems that you subclass QGraphicsView, but I subclass QGraphicsScene, but doesn't matter. I tell you main idea. I can offer you next:

    Draw it as is, but when user end drawing, you remove this and draw 1 very beautiful curve without this gaps. You should use mouseReleaseEvent:

    In mouseMoveEvent:

        QPoint pos = mouseEvent->scenePos().toPoint();//just get point
        pol.append(pos);//append to polygon
    //...draw lines or what you want
    

    In constructor:

    QPolygon pol;
    

    In mouseReleaseEvent you create QPainterPath, load to it polygon and draw normal line without gaps.

    void GraphicsScene::mouseReleaseEvent(QGraphicsSceneMouseEvent *mouseEvent)
    {
        QPainterPath myPath;
        myPath.addPolygon(pol);
        addPath(myPath,QPen(Qt::red,2));
        pol.clear();
    }
    

    Result:

    I moved very fast and get gaps(now my mouse button is pressed)

    enter image description here

    now I released my button and get normal curve

    enter image description here