Qt captures keyboard key messages

1. Capture processing inside a single control, the key code is as follows:

//头文件
protected:
  virtual void keyPressEvent(QKeyEvent *ev);
  virtual void keyReleaseEvent(QKeyEvent *ev);
  
//实现  
void TestWidget::keyPressEvent(QKeyEvent *ev) 
{
    
    
	if (ev->key() == Qt::Key_Space) 
	{
    
     
  		//处理事件 
	}
	QWidget::keyPressEvent(ev);
}
void TestWidget::keyReleaseEvent(QKeyEvent *ev) 
{
    
    
	if (ev->key() == Qt::Key_Space) 
	{
    
    
		QMessageBox::information(this, "test", "test");
	}
	QWidget::keyReleaseEvent(ev);
} 

//注意:构造函数中需添加
this->grabKeyboard();

2. Global capture processing, the key code is as follows:

//头文件
class Application : public QApplication 
{
    
    
  Q_OBJECT
public:
  Application(int &argc, char **argv, int flag = ApplicationFlags);
  virtual ~Application();

protected:
  bool notify(QObject *obj, QEvent *event) Q_DECL_OVERRIDE;

signals:
  void sig_handle(bool);
};
//实现
Application::Application(int &argc, char **argv, int flag)
    : QApplication(argc, argv, flag) {
    
    }
Application::~Application() {
    
    }

bool Application::notify(QObject *obj, QEvent *event) 
{
    
    
	if (event->type() == QEvent::KeyPress)
	{
    
    
		QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
		if ((keyEvent->key() == Qt::Key_Space))
		{
    
    
			emit sig_handle(true);
			return true;
		}
	}
	return QApplication::notify(obj, event);
}
//构造函数中需修改如下
Application a(argc, argv);
//使用=》统计和采集全局键盘事件
auto application = dynamic_cast<Application *>(QApplication::instance());
connect(application, &Application::sig_handle, this, &TestWidget::slot_handle);

Guess you like

Origin blog.csdn.net/oTianLe1234/article/details/115307932