c++ - QKeyEvent in my app does not work -
i want program retro snaker responds keyevents, here's 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 keypress()
function, wonder function not connect anything, work? didn't, not know how activate it. need else?
http://qt-project.org/doc/qt-4.8/qwidget.html#keypressevent. need override keypressevent, not create keypress function of own.
so, change
void keypress(qkeyevent* keyevent);
to
void keypressevent(qkeyevent* keyevent)
Comments
Post a Comment