和通用的信号机制不同,事件是处理中的更底层实现。
以下程序实现了一个能根据用户鼠标和按键的不同行为,在终端中实现打印不同的语句。
源代码如下:
.h文件
/****************************************************************************
** Form interface generated from reading ui file 'form1.ui'
**
** Created: 一 2月 4 16:15:52 2008
** by: The User Interface Compiler ($Id: qt/main.cpp 3.1.1 edited Nov 21 17:40 $)
**
** WARNING! All changes made in this file will be lost!
****************************************************************************/
#ifndef FORM1_H
#define FORM1_H
#include <qvariant.h>
#include <qwidget.h>
#include <qevent.h>
class QVBoxLayout;
class QHBoxLayout;
class QGridLayout;
class Form1 : public QWidget
{
Q_OBJECT
public:
Form1( QWidget* parent = 0, const char* name = 0, WFlags fl = 0 );
~Form1();
protected:
bool event(QEvent *event);
protected slots:
virtual void languageChange();
};
#endif // FORM1_H
.cpp文件
/****************************************************************************
** Form implementation generated from reading ui file 'form1.ui'
**
** Created: 一 2月 4 16:16:05 2008
** by: The User Interface Compiler ($Id: qt/main.cpp 3.1.1 edited Nov 21 17:40 $)
**
** WARNING! All changes made in this file will be lost!
****************************************************************************/
#include "form1.h"
#include <qvariant.h>
#include <qlayout.h>
#include <qtooltip.h>
#include <qwhatsthis.h>
#include <qimage.h>
#include <qpixmap.h>
#include <qevent.h>
#include <iostream.h>
/*
* Constructs a Form1 as a child of 'parent', with the
* name 'name' and widget flags set to 'f'.
*/
Form1::Form1( QWidget* parent, const char* name, WFlags fl )
: QWidget( parent, name, fl )
{
if ( !name )
setName( "Form1" );
languageChange();
resize( QSize(600, 480).expandedTo(minimumSizeHint()) );
}
/*
* Destroys the object and frees any allocated resources
*/
Form1::~Form1()
{
// no need to delete child widgets, Qt does it all for us
}
/*
* Sets the strings of the subwidgets using the current
* language.
*/
void Form1::languageChange()
{
setCaption( tr( "Form1" ) );
}
bool Form1::event(QEvent *event)
{
if(event->type()==QEvent::KeyPress) 判断是否为案件事件
{
QKeyEvent *keyEvent=(QKeyEvent *)event;
if(keyEvent->key()==Key_Tab) 判断不同的按键以实现不同的处理
cout <<"is Tab/n";
else if(keyEvent->key()==Key_A)
cout <<"is A/n";
}
else if(event->type()==QEvent::MouseButtonRelease) 鼠标双击事件
{
cout <<"QEvent::MouseButtonRelease/n";
}
else if(event->type()==QEvent::Enter)
{
cout <<"QEvent::Enter/n";
}
else if(event->type()==QEvent::Leave)
{
cout <<"QEvent::Leave/n";
}
}
主要就是重新实现实现widget的event()函数,根据不同的参数实现不同的处理。
还应该注意的两点是:
(1)C++中的else if中间有一个空格,不要误写为elseif。
(2)最后可以不用写else判断,判断可以全是else if。