方法:
????????構(gòu)造QMouseEvent或QKeyEvent,使用QApplication::sendEvent或postEvent進行投送事件? ? 。
????????QApplication::sendEvent()和QApplication::postEvent()都是Qt中用于發(fā)送事件的函數(shù),它們之間的區(qū)別在于事件的處理方式。
????????QApplication::sendEvent(target, event)是直接將事件event發(fā)送給目標target,并阻塞當前線程等待目標處理完事件后再繼續(xù)執(zhí)行,這個過程類似于一個同步調(diào)用。
????????QApplication::postEvent(target, event)則是將事件event放入目標target的事件隊列中,并立即返回,在目標及其父級窗口的事件循環(huán)下一次輪詢時會取出該事件進行處理。這個過程類似于一個異步調(diào)用。
????????因此,使用QApplication::postEvent()能夠避免當前線程等待目標窗口處理事件而被阻塞的情況,可以提高程序的響應(yīng)性。但也需要注意的是,由于QApplication::postEvent()是基于事件循環(huán)的機制進行處理的,所以它并不是實時的,可能會存在一定的延遲。如果需要立即處理事件并等待結(jié)果,則應(yīng)該使用QApplication::sendEvent()。文章來源:http://www.zghlxwxcb.cn/news/detail-552905.html
以下是在MainWindow實現(xiàn)的,主動觸發(fā)、接收QMouseEvent及QKeyEvent的示例:文章來源地址http://www.zghlxwxcb.cn/news/detail-552905.html
//MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QMouseEvent>
#include <QKeyEvent>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = 0);
void mousePressEvent(QMouseEvent* )override;
void keyPressEvent(QKeyEvent* )override;
~MainWindow();
protected:
void sendMouseEvent();
void sendKeyEvent();
private:
bool currentMouseEvent {false};
};
#endif // MAINWINDOW_H
//MainWindow.cpp
#include "mainwindow.h"
#include <QApplication>
#include <QDebug>
#include <QTimer>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
QTimer* timer = new QTimer(this);
timer->start(1000);
connect(timer,&QTimer::timeout,this,[=]{
if(currentMouseEvent)
{
this->sendKeyEvent();
currentMouseEvent = false;
}
else {
currentMouseEvent = true;
this->sendMouseEvent();
}
});
}
MainWindow::~MainWindow()
{
}
//鼠標事件
void MainWindow::mousePressEvent(QMouseEvent *eve)
{
if(eve->button() == Qt::LeftButton)
qDebug()<<"鼠標左鍵點擊";
QMainWindow::mousePressEvent(eve);
}
//鍵盤事件
void MainWindow::keyPressEvent(QKeyEvent *eve)
{
if(eve->key() == Qt::Key_Enter)
qDebug()<<"鍵盤回車按下";
QMainWindow::keyPressEvent(eve);
}
//手動觸發(fā)鍵盤事件
void MainWindow::sendKeyEvent(){
QKeyEvent *event = new QKeyEvent(QEvent::KeyPress,
Qt::Key_Enter,
Qt::NoModifier,
"");
QApplication::postEvent(this, event);
}
//手動觸發(fā)鼠標事件
void MainWindow::sendMouseEvent()
{
QMouseEvent *event = new QMouseEvent(QEvent::MouseButtonPress,
QPointF(width()/2, height()/2),
Qt::LeftButton,
Qt::LeftButton,
Qt::NoModifier);
QApplication::postEvent(this, event);
}
到了這里,關(guān)于Qt/QtCreator:主動觸發(fā)鼠標或鍵盤事件QMouseEvent與QKeyEvent的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!