我在注册右键单击我的自定义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)*具有*所需的功能,用于查找哪个按钮被按下等。检查链接中的文档。或者我误解了你的问题? –