我试图以某种方式检测何时右键单击QPushButton。我确实有MacBook,我想知道这个post是否由 Md提出了解决方案。如果我使用触摸板强力触摸,Minhazul Haque 也应该适合我。我复制了他提供的代码(创建了额外的QRightClickButton类),但不幸的是它对我没用。
这是我的 connect()
connect(board->dis_board[i][j], SIGNAL(rightClicked()), this, SLOT(flag()));
board 是一个类对象
class Board
{
private:
int size;
int bombs;
int places;
public:
std::vector<std::vector<QPushButton*>> board;
std::vector<std::vector<QPushButton*>> dis_board;
explicit Board(int size, int bombs);
void move(int x, int y);
void flag(int,int);
};
Board 类对象的构造函数
Board::Board(int size, int bombs) : size(size), bombs(bombs), places(size*size)
{
board.resize(size);
dis_board.resize(size);
for (int i=0; i<size; ++i)
{
board[i].resize(size);
dis_board[i].resize(size);
for(int j=0; j<size; ++j)
{
board[i][j] = new QPushButton();
dis_board[i][j] = new QPushButton();
board[i][j]->setText(" ");
dis_board[i][j]->setText(" ");
}
}
QTime time = QTime::currentTime();
qsrand((uint)time.msec());
for (int i=0; i<bombs;)
{
int x = qrand() % ((size - 1 + 1) - 0) + 0;
int y = qrand() % ((size - 1 + 1) - 0) + 0;
if(board[x][y]->text() != "x")
{
board[x][y]->setText("x");
++i;
}
}
}
在这里你有一个实际窗口类的标题(我认为它是如何调用的,因为我是Qt的新手)
#ifndef GAME_H
#define GAME_H
#include <qrightclickbutton.h>
#include <QMainWindow>
#include <vector>
#include <QGridLayout>
#include "board.h"
#include <signal.h>
#include <QMouseEvent>
namespace Ui {
class Game;
}
class Game : public QMainWindow
{
Q_OBJECT
public:
explicit Game(QWidget *parent = 0, int x=0, int y=0);
~Game();
private slots:
void flag();
private:
Ui::Game *ui;
int size;
int bombs;
Board *board;
QGridLayout *grid;
};
#endif // GAME_H
我认为最重要的是窗口的构造函数
Game::Game(QWidget *parent, int size, int bombs) :
QMainWindow(parent),
ui(new Ui::Game),
size(size),
bombs(bombs)
{
ui->setupUi(this);
grid = new QGridLayout();
board = new Board(size, bombs);
ui->verticalLayout->addLayout(grid);
for(int i=0; i<size; ++i)
{
for(int j=0; j<size; ++j)
{
grid->addWidget(board->dis_board[i][j], i, j);
connect(board->dis_board[i][j], SIGNAL(rightClicked()), this, SLOT(flag()));
}
}
}
Game::~Game()
{
delete ui;
}
void Game::flag()
{
QMessageBox msg;
msg.setText("WARNGING");
msg.exec();
QPushButton *buttonSender = qobject_cast<QPushButton*>(sender());
for(unsigned long x=0; x<board->dis_board.size(); ++x)
{
for(unsigned long y=0; y<board->dis_board.size(); ++y)
{
if(board->dis_board[x][y] == buttonSender)
{
board->flag(x,y);
return;
}
}
}
}
同样点击()SIGNAL (左键)可以正常使用这些按钮。