Qt rightclick QPushButton

I use Qt Creator to create a gui for playing chess. How can I find out that QpushButton has right clicked? for the flag in the game. In other words, what signal is used for right-clicking?

+5
source share
3 answers

Create your own filter button in the mousePressEvent slot .

qrightclickbutton.h

#ifndef QRIGHTCLICKBUTTON_H
#define QRIGHTCLICKBUTTON_H

#include <QPushButton>
#include <QMouseEvent>

class QRightClickButton : public QPushButton
{
    Q_OBJECT

public:
    explicit QRightClickButton(QWidget *parent = 0);

private slots:
    void mousePressEvent(QMouseEvent *e);

signals:
    void rightClicked();

public slots:

};

#endif // QRIGHTCLICKBUTTON_H

qrightclickbutton.cpp

#include "qrightclickbutton.h"

QRightClickButton::QRightClickButton(QWidget *parent) :
    QPushButton(parent)
{
}

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

Now connect like this:

QRightClickButton *button = new QRightClickButton(this);
ui->gridLayout->addWidget(button);
connect(button, SIGNAL(rightClicked()), this, SLOT(onRightClicked()));

Create a slot in MainWindow.cpp.

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

It works for me!

+16
source

, QPushButton , . QPushButton , , , . rightClicked() , :

signals:
    void rightClicked();

protected:
    void mouseReleaseEvent(QMouseEvent *e) {
        if (e->button() == Qt::RightButton) emit rightClicked();
        else if (e->button() == Qt::LeftButton) emit clicked();
    }

... , , .

signals:
    void clicked(QMouseEvent *);

protected:
    void mouseReleaseEvent(QMouseEvent *e) {
        emit clicked(e);
    }

, clicked(QMouseEvent *), .

+5

, :

class CRightClickEnabler : public QObject
{
public:
    CRightClickEnabler(QAbstractButton * button): QObject(button), _button(button) {
        button->installEventFilter(this);
    };

protected:
    inline bool eventFilter(QObject *watched, QEvent *event) override {
        if (event->type() == QEvent::MouseButtonPress)
        {
            auto mouseEvent = (QMouseEvent*)event;
            if (mouseEvent->button() == Qt::RightButton)
                _button->click();
        }
        return false;
    }

private:
    QAbstractButton* _button;
};

:

connect(ui->pushButton, &QPushButton::clicked, [](){qDebug() << "Button clicked";});
new CRightClickEnabler(ui->pushButton);

From this moment, the signal clickedwill be triggered by clicking the right mouse button, as well as clicking the left mouse button. There is no need to delete this object - it uses it ui->pushButtonas the parent and Qt will be automatically deleted when the parent is destroyed.

Obviously, you can write two lines of code (literally) to announce a new signal here, and if you want to emit this signal when you right-click instead clicked.

+2
source

All Articles