我想编写一个复古蛇来响应我的按键事件,这是我的代码:
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)
您还必须使用
setFocusPolicy
参数调用小部件的 Qt::StrongFocus
函数。因此小部件通过 Tab 键和单击来接受焦点。