Question

I want to program a retro snaker that responds to my keyevents, here's my code:

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();
}

Focus on the keypress() function, I wonder that the function does not connect to anything, could it work? Actually it didn't, but I do not know how to activate it. Do I need to do anything else?

Was it helpful?

Solution

http://qt-project.org/doc/qt-4.8/qwidget.html#keyPressEvent. You need to override keyPressEvent, not create a keyPress function of your own.

So, change

void keypress(QKeyEvent* keyevent);

to

void keyPressEvent(QKeyEvent* keyevent)

OTHER TIPS

You also must call widget's setFocusPolicy function with Qt::StrongFocus argument. So widget accepts focus by both tabbing and clicking.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top