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
myApp.h
class someClass: public QDialog
{
Q_OBJECT
public:
...<snip>...
private:
...<snip>...
protected:
void keyPressEvent(QKeyEvent *e);
};
myApp.cpp
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?
我键入abcd以获得上面的内容。键()不应该给我按下键的整数值吗?
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?
第二个问题是,当我点击一个箭头键时,除了一个空行之外,在debug窗格中我什么也得不到。我是不是应该看到向上箭头的整数值?(此处列出的键值)。然后如何输出密钥的ASCII值?
Any help is appreciated.
任何帮助都是感激。
1 个解决方案
#1
2
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.
通过e->键()将指针移到“您输入”的指针,并使它指向另一个位置,在这个情况下,这个位置被作为输出的字符串占用。
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());
#1
2
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.
通过e->键()将指针移到“您输入”的指针,并使它指向另一个位置,在这个情况下,这个位置被作为输出的字符串占用。
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());