How to calculate number of mouse clicks in widget?



  • I have tried with a sample, but deterministic behavior is observed.

    widget::widget(QWidget *parent) : QWidget(parent)
    {
    m_numMouseClicks = 0;
    this->setFixedSize(600,400);
    m_vBlyt = new QVBoxLayout(this);
    m_lBtest = new QLabel("MOUSE CLICK TEST");
    m_pBgetClicks = new QPushButton("GetClicks");
    m_vBlyt->addWidget(m_lBtest);
    m_vBlyt->addWidget(m_pBgetClicks);
    connect(m_pBgetClicks,SIGNAL(clicked(bool)),this,SLOT(printNumofClicks()));
    }

    bool widget::eventFilter(QObject *watched, QEvent *event)
    {
    if(event->type() == QEvent::MouseButtonPress){
    m_numMouseClicks++;
    return false;
    }else{
    // standard event processing
    return QObject::eventFilter(watched, event);
    }
    }

    void widget::printNumofClicks()
    {
    qDebug()<<Q_FUNC_INFO<<"# num of clicks :"<<m_numMouseClicks<<endl;
    }

    int main(int argc, char *argv[])
    {
    QApplication a(argc, argv);
    widget *wobj = new widget;
    a.installEventFilter(wobj);
    wobj->show();

    return a.exec();
    

    }

    output: number of clicks are not in sync



  • Just reimplement this Method http://doc.qt.io/qt-4.8/qwidget.html#mousePressEvent

    And everytime count the click. Its a protected Method from QWidget.



  • @Fuel
    Thank you @Fuel MousePressEvent is working, but i have doubt, why eventFilter logic is giving different output? Can you explain ?



  • @Fuel
    I want to calculate number of mouse clicks in complete application, by using mousePressEvent it gives number of clicks only in widget. widget has Qpushbutton, on button click : mousePressEvent of widget is not called.



  • Dont know if there is a all in one Solution. Maybe you have to count every Event by itself. So you need to count the Events from pressing the QPushButton and shared it with your Application.



  • Hi,
    Thank you.
    Solved by @dheerendra
    bool widget::eventFilter(QObject *watched, QEvent *event)
    {
    if(event->type() == QEvent::MouseButtonPress){
    QMouseEvent mE = dynamic_cast<QMouseEvent>(event);
    if (m_timeStamp!=mE->timestamp()){
    m_timeStamp=mE->timestamp();
    m_numMouseClicks++;
    }
    qDebug() << " Object ="<< watched->objectName() << " Time =" << mE->timestamp() << endl;
    qDebug()<<Q_FUNC_INFO<<m_numMouseClicks<<"#class Name :"<<watched->metaObject()->className()<<endl;
    this->printNumofClicks();
    }
    return QObject::eventFilter(watched, event);
    }


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.