Keypress events
-
Hello everyone,
Today I satrted wondering how the keypress events work in Qt, so I started to make a small app to check that out. Unfortunately I can't manage to get it working :( . All I get is the button in the middle, but its never moves..
Here's the code:
@#include "Mainwin.h"
#include <QKeyEvent>
#include <QKeySequence>
#include <QPoint>
#include <QDebug>Mainwin::Mainwin() : QWidget()
{
but = new QPushButton(this);
but->setText("O");
but->setVisible(true);
this->setFixedSize(600,600);
but->move(300,300);waitforkp();
}
void Mainwin::waitforkp()
{
QKeyEvent *event = new QKeyEvent(QEvent::KeyPress,0,Qt::NoModifier,"",false,4);
if (event->key() == Qt::Key_Down){
but->move(but->pos().x(),but->pos().y()-1);
qDebug() << "in down";
}if (event->key() == Qt::Key_Left){ but->move(but->pos().x()-1,but->pos().y());
}
if (event->key() == Qt::Key_Up){ but->move(but->pos().x(),but->pos().y()+1);
}
if (event->key() == Qt::Key_Right){ but->move(but->pos().x()+1,but->pos().y());
}
qDebug() << but->pos();
}
@Also, I guess it's not the "conventional way" to do it.
Thanks for every answer I get ;)EDIT: I never see the "in down" debug I placed in waitforkp()
-
Hi,
Small fix for above code:
@
void Mainwin::keyPressEvent(QKeyEvent *)
{
.... // code here
}
@
is the correct syntax. For all Q_Object derived classes your are able to overwrite the events, such as timerEvent, changeEvent etc etc. For every event there is a eventhandler. -
This still doesn't work :(
Here's my updated code:
@#include "Mainwin.h"
#include <QKeyEvent>
#include <QKeySequence>
#include <QPoint>
#include <QDebug>Mainwin::Mainwin() : QWidget()
{
but = new QPushButton(this);
but->setText("O");
but->setVisible(true);
this->setFixedSize(600,600);
but->move(300,300);QKeyEvent *event = new QKeyEvent(QEvent::KeyPress,0,Qt::NoModifier,"",false,4); keyPressEvent(event);
}
void Mainwin::keyPressEvent(QKeyEvent *event)
{if (event->key() == Qt::Key_Down){ but->move(but->pos().x(),but->pos().y()-1); qDebug() << "in down";
}
if (event->key() == Qt::Key_Left){ but->move(but->pos().x()-1,but->pos().y());
}
if (event->key() == Qt::Key_Up){ but->move(but->pos().x(),but->pos().y()+1);
}
if (event->key() == Qt::Key_Right){ but->move(but->pos().x()+1,but->pos().y());
}
qDebug() << but->pos();
}@
And I still can't see the "in down" debug info.. -
don't do that (in your constructor):
@
QKeyEvent *event = new QKeyEvent(QEvent::KeyPress,0,Qt::NoModifier,"",false,4);keyPressEvent(event);
@rather use QApplication::postEvent().
Or better use your keyboard ;)And for clarification why you don't see the debug output. You create your key event with a key of value 0 instead of Qt::Key_Down.