Search code examples
c++qtsignals-slotsqlistwidget

QListWidget itemClicked and itemDoubleClicked - block single click if double click


So far I have this code, which works fine:

QObject::connect(mListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(itemDoubleClicked(QListWidgetItem*)));
QObject::connect(mListWidget, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(itemClicked(QListWidgetItem*)));

The problem is that every time I double click on an item, the itemClicked slot gets executed.

Can I block the itemClicked slot if the user double clicks on an item? So just itemDoubleClicked gets executed?


Solution

  • Thanks to vahancho for the idea, to use a timer. Here is my solution:

    YourClass.h

    private:
        QListWidgetItem* mSingleClickedItem;
        bool mDoubleClicked;
    
    private slots:
        void itemClickedTimeout();
    

    YourClass.cpp

    void YourClass::itemClicked(QListWidgetItem* listWidgetItem) {
        if (!mDoubleClicked) {
            QTimer::singleShot(300, this, SLOT(itemClickedTimeout()));
            // use QApplication::doubleClickInterval() instead of 300
            mSingleClickedItem = listWidgetItem;
        }
    }
    
    void YourClass::itemClickedTimeout() {
        if (!mDoubleClicked) {
            // do something, listitem has been clicked once
        } else mDoubleClicked = false;
    }
    
    void YourClass::itemDoubleClicked(QListWidgetItem* listWidgetItem) {
        mDoubleClicked = true;
    
        // do something, listitem has been clicked twice
    }