QKeyEvent在我的应用程序不工作



我想编写一个响应我的键事件的复古蛇,下面是我的代码:

paint.h

#ifndef PAINT_H
#define PAINT_H
#include<QWidget>
#include<QPaintEvent>
#include<QKeyEvent>
#include<QTimer>
class paint:public QWidget
{
Q_OBJECT
public:
    paint(QWidget*parent=0);
    ~paint();
protected:
    void paintEvent(QPaintEvent* );
    void keypress(QKeyEvent* keyevent);
public slots:
    void autorun();
private:
    int snake[100][2];
    int length;
    QTimer *timer;
    int flag;
};
#endif

paint.cpp

#include"paint.h"
#include<QtGui>
paint::paint(QWidget*parent):QWidget(parent)
{
flag=1;
snake[0][0]=45;
snake[0][1]=45;
length=4;
timer=new QTimer;
timer->start(1000);
connect(timer,SIGNAL(timeout()),this,SLOT(autorun()));
}
paint::~paint(){}
void paint::paintEvent(QPaintEvent* )
{
QPainter p(this);
p.setWindow(0,0,810,810);
QRectF border(45-20,45-20,16*45+40,16*45+40);
QRectF inter(45,45,16*45,16*45);
p.setPen(Qt::NoPen);
p.setBrush(QBrush(Qt::darkMagenta,Qt::SolidPattern));
p.drawRect(border);
p.setBrush(QBrush(Qt::gray,Qt::SolidPattern));
p.drawRect(inter);//
p.setPen(Qt::NoPen);
for(int i=45;i<=17*45;i+=45)
{
    p.drawLine(45,i,17*45,i);
    p.drawLine(i,45,i,17*45);
}
p.setPen(QPen(Qt::darkGray,1,Qt::SolidLine,Qt::RoundCap,Qt::RoundJoin));
//  for(int i=0;i<length;++i)
{
    QRectF snakebody(snake[0][0],snake[0][1],45,45);
    p.setBrush(QBrush(Qt::red));
    p.drawRect(snakebody);
}
}
void paint::keypress(QKeyEvent* keyevent)
{
qDebug()<<"key"<<endl;
switch(keyevent->key())
{
    case Qt::Key_Up:
        snake[0][1]=45;
        break;
    case Qt::Key_Down:
        snake[0][1]=720;
        break;
    case Qt::Key_Left:
        snake[0][0]=45;
        break;
    case Qt::Key_Right:
        snake[0][1]=720;
        break;
    case Qt::Key_Q:
        qDebug()<<"Q"<<endl;
        break;
}
}
void paint::autorun()
{
snake[0][1]+=45;
if(snake[0][1]>720)
{
    snake[0][1]=45;
    snake[0][0]+=45;
    if(snake[0][0]>720)
    {
        snake[0][0]=45;
    }
}
update();
}

关注keypress()功能,我想知道该功能不连接任何东西,它可以工作吗?实际上它没有,但是我不知道如何激活它。我还需要做什么吗?

http://qt-project.org/doc/qt-4.8/qwidget.html#keyPressEvent。您需要重写keyPressEvent,而不是创建您自己的keyPress函数。

所以,改变

void keypress(QKeyEvent* keyevent);

void keyPressEvent(QKeyEvent* keyevent)

您还必须使用Qt::StrongFocus参数调用widget的setFocusPolicy函数。因此,widget通过选择和单击来接受焦点。

相关内容

  • 没有找到相关文章

最新更新