Qt event three systems: key events

QKeyEvent class is used to describe a keyboard event. When the keyboard key is pressed or released, the keyboard event will be transmitted to the input member has the keyboard focus.

QKeyEvent the key () function can get specific keys for Qt given all the keys, you can view in Qt Help:: Key keywords. Of particular note is that the Enter key here is Qt :: Key_Return; some of the modifier keys on the keyboard, such as Ctrl and Shift, etc., where the need to use QKeyEvent of modifiers () function to get, you can use the Qt :: Help KeyboardModifier keyword to view all the modifier keys.

QKeyEvent member function has two key events:

void QWidget::keyPressEvent(QKeyEvent *event)   //键盘按下事件
void QWidget::keyReleaseEvent(QKeyEvent *event) //键盘松开事件

Both can basically meet the needs of the general, but only if the control has received the focus of the focus has been acquired. Specifically how to use it?

Be declared in the header file .h in:

protected:
    void keyPressEvent(QKeyEvent *event); //键盘按下事件
    void keyReleaseEvent(QKeyEvent *event); //键盘松开事件

Be driven functions in the .cpp:

//键盘按下事件
void Widget::keyPressEvent(QKeyEvent * event)
{
    switch (event->key())
    {
        //ESC键
        case Qt::Key_Escape:
            qDebug() <<"ESC";
        break;
        //回车键
        case Qt::Key_Return:
            qDebug() <<"Enter";
        break;
        //退格键
        case Qt::Key_Backspace:
            qDebug() <<"Back";
        break;
        //空格键
        case Qt::Key_Space:
            qDebug() <<"Space";
        break;
        //F1键
        case Qt::Key_F1:
            qDebug() <<"F1";
        break;
    }

    //先检测Ctrl键是否按下
    if(event->modifiers() == Qt::ControlModifier)
    {
        //如果是,那么再检测M键是否按下
        if(event->key() == Qt::Key_M)
        {
            //按下则使窗口最大化
            this->setWindowState(Qt::WindowMaximized);
        }
    }
}

//键盘释放事件
void Widget::keyReleaseEvent(QKeyEvent *event)
{
    //方向UP键
    if(event->key() == Qt::Key_Up)
    {
        qDebug() << "release: "<< "up";
    }
}

Respectively Press ESC, Enter, Backspace, Space, F1 key, "application output" as the output window, press Ctrl + M to additionally can also maximize the window:

ESC
Enter
Back
Space
F1
release:  up

Guess you like

Origin www.cnblogs.com/linuxAndMcu/p/11023299.html