Qt中鼠标的双击事件和单击事件的实现方式

来源:互联网 发布:淘宝店铺模板有什么用 编辑:程序博客网 时间:2024/06/13 02:30

背景

同一个部件既要响应鼠标单击事件又要响应双击事件,而且两者响应的动作没有交集,跟不存在包含关系(如果双击事件动作包含单击事件的动作,那么只需要将双击事件特有的部分放到mouseDoubleClickEvent中去处理就好了)。问题点:两者响应的方式完全不同,举例:对一个QPushButton控件响应单击事件和双击事件,两个事件都会触发弹窗,两个不同的弹窗。

原理

Qt中,在双击事件mouseDoubleClickEvent中会触发单击事件mousePressEvent事件,原因是如下:
(1)、鼠标 按下->弹起 ,一个单击信号就发射了;
(2)、在单击后的一段(很短)的时间内,鼠标 按下->弹起,一个双击信号发射;

实现

  1. 方式一(思路见原文)
    使用单击事件的处理函数mousePressEvent和双击事件的处理函数mouseDoubleClickEvent,外加一个定时器来区分单击事件
#ifndef CBUTTON_H#define CBUTTON_H#include <QPushButton>#include <QTimer>class CButton : public QPushButton{    Q_OBJECTpublic:    explicit CButton(QWidget *pParent);private:    void mousePressEvent(QMouseEvent *e);    void mouseDoubleClickEvent(QMouseEvent *event);private slots:    void slotTimerTimeOut();    void mouseClicked();private:    QTimer m_cTimer;};#endif // CBUTTON_H
#include "cbutton.h"#include <QDebug>CButton::CButton(QWidget *pParent):QPushButton(pParent){    connect(&m_cTimer,SIGNAL(timeout()),this,SLOT(slotTimerTimeOut()));}void CButton::mousePressEvent(QMouseEvent *e){    qDebug()<<"CButton::mousePressEvent"<<endl;    m_cTimer.start(200);}void CButton::mouseDoubleClickEvent(QMouseEvent *event){    m_cTimer.stop();    qDebug()<<"CButton::mouseDoubleClickEvent"<<endl;}void CButton::slotTimerTimeOut(){    m_cTimer.stop();    mouseClicked();}void CButton::mouseClicked(){    qDebug()<<"CButton::mouseClicked"<<endl;}

2.方式二 (思路见原文)
 使用单击事件信号,增加一个变量和一个定时器来区分单击事件、双击事件

#ifndef CWINBUTTON_H#define CWINBUTTON_H#include <QPushButton>#include <QTimer>class CWinButton : public QPushButton{    Q_OBJECTpublic:    explicit CWinButton(QWidget *pParent=nullptr);private slots:    void slotTimerTimeOut();    void clicked();private:    int m_nClickTimes;    QTimer m_cTimer;};#endif // CWINBUTTON_H
#include "cwinbutton.h"#include <QDebug>CWinButton::CWinButton(QWidget *pParent):QPushButton(pParent){    m_nClickTimes =0;    connect(&m_cTimer,SIGNAL(timeout()),this,SLOT(slotTimerTimeOut()));    connect(this,SIGNAL(clicked(bool)),this,SLOT(clicked()));}void CWinButton::slotTimerTimeOut(){    qDebug()<<"CWinButton::slotTimerTimeOut"<<endl;    m_cTimer.stop();    if(1==m_nClickTimes){        qDebug()<<"click event"<<endl;        //TODO Click respond.    }else if(2==m_nClickTimes){        qDebug()<<"double click event"<<endl;        //TODO Double click respond.    }    m_nClickTimes=0;}void CWinButton::clicked(){    qDebug()<<"CWinButton::clicked"<<endl;    m_nClickTimes++;    m_cTimer.start(200);}

总结

方式一中双击事件触发的点击过程中,会引起单击事件,无法杜绝。方式二的实现清楚的区分开了两种事件。在两种事件响应互不关联的情况下,这种方式是最佳选择。

原创粉丝点击