I am currently having a problem for the right click event for QPushButton
in the minesweeper game. From what I understand, if I want to give the right click event for the QPushButton
, I have to do something like this:
In the Buttons Class
:
class Buttons : public QPushButton
{
Q_OBJECT
public:
Buttons(QWidget *parent = Q_NULLPTR);
signals:
void btnRightClicked();
private slots:
void mousePressEvent(QMouseEvent *e) {
if(e->button() == Qt::RightButton) {
emit btnRightClicked();
}
}
};
And then in the mainwindow.cpp
, create an object like this:
Buttons *mButtons = new Buttons(this);
And connect the btnRightClick signal
to a slot
in MainWindow Class
like this:
connect(mButtons, &Buttons::btnRightClicked, this, &MainWindow::onRightClicked);
This works, but since it's a minesweeper game, I am gonna need a lot of buttons. I wonder each time when I am gonna need a button that has the right click event, do I have to create a new object like above?
For example, if I am want 64 QPushButtons
, do I have to create 64 objects like this?
for(int i = 0; i < 8; i++) {
for(int j = 0; j < 8; j++) {
Buttons *mButton = new Buttons(mCentralWidget);
mGridLayout->addWidget(mButton, i * 8, j);
connect(mButton, &Buttons::btnRightClicked, this, &MainWindow::onRightClicked);
}
}
For me, creating so many objects may sound a little bit crazy. Is there a way to just create one object which contains many QPushButtons
that have the right click event?
Allow me to ask another question, which is even if I have to create so many objects, each time I click one of them, that object should be hidden or disappeared. I tried this:
connect(mButton, &Buttons::clicked, mButton, &Buttons::hide);
which is not working.
Hope I explain my question clear. So how do I solve those problems? Or is there any advice for handling the right click event in the minesweeper game?
Any advice will be appreciated, Thanks.