Qt – How to connect to mousePressEvent slot Qt

qmouseeventqt

In Class Buttons, I have a btnRightClicked signal and a mousePressEvent slot:

void Buttons::mousePressEvent(QMouseEvent *e)
{
    if(e->button() == Qt::RightButton) {
        emit btnRightClicked();
    }
}

And in mainwindow.cpp, I connect the btnRightClicked signal to onRightClicked slot like this:

connect(&mButtons, SIGNAL(btnRightClicked()), this, SLOT(onRightClicked()));

The onRightClicked slot is like this:

void MainWindow::onRightClicked()
{
    qDebug() << "right clicked";
}

But I ran this program, nothing happened. I guess the reason is because I did not connect to the mousePressEvent slot. I am kind of new to Qt, I do not know if I am right or not.

I set up some buttons on the central widget, I want them to have the right clicked event when right click each of them. So how can I make this work?

Thanks

Edit:
in button.h:

class Buttons : public QObject
{
    Q_OBJECT
public:
    Buttons();
    QVector<QPushButton*> buttons;

    void setButtons(int totalBtns) {
        for(int i = 0; i < totalBtns; i++) {
            buttons[i]->setObjectName(QString::number(i));
            buttons[i]->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
        }
    }

public slots:
    void mousePressEvent(QMouseEvent *e) {
        if(e->button() == Qt::RightButton) {
            emit btnRightClicked();
        }
    }

signals:
    void btnRightClicked();
};

Best Answer

To get the mouse right click on your widget, you need to implement your own button widget.

class MyButton : public QPushButton
{
 Q_OBJECT

public:
    MyButton(QWidget *parent = Q_NULLPTR);

private slots:
    void mousePressEvent(QMouseEvent *e);

signals:
    void btnRightClicked();
};

cpp

MyButton:MyButton(QWidget * parent) : 
    QPushButton(parent)
{
}
void MyButton::mousePressEvent(QMouseEvent *e)
{
    if(e->button()==Qt::RightButton)
        emit btnRightClicked();

    //this forwards the event to the QPushButton
    QPushButton::mousePressEvent(e);
}

In your buttons class change the button vector to

 QVector<MyButton*> buttons;

Then register the right click event of your MyButton to your signal in Buttons class then forwared the signal to your mainWindow

connect(&mButtons, &Buttons::btnRightClicked,
        this,      &MainWindow::onRightClicked);
Related Topic