Qt开发计算器应用如何正确拦截乘号(*)按键按下事件
问题根因
你的代码存在三处核心问题:
- Qt枚举采用大驼峰命名规则,你使用的
Qt::Key_multiply拼写错误,正确的小键盘乘号枚举值为Qt::Key_Multiply Qt::Key_Multiply仅对应小键盘的按键,主键盘按下Shift+8输入时,key()返回值为Qt::Key_8,同时携带Qt::ShiftModifier修饰符,单独判断Qt::Key_Multiply无法捕获该场景- 小键盘小数点对应的Qt枚举为
Qt::Key_KeypadPeriod,和主键盘小数点的Qt::Key_Period是两个独立枚举值
正确枚举对应表
| 输入符号 | 触发场景 | 对应Qt枚举值 |
|---|---|---|
| * | 小键盘乘号键 | Qt::Key_Multiply |
| * | 主键盘Shift+8组合键 | 需同时满足key() == Qt::Key_8和modifiers() & Qt::ShiftModifier |
| . | 小键盘小数点键 | Qt::Key_KeypadPeriod |
| . | 主键盘小数点键 | Qt::Key_Period |
修复方案
这里提供两种实现方案,可按需选择:
方案1:补充枚举判断(适合需要严格区分按键来源的场景)
修改eventFilter中的switch分支,补充缺失的判断逻辑:
bool MainWindow::eventFilter(QObject *obj, QEvent *event){ if(obj==this && event->type()==QEvent::KeyPress){ QKeyEvent* keyEvent=static_cast<QKeyEvent*>(event); QString KeyPressed; // 先处理Shift+8的乘号场景 if (keyEvent->key() == Qt::Key_8 && (keyEvent->modifiers() & Qt::ShiftModifier)) { VisualItem_key_pressed("*"); return true; } 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; // 补充两种小数点的判断 case Qt::Key_Period: case Qt::Key_KeypadPeriod: KeyPressed=".";VisualItem_key_pressed(KeyPressed);return true; } } return QMainWindow::eventFilter(obj,event); }
方案2:直接判断输入字符(更简单通用,无需区分按键来源)
如果不需要区分输入符号的按键来源,直接读取按键事件的text属性即可,不管是哪种方式输入的对应符号都能直接捕获,代码更简洁:
bool MainWindow::eventFilter(QObject *obj, QEvent *event){ if(obj==this && event->type()==QEvent::KeyPress){ QKeyEvent* keyEvent=static_cast<QKeyEvent*>(event); QString input = keyEvent->text(); // 直接判断输入的字符是否为支持的符号 if (input == "*" || input == "." || input == "+" || input == "-" || input == "/" || input == "(" || input == ")") { VisualItem_key_pressed(input); return true; } // 数字键也可以用同样的逻辑处理,无需逐个写case if (input.size() == 1 && input.at(0).isDigit()) { VisualItem_key_pressed(input); return true; } } return QMainWindow::eventFilter(obj,event); }
内容的提问来源于stack exchange,提问作者Айдар Имамов
相关产品推荐
相关产品推荐

