How to connect to mousePressEvent slot Qt

别等时光非礼了梦想. 提交于 2019-12-06 00:45:50

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);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!