Sometimes it needs to control whatever we type with keyboard in text.

For this purpose, we can utilize key names that Qt4 offers, such as Qt::Key_Backspace, Qt::Key_Left and Qt::Key_Right. Complete list can be found at page qt.html on Qt4 documentation.

To catch a combination of key names, QKeySequence is applied instead.

Here is an example.

void MyTextEdit::keyPressEvent(QKeyEvent * e)
{
  // in case of clicking Return/Enter key
  if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter)
  {
    qDebug() << "R E T U R N / E N T E R is just typed --> not allowed";

    return;
  }

  // in case of deleting character by backspace
  if (e->key() == Qt::Key_Backspace)
  {
    qDebug() << "B A C K S P A C E is just typed";
  }

  // in case of pressing an arrow
  if (e->key() == Qt::Key_Left || e->key() == Qt::Key_Right || e->key() == Qt::Key_Up || e->key() == Qt::Key_Down)
  {
    qDebug() << "M O V I N G";
  }

  // in case of pressing SHIFT and RIGHT arrow
  if (e == QKeySequence::SelectNextChar)
  {
    qDebug() << "SelectNextChar is just pressed";
  }

  // in case of pressing SHIFT and LEFT arrow
  if (e == QKeySequence::SelectPreviousChar)
  {
    qDebug() << "SelectPreviousChar is just pressed";
  }

  QTextEdit::keyPressEvent(e);

  // in case of pressing CTRL+Z
  if (e == QKeySequence::Undo)
  {
    qDebug() << "U N D O is just pressed";
    mCursor.setPosition(textCursor().position());
  }
}

where mCursor is type of QTextCursor and declared in the header.

You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.
Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>