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

相关推荐
weixin_5806140039 分钟前
如何提取SQL日期中的年份_使用YEAR或EXTRACT函数
jvm·数据库·python
2301_813599551 小时前
SQL生产环境规范_数据库使用最佳实践
jvm·数据库·python
a9511416421 小时前
Go 中通过 channel 传递切片时的数据竞争与深拷贝解决方案
jvm·数据库·python
Dxy12393102161 小时前
Python 使用正则表达式将多个空格替换为一个空格
开发语言·python·正则表达式
qq_189807031 小时前
如何修改RAC数据库名_NID工具在集群环境下的改名步骤
jvm·数据库·python
aXin_ya1 小时前
Redis 高级篇(最佳实践)
数据库·redis·缓存
zhangchaoxies1 小时前
如何检测SQL注入风险_利用模糊测试技术发现漏洞
jvm·数据库·python
zhangchaoxies2 小时前
CSS如何实现响应式弹性网格布局_配合media query修改flex-wrap属性
jvm·数据库·python
霖霖总总2 小时前
[Redis小技巧32]Redis分布式锁的至暗时刻:从原理演进到时钟跳跃的终极博弈
数据库·redis·分布式
故事和你912 小时前
洛谷-数据结构1-1-线性表1
开发语言·数据结构·c++·算法·leetcode·动态规划·图论