鼠标按键事件

-----------mousekeyevent.h---------
#include <QtGui/QLabel>
#include <QtGui/qevent.h>
#include <QString>
/通过继承QObject,事件通过它们的event函数来通知对象
//在QWidget中的event实现把绝大多数常用类型的事件提前传递给特定的事件处理器
class MouseKeyEvent
    : public QWidget
{
public:
    MouseKeyEvent(QWidget *parent);
protected:
    void mousePressEvent(QMouseEvent *);
    void mouseMoveEvent(QMouseEvent *);
    void keyPressEvent(QKeyEvent *);
private:
    QLabel *label;
};
------------mousekeyevent.cpp-------
#include "mousekeyevent.h"

MouseKeyEvent::MouseKeyEvent(QWidget *parent)
    : QWidget(parent)
{
    setWindowTitle("qt_example");

    label = new QLabel("Welcome!", this);
    label->setGeometry(25,70,250,100);
}


void MouseKeyEvent::mousePressEvent(QMouseEvent *e)
{
    switch(e->button())
    {
//Qt处理的事件类型有一百多种,其中的每一种都可以通过一个枚举值来进行识别
    case Qt::LeftButton:
        label->clear();
        label->setText("Mouse:LeftButton Press!");
        break;
    case Qt::RightButton:
        label->clear();
        label->setText("Mouse:RightButton Press!");
        break;
    case Qt::MidButton:
        label->clear();
        label->setText("Mouse:MidButton Press!");
        break;
    default:
        label->clear();
        label->setText("Mouse:Undefined Press!");
        break;
    }
}

void MouseKeyEvent::mouseMoveEvent(QMouseEvent *e)
{
    QString str = QString("X:");
    QString ps = "";
    ps.setNum(e->x());
    str += ps;
    str += "  Y";
    ps = "";
    ps.setNum(e->y());
    str += ps;
    label->clear();
    label->setText(str);
}
//如果该事件是一个按键事件,那么就把这个QEvent对象强制转换成QKeyEvent并且检查按下的是哪一个键
void MouseKeyEvent::keyPressEvent(QKeyEvent *e)
{
    switch(e->key())
    {
    case Qt::Key_Escape:
        label->clear();
        label->setText("Key:Esc Press!");
        break;
    default:
        label->clear();
        label->setText("Key:Undefind Press!");
        break;
    }
}
------------------main.cpp-----------
#include <QtGui/QApplication>
#include "mousekeyevent.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    MouseKeyEvent *mouseKeyEvent = new MouseKeyEvent(0);
    mouseKeyEvent->setGeometry(10, 20, 320, 240);
    mouseKeyEvent->show();
    return a.exec();
}

你可能感兴趣的:(职场,鼠标,休闲)