我正在尝试“取消
”QTextEdit
或QPlainTextEdit
中的键码。当我说取消时,我的意思是,我想根据输入的键将“输入”字符变成“无”。示例:如果用户在键盘上点击“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/