欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > 如何在Qt中创建左侧边线,可以向左侧拖拽的矩形

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

2025/9/18 1:00:54 来源:https://blog.csdn.net/xie__jin__cheng/article/details/140438862  浏览:    关键词:如何在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坐标满足这个条件,我们就更新矩形的位置。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词