c++qtqt5qt-signalsqt-slot

QWidget with doubleclick


I want to be able to double click a QPushbutton instead of a single click.

What I tried:

connect(pb, SIGNAL(doubleClicked()), this, SLOT(comBtnPressed()));

Error says "QObject::connect: No such signal QPushButton::doubleClicked()"

I chose QPushButton initially, but for my purpose, you can suggest change to other object if it can make a doubleclick event. Not necessarily be a push button.

Thank you Masters of Qt and C++.


Solution

  • A simple solution is to create our own widget so we overwrite the mouseDoubleClickEvent method, and you could overwrite paintEvent to draw the widget:

    #ifndef DOUBLECLICKEDWIDGET_H
    #define DOUBLECLICKEDWIDGET_H
    
    #include <QWidget>
    #include <QPainter>
    
    class DoubleClickedWidget : public QWidget
    {
        Q_OBJECT
    public:
        explicit DoubleClickedWidget(QWidget *parent = nullptr):QWidget(parent){
            setFixedSize(20, 20);
        }
    
    signals:
        void doubleClicked();
    protected:
        void mouseDoubleClickEvent(QMouseEvent *){
            emit doubleClicked();
        }
        void paintEvent(QPaintEvent *){
            QPainter painter(this);
            painter.fillRect(rect(), Qt::green);
        }
    };
    
    #endif // DOUBLECLICKEDWIDGET_H
    

    If you want to use it with Qt Designer you can promote as shown in the following link.

    and then connect:

    //new style
    connect(ui->widget, &DoubleClickedWidget::doubleClicked, this, &MainWindow::onDoubleClicked);
    //old style
    connect(ui->widget, SIGNAL(doubleClicked), this, SLOT(onDoubleClicked));
    

    In the following link there is an example.