如何在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坐标满足这个条件,我们就更新矩形的位置。

相关推荐
IT 小阿姨(数据库)2 分钟前
PostgreSQL通过pg_basebackup物理备份搭建流复制备库(Streaming Replication Standby)
运维·服务器·数据库·sql·postgresql·centos
-森屿安年-7 分钟前
C++ 类与对象
开发语言·c++
ajassi200015 分钟前
开源 C++ QT QML 开发(八)自定义控件--圆环
c++·qt·开源
小蒜学长30 分钟前
springboot基于javaweb的小零食销售系统的设计与实现(代码+数据库+LW)
java·开发语言·数据库·spring boot·后端
会开花的二叉树1 小时前
c语言贪吃蛇游戏开发
c语言·开发语言
云边有个稻草人1 小时前
从内核调优到集群部署:基于Linux环境下KingbaseES数据库安装指南
linux·数据库·金仓数据库管理系统
韩立学长1 小时前
【开题答辩实录分享】以《C#大型超市商品上架调配管理系统的设计与实现》为例进行答辩实录分享
开发语言·c#
EnCi Zheng1 小时前
JPA 连接 PostgreSQL 数据库完全指南
java·数据库·spring boot·后端·postgresql
Raymond运维1 小时前
MySQL包安装 -- RHEL系列(Yum资源库安装MySQL)
linux·数据库·mysql
tao3556672 小时前
【Python刷力扣hot100】49. Group Anagrams
开发语言·python·leetcode