QTextEdit - 如何“取消”在onKeyPress()中输入键码, [英] QTextEdit - How to "cancel" entered key codes in onKeyPress()
问题描述
我试图在中的
或取消
键代码QTextEdit QPlainTextEdit
。当我说取消,我的意思是,我想把输入字符为无取决于输入的键。示例:如果用户在键盘上点击a或b,我不想在文本中显示/输入a或b,而是输入将被忽略并变为无/不处理。
I am trying to "cancel
" key codes in QTextEdit
or QPlainTextEdit
. When I say cancel, what I mean is, I want to turn the "entered" character into "nothing" depending on the key entered. Example: if the user hits "a" or "b" on the keyboard, I would not want to have "a" or "b" displayed / entered into the text, instead, the input would be ignored and turned into nothing / won't be processed.
使用C ++ Builder,您有一个 KeyDown_Event
和一个Key参数。一旦检测到输入的键代码,如果您不喜欢它,您可以将键参数设置为0,因此您设置键= 0,并且不会显示键击。
With C++ Builder, you have a KeyDown_Event
and a "Key" parameter. Once you detect the entered key code, if you don't like it, you can set the "Key" parameter to 0, so you set "Key = 0" and the key stroke would not be displayed. How do I achieve the same thing in 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中执行此操作?
How do I do this in Qt?
> setAccepted(false)和e-> Ignore(),但没有什么区别。我认为到时间e-> ignore()被执行,char已经插入到文本框中。使用C ++ Builder,您可以使用KeyDown事件拦截它并取消它。我似乎找不到一个方法与Qt。
I tired doing e->setAccepted(false) and e->Ignore() but it made no difference. I think by the time e->ignore() is executed, the "char" is already inserted into the text box. With C++ Builder, you can intercept this with the KeyDown event and cancel it. I can't seem to find a way with Qt.
Thx
推荐答案
类似于 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);
}
UPDATE
如 IInspectable 注意到,这不会帮助您过滤 Ctrl + C / Ctrl + V
方法。如果你需要这些,你需要连接到 QTextEdit :: textChanged
信号并手动更新文本。像这样:
As IInspectable noticed, this won't help you with filtering Ctrl+C/Ctrl+V
method. If you need these either, you'll need to connect to QText:textChanged
signal and updated the text manually. Something like this:
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);
这篇关于QTextEdit - 如何“取消”在onKeyPress()中输入键码,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!