如何在Qt中使用除主窗口之外的其他classe键盘键?

时间:2014-05-12 14:59:19

标签: qt

我正在制作一个2048游戏实现,并希望使用w,a,s,d键盘键向上,向下,向左和向右移动数字矩阵,但我无法弄清楚如何调用键盘事件功能我的main.cpp。这是代码:

main.cpp中:

int main(int argc, char *argv[])
{
    QApplication game_2048(argc, argv);

    Matrix game = Matrix(4);

    srand (time(NULL));

    QWidget *window_main = new QWidget;
    window_main->setWindowTitle("2048 Game");
    QGridLayout *layout = new QGridLayout;
    window_main->setFixedSize(600,400);
    QPushButton ***polja = new QPushButton**[4];
    for(int i=0; i<4; i++)
    {
        polja[i] = new QPushButton*[4];
        for(int j=0; j<4; j++)
        {
            QString name = QString::number(game._matrix[i][j]);
            polja[i][j] = new QPushButton(window_main);
            polja[i][j]->setFixedHeight(100);
            polja[i][j]->setText(name);
            polja[i][j]->move(100 +100*i,100*j);
        }
    }

    window_main->setLayout(layout);

    window_main->show();

    return game_2048.exec();

和mainwindow.cpp:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}

MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::keyPressEvent(QKeyEvent *e)
{
    if(e->key() == Qt::Key_W)
        game->playUp();
    if(e->key() == Qt::Key_S)
        game->playDown();
    if(e->key() == Qt::Key_D)
        game->playRight();
    if(e->key() == Qt::Key_A)
        game->playLeft();

}

提前致谢。

1 个答案:

答案 0 :(得分:0)

您没有使用自己创建的MainWindow课程。请在main.cpp中尝试以下更改:

#include "MainWindow.h"

int main(int argc, char *argv[])
{
    ...
    // QWidget *window_main = new QWidget;
    MainWindow *window_main = new MainWindow;
    ...
}

keyPressEvent看起来没问题,但也许您希望将其他按键传递给原来的QMainWindow keyPressEvent实施:

void MainWindow::keyPressEvent(QKeyEvent *e)
{
    if(e->key() == Qt::Key_W)
        game->playUp();
    else if(e->key() == Qt::Key_S)
        game->playDown();
    else if(e->key() == Qt::Key_D)
        game->playRight();
    else if(e->key() == Qt::Key_A)
        game->playLeft();
    else
        QMainWindow::keyPressEvent( e );
}