Qt的事件模型一个强大的功能是一个QObject对象能够监视发送其他QObject对象的事件,在事件到达之前对其进行处理。
上示的图片黑色键盘是一个独立的Widget的子类CKeyboardForm,白色的背景部分是一个独立的主窗口。现在要实现在白色背景上任意点击某一位置即可实现虚拟键盘的收起,很显然这里就要通过CKeyboardForm来截取全局的鼠标(触摸屏)点击事件,并在代码的监视处实现以上的功能,这就是事件过滤的方法。实现一个事件的过滤包括两个步骤
1.在目标对象上调用installEventFilter(),注册监视对象。
2.在监视对象的EventFilter()函数中处理目标对象的事件。
注册监视对象的位置是在CKeyboardForm的构造函数当中:CKeyboardForm::CKeyboardForm(QWidget parent)
: QWidget(parent)
{
m_lstCharacterBtn.clear();
m_eCurrentMode = InputMode::en;
m_bUpperMode = false;
m_iSymbolPage = 0;
QDesktopWidget desktopWidget = QApplication::desktop();
//global capture
qApp->installEventFilter(this);
}
事件过滤器注册之后,发送到qApp的事件首先到达CKeyboardForm::eventFilter()函数,然后在到达最终的目的地。
下面是eventFilter()的代码。
bool CKeyboardForm::eventFilter(QObject *watched, QEvent *event)
{
if(event->type() == QEvent::MouseButtonPress)
{
QMouseEvent *mouseEvent = dynamic_cast
if(mouseEvent->buttons() == Qt::LeftButton)
{
QPoint pos = mouseEvent->globalPos();
if(pos.y() <= 450)
{
//qDebug()<<“x=”<
}
}
}
return QWidget::eventFilter(watched, event);
}
如果事件是鼠标事件的话,把Event转换成MouseButtonPress,当确定了鼠标点击后,或者当下鼠标点击位置的绝对坐标,然后通过绝对坐标的纵坐标判断是否激发相关信号。
/
Qt 的事件处理有5中级别:
上诉例子说明的是第四种情况(给QApplication安装事件过滤器),下面给出第五种情况(继承QApplication,重写notify())的伪代码,一起学习。
//.h文件
#ifndef MYQAPPLICATION_H
#define MYQAPPLICATION_H
#include
#include
class CMyApplication : public QApplication
{
Q_OBJECT
public:
CMyApplication(int &argc, char **argv);
~CMyApplication();
bool notify(QObject *, QEvent *);
};
#endif
//.cpp文件
#include “MyQApplication.h”
#include
CMyApplication::CMyApplication(int &argc, char **argv):QApplication(argc,argv)
{
}
CMyApplication::~CMyApplication()
{
}
bool CMyApplication::notify(QObject *obj, QEvent *e)
{
const QMetaObject *objMeta = obj->metaObject();
QString clName = objMeta->className();
if(e->type() == QEvent::MouseButtonPress)
{
QMouseEvent *mouseEvent = static_cast(e);
if(mouseEvent->buttons() == Qt::LeftButton)
{
qDebug()<<"left"<
}
//main函数
#include
#include
#include “myapplication.h”
int main(int argc, char *argv[])
{
//注意此处是用myApplication构造不是QApplication
myApplication a(argc, argv);
QWidget w;
w.show();
return a.exec();
}
你可能感兴趣的:(QT,qt)