QT之键盘事件
Widget.h:
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include<QKeyEvent> #include "mypushbutton.h" class Widget : public QWidget { Q_OBJECT public: Widget(QWidget *parent = 0); ~Widget(); void keyPressEvent(QKeyEvent* e); void keyReleaseEvent(QKeyEvent* e); private: MyPushButton *p1; MyPushButton *p2; }; #endif // WIDGET_H
mypushbutton.h:
#ifndef MYPUSHBUTTON_H #define MYPUSHBUTTON_H #include <QPushButton> class MyPushButton : public QPushButton { Q_OBJECT public: explicit MyPushButton(const QString& text,QWidget *parent = nullptr); void keyPressEvent(QKeyEvent* e); void keyReleaseEvent(QKeyEvent* e); signals: public slots: }; #endif // MYPUSHBUTTON_H
mypushbutton.cpp:
#include "mypushbutton.h" #include<QKeyEvent> #include<QDebug> MyPushButton::MyPushButton(const QString& text,QWidget *parent) :QPushButton(text,parent){} void MyPushButton::keyPressEvent(QKeyEvent* e) { //e->modifiers() 修饰键 if(e->modifiers()&Qt::ControlModifier) { qDebug()<<"子类的Ctrl被按下了"<<endl; } if(e->modifiers()&Qt::AltModifier) { qDebug()<<"子类的Alt被按下了"<<endl; } switch(e->key()) { case Qt::Key_A: qDebug()<<__FUNCTION__<<e->text()<<endl; break; case Qt::Key_D: qDebug()<<__FUNCTION__<<e->text()<<endl; break; } } void MyPushButton::keyReleaseEvent(QKeyEvent* e) { }
widget.cpp:
#include "widget.h" #include<QDebug> #include "mypushbutton.h" #include<QVBoxLayout> Widget::Widget(QWidget *parent) : QWidget(parent) { p1=new MyPushButton("按钮1",this); p2=new MyPushButton("按钮2",this); QVBoxLayout *s=new QVBoxLayout(this); s->addWidget(p1); s->addWidget(p2); //this->setFocus(); //本来是子窗口接受键盘事件,现在设置焦点窗口为父窗口 this->setFocus(Qt::OtherFocusReason); //按tab键可以实现在两个按钮之间来回切换 } void Widget::keyPressEvent(QKeyEvent* e) { //e->modifiers() 修饰键 if(e->modifiers()&Qt::ControlModifier) { qDebug()<<"Ctrl被按下了"<<endl; } if(e->modifiers()&Qt::AltModifier) { qDebug()<<"Alt被按下了"<<endl; } switch(e->key()) { case Qt::Key_A: qDebug()<<e->text()<<endl; break; case Qt::Key_D: qDebug()<<e->text()<<endl; break; } } void Widget::keyReleaseEvent(QKeyEvent* e) { } Widget::~Widget() { }
main.cpp:
#include "widget.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; w.show(); return a.exec(); }
效果: