C++qt画roi矩形区域,周围八个点,能够增加删除选中移动缩放,代码
时间: 2023-03-20 16:01:10 浏览: 244
以下是一个使用Qt和C++画ROI矩形区域并实现选中、移动、缩放、删除等功能的示例代码。主要思路是通过鼠标事件和键盘事件来响应用户的操作,同时通过自定义的矩形类来管理ROI矩形的状态和操作。
```cpp
#include <QtWidgets>
// 自定义矩形类
class MyRect {
public:
MyRect(QRectF rect) : m_rect(rect), m_selected(false), m_moving(false), m_resizing(false) {}
QRectF rect() const { return m_rect; }
bool isSelected() const { return m_selected; }
void setSelected(bool selected) { m_selected = selected; }
bool isMoving() const { return m_moving; }
void setMoving(bool moving) { m_moving = moving; }
bool isResizing() const { return m_resizing; }
void setResizing(bool resizing) { m_resizing = resizing; }
void move(QPointF delta) { m_rect.translate(delta); }
void resize(QPointF delta) { m_rect.adjust(0, 0, delta.x(), delta.y()); }
private:
QRectF m_rect; // 矩形区域
bool m_selected; // 是否选中
bool m_moving; // 是否正在移动
bool m_resizing; // 是否正在缩放
};
// 自定义绘制区域类
class PaintArea : public QWidget {
public:
PaintArea(QWidget *parent = nullptr) : QWidget(parent), m_pen(Qt::blue), m_brush(Qt::transparent), m_mode(None) {}
void setPen(const QPen &pen) { m_pen = pen; }
void setBrush(const QBrush &brush) { m_brush = brush; }
void setRect(const QRectF &rect) { m_rect = MyRect(rect); }
QRectF rect() const { return m_rect.rect(); }
void clear() { m_rectangles.clear(); update(); }
protected:
void paintEvent(QPaintEvent *event) override {
QPainter painter(this);
painter.setPen(m_pen);
painter.setBrush(m_brush);
for (const MyRect &rect : m_rectangles) {
painter.drawRect(rect.rect());
if (rect.isSelected()) {
painter.setPen(Qt::red);
painter.setBrush(Qt::NoBrush);
painter.drawRect(rect.rect().adjusted(-5, -5, 5, 5));
painter.setPen(m_pen);
}
}
}
void mousePressEvent(QMouseEvent *event) override {
if (event->button() == Qt::LeftButton) {
// 选中或开始移动/缩放
for (MyRect &rect : m_rectangles) {
if (rect.rect().adjusted(-5, -5, 5, 5).contains(event->pos())) {
rect.setSelected(true);
if (event->pos().x() < rect.rect().left() + 5 || event->pos().x() > rect.rect().right() - 5 ||
event->pos().y() < rect.rect().top() + 5 || event->pos().y() > rect.rect().bottom() - 5) {
rect.setResizing(true);
} else {
rect.setMoving(true);
}
m_mode = Moving;
break;
}
}
if (m_mode == None) {
// 创建新的矩形区域
阅读全文