6

我有一个只有一个 QPlainTextEdit 的简单应用程序,与此处的 Qt 示例基本相同:

http://qt-project.org/doc/qt-5.1/qtwidgets/mainwindows-application.html

当我按 Ctrl+Z 时,它调用撤消。当我按 Ctrl+A 时,它会选择所有文本。还行吧。

但是当我按下菜单中未定义的 Ctrl+E 或 Ctrl+R 时,字符“e”和“r”将出现在 QSimpleTextEdit 中。

我该如何防止这种情况?如何“过滤”已定义为菜单快捷方式的按键并使其保持工作,并“防止”那些未定义为菜单快捷方式的按键出现在编辑中?

4

2 回答 2

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);
}
于 2013-10-21T18:31:33.790 回答
1

有2个选项:

1)创建一个子类并重新实现keyPressEvent()

2)创建一个eventFilter并使用installEventFilter()(见http://qt-project.org/doc/qt-5.0/qtcore/qobject.html#installEventFilter

于 2013-10-10T12:17:56.087 回答