如何在Qt中创建左侧边线,可以向左侧拖拽的矩形

在Qt中,要创建一个左侧边线可以向左侧拖拽的矩形,你需要自定义一个QGraphicsRectItem的子类,并处理鼠标事件来实现拖拽功能。以下是一个简单的实现:

复制代码
#include <QApplication>  
#include <QGraphicsView>  
#include <QGraphicsScene>  
#include <QGraphicsRectItem>  
#include <QMouseEvent>  
  
class ResizableRectItem : public QGraphicsRectItem {  
public:  
    ResizableRectItem(const QRectF &rect, QGraphicsItem *parent = nullptr)  
        : QGraphicsRectItem(rect, parent),  
          dragging(false),  
          edgeSensitivity(5) {}  
  
protected:  
    void mousePressEvent(QGraphicsSceneMouseEvent *event) override {  
        if (event->button() == Qt::LeftButton) {  
            QRectF rect = this->rect();  
            QPointF pos = event->pos();  
  
            if (pos.x() <= rect.x() + edgeSensitivity) {  
                // Left edge  
                dragging = true;  
                dragStartPos = pos;  
            }  
        }  
    }  
  
    void mouseMoveEvent(QGraphicsSceneMouseEvent *event) override {  
        if (dragging) {  
            QPointF pos = event->pos();  
            qreal newX = pos.x();  
            if (newX < this->rect().x() + this->rect().width()) {  
                // Prevent the rectangle from becoming too small or negative width  
                this->setRect(QRectF(newX, this->rect().y(), this->rect().x() + this->rect().width() - newX, this->rect().height()));  
            }  
        }  
    }  
  
    void mouseReleaseEvent(QGraphicsSceneMouseEvent *event) override {  
        dragging = false;  
    }  
  
private:  
    bool dragging;  
    QPointF dragStartPos;  
    int edgeSensitivity;  
};  
  
int main(int argc, char *argv[]) {  
    QApplication app(argc, argv);  
    QGraphicsScene scene;  
    QGraphicsView view(&scene);  
  
    ResizableRectItem *rect = new ResizableRectItem(QRectF(50, 50, 200, 100));  
    scene.addItem(rect);  
  
    view.show();  
    return app.exec();  
}

在这个例子中,ResizableRectItem类重写了mousePressEventmouseMoveEventmouseReleaseEvent方法。当用户点击矩形的左侧边线时,mousePressEvent会设置拖拽状态,并记录拖拽开始的位置。当用户移动鼠标时,mouseMoveEvent会根据鼠标的新位置更新矩形的位置,实际上是改变矩形的x坐标,同时保持宽度不变(或者你可以根据需要调整宽度)。最后,当用户释放鼠标按钮时,mouseReleaseEvent会结束拖拽状态。

注意,在mouseMoveEvent中,我们检查新的x坐标是否小于矩形的当前x坐标加上宽度,这是为了防止矩形变得太小或宽度变为负数。如果新的x坐标满足这个条件,我们就更新矩形的位置。

相关推荐
小溪学编程20 分钟前
AQS 原理详解:从 CLH 队列到 ReentrantLock 的实现
java·开发语言
持敬chijing22 分钟前
Web前后端开发-JavaScript 入门教程
开发语言·前端·javascript
笃行35027 分钟前
SQLServer数据库迁移实录:十年老系统搬上 KingbaseES,T-SQL 基本没重写
数据库
2601_9669496533 分钟前
从轮询到策略消费:量化系统如何高效处理五档盘口数据
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
我命由我123451 小时前
人脸识别 - 去重时间窗口
java·开发语言·python·学习·java-ee·学习方法·python3.11
落魄大学生之流水线上谋生计1 小时前
Java并发核心机制详解:线程池、CAS、AQS、锁升级
java·开发语言·数据库
hahaha60161 小时前
HLS高层次综合设计技巧--数组
开发语言·嵌入式硬件·算法·fpga开发
佳児素花痴╮2 小时前
Qt速通2
开发语言·qt
Wang's Blog2 小时前
Java框架快速入门: Spring Security+OAuth2之邮件验证码发送(SMTP与API方式)
java·数据库·spring
“AI国潮设计-小江”2 小时前
【Python/SDXL实战】潮汕国潮IP视觉落地:普宁英歌舞猫IP & 创意甜品设计(附ComfyUI工作流与商业授权说明)
开发语言·人工智能·python·prompt·aigc