Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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++.

like image 286
GeneCode Avatar asked Jul 16 '26 06:07

GeneCode


1 Answers

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.

like image 164
eyllanesc Avatar answered Jul 17 '26 18:07

eyllanesc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!