【发布时间】:2021-05-23 16:29:55
【问题描述】:
我是 Qt 的新手,现在正在开发具有键盘输入机会的计算器应用程序 (1,2,3,4,5,6,7,8,9,0,-,+,/,*, .,(,),)。
首先,我尝试像这样确定“keyPressEvent”方法:
void MainWindow::keyPressEvent(QKeyEvent* ev)
{
QString CurrentLabel_disp = ui->label->text();
QString KeyPressed;
if (ev->key() == Qt::Key_0)
KeyPressed = "0";
else if (ev->key() == Qt::Key_1)
KeyPressed = "1";
...
else if (ev->key() == Qt::Key_Plus)
KeyPressed = "+";
else if (ev->key() == Qt::Key_Minus)
KeyPressed = "-";
else if (ev->key() == Qt::Key_Slash)
KeyPressed = "/";
else if (ev->key() == Qt::Key_multiply)
KeyPressed = "*";
}
经过一番思考,我决定重新实现“bool eventFilter()”并使用“installEventFilter(this)”方法而不是“keyPressEvent”确定:
bool MainWindow::eventFilter(QObject *obj, QEvent *event){
if(obj==this && event->type()==QEvent::KeyPress){
QKeyEvent* keyEvent=static_cast<QKeyEvent*>(event);
QString KeyPressed;
switch (keyEvent->key()) {
case Qt::Key_0:
KeyPressed="0";VisualItem_key_pressed(KeyPressed);return true;
case Qt::Key_1:
KeyPressed="1";VisualItem_key_pressed(KeyPressed);return true;
...
case Qt::Key_Plus:
KeyPressed="+";VisualItem_key_pressed(KeyPressed);return true;
case Qt::Key_Minus:
KeyPressed="-";VisualItem_key_pressed(KeyPressed);return true;
case Qt::Key_Slash:
KeyPressed="/";VisualItem_key_pressed(KeyPressed);return true;
case Qt::Key_multiply:
KeyPressed="*";VisualItem_key_pressed(KeyPressed);return true;
}
}
return QMainWindow::eventFilter(obj,event);
}
但在第一种和第二种情况下,乘法键 (*) 不像其他键那样工作..
所以,问题实际上是,程序没有将小键盘上的按 (*) 键或按 (shift+8) 与“case Qt::Key_multiply”相关联
可能问题出在“Qt::Key_multiply”中,因为我真的不知道在 Qt 中如何调用小键盘小数分隔符 (.) 和乘法 (*) 符号..
你能指导我解决这个问题吗?
【问题讨论】:
-
Shift+8和小键盘上的乘法键都映射到Qt::Key_Asterisk。这也仅适用于keyPressEvent,不需要eventFilter。 -
我爱你,戴夫,谢谢!
标签: c++ qt5 calculator