您可以使用以下代码:
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);
}