c++ - QTextEdit - 如何 "cancel"在 onKeyPress() 中输入键码

标签 c++ qt

我正在尝试“取消QTextEditQPlainTextEdit 中的键码。当我说取消时,我的意思是,我想根据输入的键将“输入”字符变成“无”。示例:如果用户在键盘上点击“a”或“b”,我不想在文本中显示/输入“a”或“b”,相反,输入将被忽略并变成无/赢'被处理。

使用 C++ Builder,您有一个 KeyDown_Event 和一个“Key”参数。一旦你检测到输入的键码,如果你不喜欢它,你可以将“Key”参数设置为0,这样你设置“Key = 0”并且击键不会被显示。我如何在 Qt 中实现相同的目的?

我用代码解释一下:

if (e->key() == 67)
    // do not send "c" to the QTextEdit (In C++ Bullder, you would do Key = 0)

if (e->key() == 65)
    // do not send "a" to the QTextEdit (In C++ Bullder, you would do Key = 0)

我如何在 Qt 中执行此操作?

我厌倦了 e->setAccepted(false) 和 e->Ignore() 但它们没有区别。我认为在执行 e->ignore() 时,“char”已经插入到文本框中。使用 C++ Builder,您可以使用 KeyDown 事件拦截它并取消它。我似乎找不到使用 Qt 的方法。

谢谢

最佳答案

类似于 void QObject::installEventFilter ( QObject * filterObj ) 示例:

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent)
{
    setupUi(this);

    textEdit->installEventFilter(this);
}

bool MainWindow::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == textEdit && event->type() == QEvent::KeyPress) {
        QKeyEvent *e = static_cast < QKeyEvent * >(event);
        if (e->key() == Qt::Key_A) {
            return true;
        }
    }
    return QMainWindow::eventFilter(watched, event);
}

更新

正如 IInspectable 所注意到的,这不会帮助您过滤 Ctrl+C/Ctrl+V 方法。如果您需要这些,您需要连接到 QTextEdit::textChanged 信号并手动更新文本。像这样:

static QString oldString;
QString s = textEdit->toPlainText();
if (s == oldString)
   return;
int pos = textEdit->textCursor().position();
s.remove('a', Qt::CaseInsensitive);
oldString = s;
textEdit.setPlainText(s);
QTextCursor cursor = textEdit->textCursor();
cursor.setPosition(pos);
textEdit->setTextCursor(cursor);

关于c++ - QTextEdit - 如何 "cancel"在 onKeyPress() 中输入键码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30591912/

相关文章:

c++ - 实现符合 CEN-XFS 的新服务提供 (SP)

c++ - 使用 GLUT_3_2_CORE_PROFILE 时出现 OpenGL 错误 1282(无效操作)

c++ - 如何设置与背景图片大小相对应的窗口大小?

qt - QDialogBu​​ttonBox 中 "Apply"按钮的位置

c++ - 从 QGroupBox 中删除标题

c++ - 在 C++ 中生成随机 double

c++ - 将 system() 结果存储在文件中

c++ - 将 size_t 转换为 int 以声明 char 数组的大小

c++ - 如何使用 QPainter 绘画?

c++ - 如何在 QStyledItemDelegate 中绘制整行的背景?