1
votes

I have QVector<QPoint> m_vertices; in my drawingwidget.h

class DrawingWidget: public QWidget {
    Q_OBJECT
    public:
        DrawingWidget(MainWindow *parent = 0);
        ~DrawingWidget();
        QVector<QPoint> m_vertices;

I trying to implement adding/deleting vertices on my mainwindow. I managed to make the add function, now it's should be easy to delete them, but i am a bit confused.

The main idea is, that i have a pop-up menu, where i can choose a "tool". I can add vertex, remove vertex, move vertex, add line, delete line. The idea is , when i choose for example "Add Vertex" then the "m_state" will change to "ADD_VERTEX_SELECTED" so i can only add vertices and nothing else.

enum DrawingWidgetState {
    NO_TOOL_SELECTED,
    ADD_VERTEX_SELECTED,
    MOVE_VERTEX_SELECTED,
    DELETE_VERTEX_SELECTED,
    ADD_LINE_SELECTED,
    DELETE_LINE_SELECTED
};

Drawing

void DrawingWidget::paintEvent(QPaintEvent *event) {
    QPainter painter(this);
    painter.fillRect(event->rect(), Qt::blue);
    painter.setBrush(Qt::black);
    for(int i = 0; i < m_vertices.size() ; i++) {
        painter.drawEllipse(m_vertices[i], 20, 20);
    }

MousePress event. On left click, I have to delete the vertex that I clicked on

void DrawingWidget::mousePressEvent(QMouseEvent *event) {
    if(m_state == ADD_VERTEX_SELECTED) {
        if(event->button() == Qt::LeftButton) {
            //m_x = event->x();
            //m_y = event->y();
            //update();
            QPoint point = event->pos();
            m_vertices.append(point);
            update();
        }
    }
    if(m_state == DELETE_VERTEX_SELECTED) {
        if(event->button() == Qt::LeftButton) {
            m_vertices.clear();
            }
        }
    }

How can i do that ?

1
Find a vertex that is less than 20px from event->pos and remove it? - Botje
Yes, something like that - Ximaks

1 Answers

0
votes

This code uses std::find_if together with a lambda expression to find the closest point. You probably want to allow a bit more leeway than the exact circle radius, but that is up to you.

auto it = std::find_if(m_vertices.begin(), m_vertices.end(), [point = event->pos](QPoint v) {
   auto d = v - point;
   return QPoint::dotProduct(d, d) < 400; // dotProduct returns square of distance
});

if (it != m_vertices.end()) {
    m_vertices.erase(it);
}