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

相关推荐
软件黑马王子8 分钟前
C#系统学习第八章——字符串
开发语言·学习·c#
阿蒙Amon10 分钟前
C#读写文件:多种方式详解
开发语言·数据库·c#
Da_秀18 分钟前
软件工程中耦合度
开发语言·后端·架构·软件工程
Fireworkitte24 分钟前
Java 中导出包含多个 Sheet 的 Excel 文件
java·开发语言·excel
坏柠29 分钟前
C++ Qt 基础教程:信号与槽机制详解及 QPushButton 实战
c++·qt
东窗西篱梦30 分钟前
Redis集群部署指南:高可用与分布式实践
数据库·redis·分布式
就是有点傻1 小时前
C#如何实现中英文快速切换
数据库·c#
雨落倾城夏未凉2 小时前
4.信号与槽
后端·qt
运器1232 小时前
【一起来学AI大模型】算法核心:数组/哈希表/树/排序/动态规划(LeetCode精练)
开发语言·人工智能·python·算法·ai·散列表·ai编程
1024小神2 小时前
hono框架绑定cloudflare的d1数据库操作步骤
数据库