2017-04-10 391 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