3

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

1 回答 1

4

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

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到您的信号,然后将信号转发到您的ButtonsmainWindow

connect(&mButtons, &Buttons::btnRightClicked,
        this,      &MainWindow::onRightClicked);
于 2017-11-24T05:09:12.110 回答