2

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

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

4

2 回答 2

4

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

所以,改变

void keypress(QKeyEvent* keyevent);

void keyPressEvent(QKeyEvent* keyevent)
于 2013-03-26T06:50:57.810 回答
2

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

于 2013-03-26T06:55:57.983 回答