我在註冊右鍵單擊我的自定義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也被註冊了。
爲什麼你不只是使用[QGraphicsSceneMouseEvent :: button](http://doc.qt.io/qt-5/qgraphicsscenemouseevent.html#button)? –
你的意思是在mousepressevent裏面實現它嗎? – VikingPingvin
不,我的意思是[QGraphicsSceneMouseEvent](http://doc.qt.io/qt-5/qgraphicsscenemouseevent.html)*具有*所需的功能,用於查找哪個按鈕被按下等。檢查鏈接中的文檔。或者我誤解了你的問題? –