我已经创建了一个类GraphicPoint,它继承了QObject和QGraphicsEllipseItem。
. h文件class GraphicPoint : public QObject, public QGraphicsEllipseItem
{
Q_OBJECT
public:
GraphicPoint(qreal x, qreal y, qreal width, qreal height, QWidget *parent = nullptr);
signals:
void clicked();
private:
void mousePressEvent(QGraphicsSceneMouseEvent *event);
};
. cpp文件GraphicPoint::GraphicPoint(qreal x, qreal y, qreal width, qreal height, QWidget *parent) :
QObject(parent),
QGraphicsEllipseItem(x, y, width, height, nullptr)
{
}
void GraphicPoint::mousePressEvent(QGraphicsSceneMouseEvent *event){
event->accept();
emit clicked();
}
在主窗口中,我创建了一个视图和一个场景,并将点添加到场景中。快速单击按钮两次调用mousePressEvent 3次,而稍微慢一点的操作只调用2次。下面是主窗口构造函数
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent)
{
n = 0;
view = new QGraphicsView(this);
scene = new QGraphicsScene(this);
view->setScene(scene);
testPoint = new GraphicPoint(0, 0, 10, 10, this);
connect(testPoint, &GraphicPoint::clicked, [this](){
n++;
qDebug()<<n;
});
scene->addItem(testPoint);
setCentralWidget(view);
}
快速点击2次后,QDebug输出3行数字1,2,3。
发生这种情况的原因是什么?是否有一些默认的双击事件调用额外的mousePressEvent?
你的问题的原因是无效的QGraphicsItem::mouseDoubleClickEvent,默认情况下调用mousePressEvent()
。为了解决这个问题,只需重载mouseDoubleClickEvent( QGraphicsSceneMouseEvent * event )
并将其保留为空。