这个是main.cpp文件:
#include <QApplication>
#include"KeyMove.h"
int main(int argc, char **argv)
{
QApplication app(argc, argv);
KeyMove keymove;
keymove.show();
return app.exec();
}
这个是KeyMove.h文件:
#include<QWidget>
#include<QLabel>
#include<QLineEdit>
#include<QKeyEvent>
class KeyMove:public QWidget
{
public:
KeyMove();
void keyPressEvent(QEvent *event);
private:
QLabel *left;
QLineEdit *keyleft;
};
这个是KeyMove.cpp文件:
#include"KeyMove.h"
#include<QtGui>
KeyMove::KeyMove()
{
left=new QLabel(tr("Left"));
keyleft=new QLineEdit;
QGridLayout* centerlayout=new QGridLayout;
centerlayout->addWidget(left,0,0,Qt::AlignLeft);
centerlayout->addWidget(keyleft,1,0,Qt::AlignLeft);
setLayout(centerlayout);
}
void KeyMove::keyPressEvent(QEvent *event)
{
if(event->type()==QEvent::KeyPress)
{
QKeyEvent *ke=static_cast<QKeyEvent *>(event);
if(ke->key()==Qt::Key_Left)
{
keyleft->setText(tr("left key has been pressed"));
}
}
}