【问题标题】:QT - mousePressEvent called 3 times when double-clickingQT - 双击时调用mousePressEvent 3次
【发布时间】:2014-07-12 05:47:18
【问题描述】:

我创建了一个类 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 的一些默认双击事件?

【问题讨论】:

    标签: c++ qt


    【解决方案1】:

    您的问题的原因是void QGraphicsItem::mouseDoubleClickEvent,默认情况下调用mousePressEvent()。为了解决这个问题,只需重载 mouseDoubleClickEvent( QGraphicsSceneMouseEvent * event ) 并将其留空。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-12
      • 1970-01-01
      • 1970-01-01
      • 2012-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多