我的应用程序中的QKeyEvent不起作用

时间:2013-03-26 06:38:37

标签: c++ linux qt connect qkeyevent

我想编写一个响应我的keyevents的复古snaker,这是我的代码:

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()函数,我想这个函数没有连接任何东西,它可以工作吗?实际上它没有,但我不知道如何激活它。我还需要做其他事吗?

2 个答案:

答案 0 :(得分:3)

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

所以,改变

void keypress(QKeyEvent* keyevent);

void keyPressEvent(QKeyEvent* keyevent)

答案 1 :(得分:2)

您还必须使用setFocusPolicy参数调用widget的Qt::StrongFocus函数。因此,小部件通过标签和点击接受焦点。