如何连接到mousePressEvent插槽Qt

时间:2017-11-24 03:16:07

标签: qt qmouseevent

Class Buttons中,我有一个btnRightClicked信号和一个mousePressEvent广告位:

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

mainwindow.cpp中,我将btnRightClicked信号连接到onRightClicked广告位,如下所示:

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

onRightClicked广告位是这样的:

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

但是我跑了这个程序,什么都没发生。我想原因是因为我没有连接到mousePressEvent插槽。我对Qt不熟悉,我不知道我是对的。

我在中央小部件上设置了一些按钮,我希望他们在右键单击每个按钮时都有正确的单击事件。那么我怎样才能做到这一点?

谢谢

编辑: 在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();
};

1 个答案:

答案 0 :(得分:3)

要让鼠标右键单击您的小部件,您需要实现自己的按钮小部件。

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);
}

在按钮类中,将按钮向量更改为

 QVector<MyButton*> buttons;

然后将MyButton的右键点击事件注册到Buttons课程中的信号,然后将信号发送到mainWindow

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