我有一个简单的应用程序,只有一个QPlainTextEdit,与Qt的例子基本相同:
http://qt-project.org/doc/qt-5.1/qtwidgets/mainwindows-application.html
当我按下Ctrl + Z时,它会调用undo。当我按Ctrl + A时,它会选择所有文本。没关系。
但是当我按下Ctrl + E或Ctrl + R(未在菜单中定义)时,字符“e”和“r”将出现在QSimpleTextEdit中。
如何防止这种情况?如何“过滤”已定义为菜单快捷键并使其保持工作的按键,并“防止”未定义为菜单快捷键的那些按键出现在编辑中?
答案 0 :(得分:1)
有两个选项:
1)创建一个子类并重新实现keyPressEvent()
2)创建一个eventFilter并使用installEventFilter()
(参见http://qt-project.org/doc/qt-5.0/qtcore/qobject.html#installEventFilter)
答案 1 :(得分:1)
您可以使用以下代码:
CSimpleEdit.h
#include <QPlainTextEdit>
class CSimpleEdit: public QPlainTextEdit
{ Q_OBJECT
public:
explicit CSimpleEdit(QWidget* parent = 0);
~ CSimpleEdit();
protected:
bool eventFilter(QObject* obj, QEvent* event);
};
CSimpleEdit.cpp
CSimpleEdit::CSimpleEdit(QWidget* parent)
: QPlainTextEdit(parent)
{ installEventFilter(this); }
CSimpleEdit::~CSimpleEdit()
{ removeEventFilter(this); }
bool CSimpleEdit::eventFilter(QObject *obj, QEvent *event)
{
if (event->type() == QEvent::KeyPress)
{ QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->modifiers() != Qt::NoModifier &&
!keyEvent->modifiers().testFlag(Qt::ShiftModifier))
{ bool bMatch = false;
for (int i = QKeySequence::HelpContents; i < QKeySequence::Deselect; i++)
{ bMatch = keyEvent->matches((QKeySequence::StandardKey) i);
if (bMatch) break;
}
/*You can also set bMatch to true by checking you application
*actions list -> QWidget::actions(). */
if (!bMatch) return true;
}
}
else if (event->type() == QEvent::KeyRelease)
{ QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
if (keyEvent->modifiers() != Qt::NoModifier &&
!keyEvent->modifiers().testFlag(Qt::ShiftModifier))
{ bool bMatch = false;
for (int i = QKeySequence::HelpContents; i < QKeySequence::Deselect; i++)
{ bMatch = keyEvent->matches((QKeySequence::StandardKey) i);
if (bMatch) break;
}
if (!bMatch) return true;
}
}
return QObject::eventFilter(obj, event);
}