Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Click and longClick in the same button



  • Hello! I have a QPushButton which has three slots, clicked, pressed and released. This is my code:

    void MainWindow::on_button_clicked()
    {
        qDebug() << "Click pressed";
    }
    
    void MainWindow::on_button_pressed()
    {
        m_pTimer->start(2000);
    }
    
    void MainWindow::on_button_released()
    {
        m_pTimer->stop();
    }
    
    void MainWindow::longClick() {
        qDebug() << "Long click pressed";
    }
    

    Well, I want that, when the timer has a timeout (longClick()), ignore de click event. How can I do it? Thank you very much!



  • @ivanicy Hello,

    Here is a possible solution:

    //widget.h
    quint64 m_pressedTime = 0;
    
    //widget.cpp
    Widget::Widget(QWidget *parent) :
        QWidget(parent),
        ui(new Ui::Widget)
    {
        ui->setupUi(this);
    
        connect(ui->pushButton, &QPushButton::pressed, [&]{ m_pressedTime = QDateTime::currentMSecsSinceEpoch(); });
        connect(ui->pushButton, &QPushButton::released, this, &Widget::released);
    }
    
    void Widget::released()
    {
        quint64 now = QDateTime::currentMSecsSinceEpoch();
        if(now - m_pressedTime > 2000){
            qDebug() << "long clicked";
        } else {
            qDebug() << "clicked";
        }
        m_pressedTime = 0;
    }
    


  • @Gojir4 That works fine but, I need a small improve. I need that when this two seconds pass, do the action, not on the release event.

    Thank you for your time!



  • This post is deleted!


  • @ivanicy I knew I should have kept the timer...

    Updated using timer

    //widget.h
        QTimer m_longClickTimer;
    
    //widget.cpp
    Widget::Widget(QWidget *parent) :
        QWidget(parent),
        ui(new Ui::Widget)
    {
        ui->setupUi(this);
    
        m_longClickTimer.setSingleShot(true);
        connect(ui->pushButton, &QPushButton::pressed, [&]{ m_longClickTimer.start(2000); });
        connect(ui->pushButton, &QPushButton::released, this, &Widget::released);
        connect(&m_longClickTimer, &QTimer::timeout, this, &Widget::longClickTimeout);
    }
    void Widget::released()
    {
        if(m_longClickTimer.isActive()){
            qDebug() << "clicked";
            m_longClickTimer.stop();
        }
    }
    
    void Widget::longClickTimeout()
    {
        qDebug() << "long clicked";
    }
    


  • @ivanicy

    Start a single shot timer with a 2 sec timeout, every time the button was pressed. If timer fires at 2s and button still pressed, start your action, else reset the time (on release also reset your time).



  • @Gojir4 @Pl45m4 Thank you very much both of you!



  • @ivanicy Glad it helped. Please don't forget to set the post as solved !


Log in to reply