Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Catch mousePressEvent for the right mouse button in a QRadioButton



  • Hi :-)

    I'm trying to catch a right mouse click, or more precise, the mousePressEvent in a QRadioButton derived widget.

    Here's some minimal example code I tried:

    main.cpp:

    #include "MainWindow.h"
    #include <QApplication>
    
    int main(int argc, char* argv[])
    {
        QApplication app(argc, argv);
        MainWindow mainWindow;
        mainWindow.show();
        return app.exec();
    }
    

    RadioButton.h:

    #include <QRadioButton>
    
    class RadioButton : public QRadioButton
    {
        Q_OBJECT
    
    public:
        RadioButton(QWidget *parent = 0);
    
    protected:
        virtual void mousePressEvent(QMouseEvent *event) override;
    
    };
    

    RadioButton.cpp:

    #include "RadioButton.h"
    #include <QDebug>
    
    RadioButton::RadioButton(QWidget *parent) : QRadioButton(parent)
    {
        setContextMenuPolicy(Qt::PreventContextMenu);
    }
    
    void RadioButton::mousePressEvent(QMouseEvent *event)
    {
        qDebug() << "mousePressEvent";
        QRadioButton::mousePressEvent(event);
    }
    

    MainWindow.h:

    #include <QMainWindow>
    
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        MainWindow();
    
    };
    

    MainWindow.cpp:

    #include "MainWindow.h"
    #include "RadioButton.h"
    #include <QVBoxLayout>
    
    MainWindow::MainWindow()
    {
        QWidget *mainWidget = new QWidget;
        QVBoxLayout *layout = new QVBoxLayout(mainWidget);
        setCentralWidget(mainWidget);
    
        RadioButton *button1 = new RadioButton;
        layout->addWidget(button1);
    
        RadioButton *button2 = new RadioButton;
        layout->addWidget(button2);
    }
    

    I thought that setting setContextMenuPolicy(Qt::PreventContextMenu) would expose all mouse clicks to the widget, but it does not behave like expected:

    If a RadioButton is clicked by the left mouse button, mousePressEvent is called as soon as the button goes down, no matter if a click is performed or the button is just pushed, dragged and released somewhere else. Not so for the right button: mousePressEvent is only invoked for a real "click", if I press and release shortly after. If I only push the right mouse button, nothing happens. Same if I push it, wait a second (apparently too long for a click) and release it again (too late).

    Shouldn't the mousePressEvent always happen? What's wrong here? Thanks for all help!



  • This post is deleted!


  • This is actually caused by KDE's mouse gesture engine. The above problem occurs when the mouse gestures are turned on. After deactivating them, the problem is gone. Btw. this also fixes the problem described in https://bugreports.qt.io/browse/QTBUG-49294


Log in to reply