2017-04-10 135 views
0

我在注册右键单击我的自定义QGraphics项目时遇到问题。QT:在QGraphicsItem上检测左右鼠标按下事件

我的自定义类的头:

#ifndef TILE_SQUARE_H 
#define TILE_SQUARE_H 
#include <QPainter> 
#include <QGraphicsItem> 
#include <QtDebug> 
#include <QMouseEvent> 

class Tile_Square : public QGraphicsItem 
{ 
public: 
Tile_Square(); 

bool Pressed; 
int MovementCostValue; 

QRectF boundingRect() const; 
void paint(QPainter *painter,const QStyleOptionGraphicsItem *option, QWidget *widget); 


protected: 
    void mousePressEvent(QGraphicsSceneMouseEvent *event); 
    void contextMenuEvent(QGraphicsSceneContextMenuEvent *cevent); 


}; 
#endif // TILE_SQUARE_H 

这里是说类的实现:

#include "tile_square.h" 

Tile_Square::Tile_Square() 
{ 
    Pressed = false; 
    MovementCostValue = 1; 

} 

QRectF Tile_Square::boundingRect() const 
{ 
    return QRectF(0,0,10,10); 
} 

void Tile_Square::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget) 
{ 
    QRectF rec = boundingRect(); 
    QBrush brush(Qt::white); 

    painter->fillRect(rec,brush); 
    painter->drawRect(rec); 
} 

//Left click 
void Tile_Square::mousePressEvent(QGraphicsSceneMouseEvent *event) 
{ 
    QMouseEvent *mouseevent = static_cast<QMouseEvent *>(*event); 
    if(mouseevent->buttons() == Qt::LeftButton){ 
     MovementCostValue++; 
     qDebug() << "LEFT: Movement value is: " << MovementCostValue; 
    } 
    else if(mouseevent->buttons() == Qt::RightButton){ 
     MovementCostValue--; 
     qDebug() << "RIGHT: Movement value is: " << MovementCostValue; 
    } 
    update(); 
    QGraphicsItem::mousePressEvent(event); 


} 

我与一个graphicsview和graphicsscene一个对话框窗口绘制此。

我想在左键单击时增加该类的内部整数,并在右键单击时减小它的内部整数。问题是,mousepressevent注册事件,而不是按下哪个按钮。在我的代码中,你可以看到我试图将它转换为常规鼠标事件,但显然失败了。

老实说,我想写

event->buttons() == Qt::LeftButton 

但QGraphicsSceneMouseEvent *事件没有这样的一个。什么是问题?

我也尝试过使用contextmenuevent,它完美地工作并注册了正确的单击,但常规的mousepressevent也被注册了。

+0

为什么你不只是使用[QGraphicsSceneMouseEvent :: button](http://doc.qt.io/qt-5/qgraphicsscenemouseevent.html#button)? –

+0

你的意思是在mousepressevent里面实现它吗? – VikingPingvin

+0

不,我的意思是[QGraphicsSceneMouseEvent](http://doc.qt.io/qt-5/qgraphicsscenemouseevent.html)*具有*所需的功能,用于查找哪个按钮被按下等。检查链接中的文档。或者我误解了你的问题? –

回答

0

首先,你不能从QGraphicsSceneMouseEvent投到QMouseEventQGraphicsSceneMouseEvent不是来自QMouseEvent,所以这不是一个安全的演员。按钮方法可能实际上并没有调用正确的方法,因为该方法不好。其次,QGraphicsSceneMouseEvent::buttons确实存在,它做你想做的,但它是一个面具。你应该这样做:

#include <QGraphicsSceneMouseEvent> 

void Tile_Square::mousePressEvent (QGraphicsSceneMouseEvent *event) 
{ 
    if (event->buttons() & Qt::LeftButton) 
    { 
     // ... handle left click here 
    } 
    else if (event->buttons() & Qt::RightButton) 
    { 
     // ... handle right click here 
    } 
} 

即使没有这当作一个面具,我希望你直接比较容易,只要你不同时按下按钮的组合工作。不过,我还没有测试过这一点。

+0

这是我尝试的第一件事。然而event->不指向任何东西。我不能调用button()和buttons(),也不能调用任何应该在那里的东西。 – VikingPingvin

+0

如果'event'是一个空指针(就像你似乎建议的那样),那么在你的代码的其他地方就会出现* *错误。 –

+0

但我的代码是字面上这个。只有对话框中的场景和视图创建者是其他代码。 – VikingPingvin

相关问题