要实现左键点击鼠标时图片跟着鼠标移动,可以通过以下步骤来实现:1. 在QGraphicsView的构造函数中设置鼠标跟踪属性,以便能够捕获鼠标事件。```cpp
QGraphicsView::QGraphicsView(QWidget *parent) : QGraphicsView(parent)
{setMouseTracking(true);
}
```2. 在QGraphicsView中重写鼠标按下、鼠标移动和鼠标释放事件的处理函数。```cpp
void QGraphicsView::mousePressEvent(QMouseEvent *event)
{if (event->button() == Qt::LeftButton) {// 获取点击位置QPointF pos = mapToScene(event->pos());// 判断是否点击到图片if (scene()->itemAt(pos, QTransform()) == imageItem) {// 记录鼠标起始位置lastMousePos = pos;// 设置鼠标移动跟踪setDragMode(QGraphicsView::ScrollHandDrag);}}QGraphicsView::mousePressEvent(event);
}void QGraphicsView::mouseMoveEvent(QMouseEvent *event)
{if (dragMode() == QGraphicsView::ScrollHandDrag) {// 获取鼠标位置QPointF pos = mapToScene(event->pos());// 计算鼠标移动距离QPointF delta = pos - lastMousePos;// 更新图片位置imageItem->setPos(imageItem->pos() + delta);// 更新鼠标位置lastMousePos = pos;}QGraphicsView::mouseMoveEvent(event);
}void QGraphicsView::mouseReleaseEvent(QMouseEvent *event)
{if (event->button() == Qt::LeftButton) {// 停止鼠标移动跟踪setDragMode(QGraphicsView::NoDrag);}QGraphicsView::mouseReleaseEvent(event);
}
```3. 创建一个QGraphicsScene,并将QPixmap添加到场景中。```cpp
QGraphicsScene *scene = new QGraphicsScene(this);
QPixmap pixmap("image.png");
QGraphicsPixmapItem *imageItem = scene->addPixmap(pixmap);
```4. 创建一个QGraphicsView,并将QGraphicsScene设置给它。```cpp
QGraphicsView *view = new QGraphicsView(this);
view->setScene(scene);
```通过以上步骤,就可以实现左键点击鼠标时图片跟着鼠标移动的功能。