Problem with selecting a specific shape on the canvas in the graphic redactor using Qt library

I am writing a graphic redactor program. In the program, there is only two shapes that i am able to draw: circle and rectangle. I am able to correctly select and drag rectangle, but for circle it is not the case. I am only able to select and drag circle if my mouse is located in the upper left corner of the circle and above.

I tried to found a logic mistake in the contains method, but did not succeed.
here is the code:

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <memory>
#include <QWidget>
#include <QApplication>
#include <QSizePolicy>
#include <QPainter>
#include <QMouseEvent>
#include <QObject>
#include <QBoxLayout>
#include <QColor>
#include <QPushButton>
class QShapeCanvas;
class shape {
public:
    virtual ~shape() = default;

    virtual void paint(QPainter& canvas) const = 0;

    [[nodiscard]] virtual bool contains(int x, int y) const = 0;

    void move(int dx, int dy) {
        m_x += dx;
        m_y += dy;
    }

    explicit operator std::string() const {
        std::ostringstream oss;
        to_string(oss);
        return oss.str();
    }

    void select() {
        is_selected = true;
    }

    void unselect() {
        is_selected = false;
    }
    [[nodiscard]] int get_x() const{
        return m_x;
    }
    [[nodiscard]] int get_y() const{
        return m_y;
    }
    void set_x(int x){
         m_x = x;
    }
    void set_y(int y){
         m_y = y;
    }

protected:
    int m_x, m_y;

    bool is_selected;

    shape(int x, int y):
        m_x{x},
        m_y{y},
        is_selected{false}{}


    virtual void to_string(std::ostringstream &oss) const = 0;

};

class rectangle : public shape {
public:
    rectangle(int x, int y, int width, int height): shape(x, y),
                                                    m_width{width}, m_height{height} { }

    void paint(QPainter& painter) const override {
        painter.setBrush(QColor(255, 0, 255));
        is_selected ? painter.setPen(QColor(255, 0, 0)) : painter.setPen(Qt::NoPen);
        painter.drawRect(m_x, m_y, m_width, m_height);
    }

    [[nodiscard]] bool contains(int x, int y) const override {
        return x >= m_x && x < (m_x + m_width) &&
               y >= m_y && y < (m_y + m_height);
    }

protected:
    void to_string(std::ostringstream &oss) const override {
        oss << "{ "name": "rectangle", "x": " << m_x << ", "y": " << m_y << ", "width": " << m_width << ", "height": " << m_height << " }";
    }

private:
    int m_width, m_height;
};

class circle : public shape {
public:
    circle(int x, int y, int radius): shape(x, y),
                                      m_radius{radius} { }

    void paint(QPainter& painter) const override {
        painter.setBrush(QColor(255, 255, 0));
        is_selected ? painter.setPen(QColor(255, 0, 0)) : painter.setPen(Qt::NoPen);
        painter.drawEllipse(m_x, m_y, 2*m_radius, 2*m_radius);
    }

    [[nodiscard]] bool contains(int x, int y) const override {
        int dx = x - m_x;
        int dy = y - m_y;
        return (dx * dx + dy * dy) <= (m_radius * m_radius);
    }

protected:
    void to_string(std::ostringstream &oss) const override {
        oss << "{ "name": "circle", "x": " << m_x << ", "y": " << m_y << ", "radius": " << m_radius << " }";
    }

private:
    const int m_radius;
};

class QShapeCanvas : public QWidget {
public:
    enum ShapesToDraw {
        CircleShape,
        RectangleShape,
        NoneShape
    };

    explicit QShapeCanvas(QWidget* parent = nullptr): QWidget(parent) {
        setMinimumSize(200,200);
        setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        setFocusPolicy(Qt::StrongFocus);
        next_shape_to_draw = NoneShape;
        selected_shape = nullptr;
        is_in_dragging_mode = false;
    }

    void addShape(const std::shared_ptr<shape>& new_shape) {
        shapes.push_back(new_shape);
    }

    void setNextShapeToDraw(ShapesToDraw to_draw) {
        next_shape_to_draw = to_draw;
    }

protected:
    void paintEvent(QPaintEvent *) override {
        QPainter painter;
        painter.begin(this);
        for(auto& shape : shapes) {
            shape->paint(painter);
        }
        painter.end();
    }

    void keyPressEvent(QKeyEvent *event) override {
        if (selected_shape && event->key() == Qt::Key_Delete) {
            selected_shape->unselect();
            for (auto it = shapes.begin(); it != shapes.end(); it++) {
                if ((*it) == selected_shape) {
                    shapes.erase(it);
                    selected_shape = nullptr;
                    break;
                }
            }
            update();
        }
    }

    void mousePressEvent(QMouseEvent *event) override {
        if (selected_shape) {
            selected_shape->unselect();
            selected_shape = nullptr;
        }

        if (event->button() == Qt::LeftButton) {
            if (next_shape_to_draw == RectangleShape) {
                addShape(std::make_shared<rectangle>(event->pos().x() - 25, event->pos().y() - 25, 50, 50));
            } else if (next_shape_to_draw == CircleShape) {
                addShape(std::make_shared<circle>(event->pos().x() - 50, event->pos().y() - 50, 50));
            }
            update();
        } else if (event->button() == Qt::RightButton) {
            for (auto it = shapes.rbegin(); it != shapes.rend(); it++) {
                if ((*it)->contains(event->pos().x(), event->pos().y())) {
                    selected_shape = *it;
                    (*it)->select();
                    is_in_dragging_mode = true;
                    previous_x = event->pos().x();
                    previous_y = event->pos().y();
                    break;
                }
            }
            update();
        }
    }

    void mouseMoveEvent(QMouseEvent *event) override{
        if(selected_shape){
           int dx = - previous_x + event->pos().x();
           int dy = - previous_y + event->pos().y();
           selected_shape->move(dx,dy);
            previous_x = event->pos().x();
            previous_y = event->pos().y();
           update();
        }
    }

private:
    std::vector<std::shared_ptr<shape>> shapes;
    ShapesToDraw next_shape_to_draw;
    std::shared_ptr<shape> selected_shape;
    bool is_in_dragging_mode = false;
    int previous_x, previous_y;
};

class QPaintWindow : public QWidget {
public:
    QPaintWindow() {
        auto* window = new QWidget;
        this->setWindowTitle("Problem #5");
        this->resize(500, 500);

        auto* canvas = new QShapeCanvas(this);
        canvas->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
        canvas->setFocusPolicy(Qt::StrongFocus);

        auto* toolbar = new QWidget;
        auto* circleButton   = new QPushButton("Circle", toolbar);
        circleButton->setStyleSheet("background-color: white;" "color: black;");
        auto* rectangleButton = new QPushButton("Rectangle", toolbar);
        rectangleButton->setStyleSheet("background-color: white;" "color: black;");

        QObject::connect(rectangleButton, &QPushButton::clicked, [canvas, rectangleButton, circleButton] {
            rectangleButton->setStyleSheet("background-color: red;" "color: white;");
            circleButton->setStyleSheet("background-color: white;" "color: black;");
            canvas->setNextShapeToDraw(QShapeCanvas::ShapesToDraw::RectangleShape);
        });

        QObject::connect(circleButton, &QPushButton::clicked, [canvas, circleButton, rectangleButton] {
            rectangleButton->setStyleSheet("background-color: white;" "color: black;");
            circleButton->setStyleSheet("background-color: red;" "color: white;");
            canvas->setNextShapeToDraw(QShapeCanvas::ShapesToDraw::CircleShape);
        });

        auto* button_layout = new QHBoxLayout(toolbar);
        button_layout->addWidget(circleButton);
        button_layout->addWidget(rectangleButton);

        auto* window_layout = new QVBoxLayout(this);
        window_layout->addWidget(canvas);
        window_layout->addWidget(toolbar);
    }
};

int main(int argc, char *argv[]) {
    QApplication app(argc, argv);

    QPaintWindow window;
    window.show();

    return QApplication::exec();
}

New contributor

ruslan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật