简体   繁体   中英

QKeyEvent keyPressEvent not detecting arrow keys?

I have a program that captures a single key press and then outputs the key that is being pressed. The problem is, I am not able to return the value of the key being pressed and cannot get the arrow keys to output anything at all. Here's my code:

myApp.h

class someClass: public QDialog
{
  Q_OBJECT

public:
  ...<snip>...

private:
  ...<snip>...

protected:
  void keyPressEvent(QKeyEvent *e);
};

myApp.cpp

MyApp::MyApp(QWidget *parent) :
  QDialog(parent),
  ui(new Ui::myApp)
{
  QWidget::grabKeyboard();
  ui->setupUi(this);
}

void someClass::keyPressEvent(QKeyEvent *e)
{
  qDebug() << "You typed " + e->key();
}

There are two issues here. First, when I type any key, I get output like the following in the Debug pane:

gw492_32\include/QtCore/qstring.h
w492_32\include/QtCore/qstring.h
492_32\include/QtCore/qstring.h
92_32\include/QtCore/qstring.h

I typed abcd to get the above. Shouldn't key() give me the integer value of the key pressed?

The second issue is that when I hit one of the arrow keys, I get nothing in the debug pane except for a blank line. Again, shouldn't I be seeing the integer value for the Up arrow? (values for keys listed here ). How would I then output the ASCII value for the key?

Any help is appreciated.

The output definitely looks like unwanted pointer arithmetic is happening. And it's undefined behavior.

"You typed " + e->key()

advances the pointer to "You typed " by e->key() and makes it point to another location, which is in this case occupied by the string you're getting as output.

If you want to print it properly, do any of the following:

qDebug() << "You typed " << e->key();
qDebug() << "You typed " + QString::number(e->key());
qDebug() << QString("You typed %1").arg(e->key());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM