I'm working on a calculator application that has a keyboard for input: (1,2,3,4,5,6,7,8,9,0,-,+,/,*,.,(,),).
Firstly, I tried just to implement keyPressEvent
method like this:
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 = "*";
}
Then I decided to reimplement bool eventFilter()
and use installEventFilter(this)
method instead of 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);
}
But in the first and second cases, multiply key (*) was not working, unlike the other keys.
So the program doesn't associate pressing (*) key on the Numpad, or pressing (Shift+8) with case Qt::Key_multiply
.
Maybe the problem is in Qt::Key_multiply
, because I really don't know how the Numpad decimal separator (.) and multiply (*) symbols are called in Qt.
Try using this:
Qt::Key_Asterisk
.