在QGraphicsScene类中跟踪鼠标移动

时间:2011-10-14 18:40:39

标签: qt qgraphicsview qobject qgraphicsscene

我将QGraphicsScene子类化,并添加了方法mouseMoveEvent来处理鼠标移动事件。我在GraphicsView上创建了一个标尺,并使用标尺跟踪鼠标移动。在QGraphicsScene :: mousemoveEvent中,我将expliitely调用标尺小部件的mouseMoveEvent。目的是让标尺知道当前的鼠标位置。

现在,当我移动鼠标时,似乎没有调用QGraphicsScene :: mousemoveEvent。但是,如果我按住鼠标左键并按住按钮移动它,我可以使它工作。这不是我想看到的;每当我将鼠标放在视图上并移动鼠标时,我都会调用此方法。

有解决方法吗?

2 个答案:

答案 0 :(得分:12)

QGraphicsView文档中所述,视图负责将鼠标和键盘事件转换为场景事件并将其传播到场景中:

  

您可以使用鼠标和键盘与场景中的项目进行交互。 QGraphicsView将鼠标和键事件转换为场景事件(继承QGraphicsSceneEvent的事件),并将它们转发到可视化场景。

由于mouse move events仅在默认情况下按下按钮时出现,因此您需要在视图上setMouseTracking(true)首先生成移动事件,以便将它们转发到场景中。
或者,如果您不需要转换为场景坐标,则可以直接在视图中重新实现mouseMoveEvent,而不是在场景中重新实现。但在这种情况下,请确保在实现中调用基类QGraphicsView::mouseMoveEvent,以便为场景中的项正确生成悬停事件。

答案 1 :(得分:2)

我一直在问,并且在某些地方找到了一些有用的信息,测试写了这个:

tgs.cpp

#include <QtGui>
#include "tgs.h"
#define _alto  300
#define _ancho 700
#include <QGraphicsSceneMouseEvent>

TGs::TGs(QObject *parent)
    :QGraphicsScene(parent)
{ // Constructor of Scene
    this->over = false;
}

void TGs::drawBackground(QPainter *painter, const QRectF &rect)
{

#define adjy 30
#define adjx 30

    int j = 0;
    int alto = 0;

    QPen pen;
    pen.setWidth(1);
    pen.setBrush(Qt::lightGray);
    painter->setPen(pen);   

    painter->drawText(-225, 10, this->str);
    alto = _alto;  // 50 + 2

    for(int i = 0; i < alto; ++i)
    {
        j = i * adjy - 17;

        painter->drawLine(QPoint(-210, j), QPoint(_ancho, j));
    }

    for(int i = 0; i < 300; ++i)
    {
        j = i * adjx - 210;

        painter->drawLine(QPoint(j, 0), QPoint(j, _ancho * 2));
    }
}

void TGs::mouseMoveEvent(QGraphicsSceneMouseEvent *mouseEvent)
{
    QString string = QString("%1, %2")
               .arg(mouseEvent->scenePos().x())
              .arg(mouseEvent->scenePos().y()); // Update the cursor position text
    this->str = string;
    this->update();
}

void TGs::mousePressEvent(QGraphicsSceneMouseEvent *event)
{
    this->update();
}

void TGs::mouseReleaseEvent(QGraphicsSceneMouseEvent *event)
{
    this->update();
}

tgs.h

#ifndef TGS_H
#define TGS_H

#include <QObject>
#include <QGraphicsView>
#include <QGraphicsScene>
#include <QGraphicsTextItem>

QT_BEGIN_NAMESPACE

class QGraphicsSceneMouseEvent;
class QMenu;
class QPointF;
class QGraphicsLineItem;
class QFont;
class QGraphicsTextItem;
class QColor;

QT_END_NAMESPACE

class TGs : public QGraphicsScene
{
public:
    TGs(QObject *parent = 0);

public slots:
    void drawBackground(QPainter *painter, const QRectF &rect);
    void mouseMoveEvent(QGraphicsSceneMouseEvent * mouseEvent);
    void mousePressEvent(QGraphicsSceneMouseEvent *event);
    void mouseReleaseEvent(QGraphicsSceneMouseEvent *event);

    bool over;
    QString str;
    QGraphicsTextItem cursor;
};

#endif // TGS_H
相关问题