Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

How to Drawline remove before line for qt



  • I want to draw a line,use keyboard key_right move it,but it can't remove before line.How to remove before line,Thanks.


  • Lifetime Qt Champion

    @erichuanhuna How do you draw the line in the first place? Do you use paintEvent and draw on a widget?



  • @jsulm

    void MainWindow::on_pushButton_clicked()
    {
    mainimg=QImage(800,600,QImage::Format_ARGB32);
    QPainter painter(&mainimg);
    painter.drawRect(50,50,800,600);

    QRectF rectangle(getPointX(), getPointY(), getEllipseWidth(), getEllipseHeight());
    QPen pen_ellipse(Qt::black);
    
    pen_ellipse.setWidth(getEllipsePen());
    painter.begin(this);
    painter.setPen(pen_ellipse);
    painter.setBrush(Qt::cyan);
    //painter.drawEllipse(rectangle);
    painter.drawLine(getPointX(), getPointY(),getPointX()+100, getPointY()+100);
    
    painter.end();
    
    QPixmap mainmap=QPixmap::fromImage(mainimg);
    ui->label_Pic->setPixmap(mainmap);
    

    }

    void MainWindow::keyPressEvent(QKeyEvent *keyEvent)
    {
    QPainter painter(&mainimg);
    QPixmap mainmap=QPixmap::fromImage(mainimg);

    switch (keyEvent->key()) {
    case Qt::Key_Down:
        setPointY(getPointY() + getStep());
    
        QWidget::update();
        break;
    case Qt::Key_Up:
        setPointY(getPointY() - getStep());
        QWidget::update();
        break;
    case Qt::Key_Right:
        setPointX(getPointX() + getStep());
        //能不能擦除上一根线
        painter.drawLine(getPointX(), getPointY(),getPointX()+100, getPointY()+100);
        ui->label_Pic->setPixmap(mainmap);
        break;
    case Qt::Key_Left:
        setPointX(getPointX() - getStep());
        QWidget::update();
        break;
    default:
        break;
    }
    

    }


  • Lifetime Qt Champion

    @erichuanhuna So, you want to have that line over the image (mainimg)? Then you simply have to do this when you want to move the line: draw the image, draw the line with updated coordinates.


Log in to reply