PDA

View Full Version : how to get key value



lzpmail
11th June 2011, 15:17
hi, i write a simple example, it function to print the key value
this is the code:


bool MainWindow::event(QEvent *event)
{
if (event->type() == QEvent::KeyPress)
{
QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);

qDebug()<<"kev value "<<keyEvent->key();
}

return QMainWindow::event(event);
}


but some time can not get some key value, for example end, up, down, page down key value can not print out.

please tell me what why, and have a good example to get key value.
thanks.

lzpmail
13th June 2011, 03:03
i use another method to get the key value. the code it

void MainWindow::keyPressEvent(QKeyEvent *k)
{
qDebug("in press event %x",k->key());
}

but this method also can not get about NO. key and letter key.
now, i don't know what the reason. please help.

Santosh Reddy
13th June 2011, 04:13
You will not be able to get all the keys in QMainWindow, because QApplication may not be passing them on. To capture all the key events, you need install an event filter on the QApplication instance. Then you can have all the keys pressed, and then eat them, or pass them back.

Example:


class KeySniffer : public QObject
{
Q_OBJECT
...
protected:
bool eventFilter(QObject * obj, QEvent * event);
};

bool KeySniffer::eventFilter(QObject * obj, QEvent * event)
{
if (event->type() == QEvent::KeyPress) {
QKeyEvent *keyEvent = dynamic_cast<QKeyEvent *>(event);
if(keyEvent)
qDebug() << "Key pressed " << keyEvent->key() << keyEvent->text();
}

// standard event processing
return QObject::eventFilter(obj, event);
}

MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
...
// Filter installation on QApplication
QApplication::instance()->installEventFilter(new KeySniffer(this));
...
}

lzpmail
13th June 2011, 04:19
bool KeyboardFilter::filter ( int unicode, int keycode, int modifiers, bool isPress, bool autoRepeat )
hi, what the unicode param fun.

Santosh Reddy
13th June 2011, 04:34
bool KeyboardFilter::filter ( int unicode, int keycode, int modifiers, bool isPress, bool autoRepeat )
hi, what the unicode param fun.\
Unicode univalent of the keycode

lzpmail
13th June 2011, 05:47
ok, i know what should to do. thank you.