其他分享
首页 > 其他分享> > QT键盘消息

QT键盘消息

作者:互联网

相对鼠标消息, 键盘消息显得要容易些.
主要是继承并实现这两个函数

virtual void keyReleaseEvent(QKeyEvent * event);
virtual void keyPressEvent(QKeyEvent * event);  

我在这两个函数里加了些代码,让用户的按键状态在状态栏中显示出来


void MainWindow::keyPressEvent(QKeyEvent * event)
{
    QString strMessage = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss:zzz");
    strMessage += " keyPressEvent ";

    if (event->modifiers() & Qt::ControlModifier)
    {
        strMessage += " ctrl";
    }

    if (event->modifiers() & Qt::ShiftModifier)
    {
        strMessage += " shift";
    }

    if (event->modifiers() & Qt::AltModifier)
    {
        strMessage += " alt";
    }


    qDebug() << hex << event->key() << endl;

    if ( (0 ==  event->key()) || ( Qt::Key_unknown == event->key()) || event->key() > Qt::Key_Escape)
    {
        strMessage += " no_key";
    }else
    {
        strMessage += " key=";
        strMessage += QChar(event->key());
    }

    ui->statusBar->showMessage(strMessage);
}

void MainWindow::keyReleaseEvent(QKeyEvent * event)
{
    QString strMessage = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss:zzz");
    strMessage  += " keyReleaseEvent ";

    if (event->modifiers() & Qt::ControlModifier)
    {
        strMessage += " ctrl";
    }

    if (event->modifiers() & Qt::ShiftModifier)
    {
        strMessage += " shift";
    }

    if (event->modifiers() & Qt::AltModifier)
    {
        strMessage += " alt";
    }


    qDebug() << hex << event->key() << endl;

    if ( (0 ==  event->key()) || ( Qt::Key_unknown == event->key()) || event->key() > Qt::Key_Escape )
    {
        strMessage += " no_key";
    }else
    {
        strMessage += " key=";
        strMessage += QChar(event->key());
    }


    ui->statusBar->showMessage(strMessage);
}

值得注意的是,假如我只按一个CTRL键,event->key()的值是1000021
按我的理解,event->key()应该是是0或者Qt::Key_unknown,表示没有键按下参考QT文档
int QKeyEvent::key() const

Returns the code of the key that was pressed or released. See Qt::Key for the list of keyboard codes. These codes are independent of the underlying window system. Note that this function does not distinguish between capital and non-capital letters, use the text() function (returning the Unicode text the key generated) for this purpose. A value of either 0 or Qt::Key_unknown means that the event is not the result of a known key; for example, it may be the result of a compose sequence, a keyboard macro, or due to key event compression.


最终,我觉得,如果event->key()的值大于0x1000000,就认为没有实际的键按下:

    if ( (0 ==  event->key()) || ( Qt::Key_unknown == event->key()) || event->key() > Qt::Key_Escape)
    {
        strMessage += " no_key";
    }else
    {
        strMessage += " key=";
        strMessage += QChar(event->key());
    }

Key_Escape的值定义如下:
Key_Escape = 0x01000000,                // misc keys

代码见: http://q1024.com/files/qt_window-master.zip 000700目录

标签:strMessage,modifiers,QT,Key,键盘,消息,key,event,Qt
来源: https://www.cnblogs.com/xingzaicpp/p/16670828.html