Qt中事件的分发大概流程是这样的:
.h文件中的定义:
protected:
virtual void mousePressEvent(QMouseEvent *event);
.cpp文件中的定义:
void Widget::mousePressEvent(QMouseEvent *event)
{
int xPt = event->pos().x();
int yPt = event->pos().y();
qDebug() << "QWidget " << xPt << ", " << yPt;
return QWidget::mousePressEvent(event);
}
下面是一个事件传递的例子:
.h例子:
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include <QPushButton>
class PushButton : public QPushButton
{
Q_OBJECT
public:
PushButton(QWidget *parent = nullptr);
~PushButton();
protected:
virtual void mousePressEvent(QMouseEvent *event);
};
// -----------------------------------------------------------------------------------
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = 0);
~Widget();
protected:
virtual void mousePressEvent(QMouseEvent *event);
private:
QPushButton *m_Button = nullptr;
};
#endif // WIDGET_H
.cpp例子:
#include "widget.h"
#include <QVBoxLayout>
#include <QDebug>
#include <QMouseEvent>
PushButton::PushButton(QWidget *parent)
:QPushButton(parent)
{
this->setFixedSize(200, 200);
}
PushButton::~PushButton()
{
}
void PushButton::mousePressEvent(QMouseEvent *event)
{
QPushButton::mousePressEvent(event);
qDebug() << "MousePressed " << event->pos().x() << ", " << event->pos().y();
event->ignore();
}
// -----------------------------------------------------------------------------------
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
m_Button = new PushButton(this);
m_Button->setText("OK");
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(m_Button);
QObject::connect(m_Button, &QPushButton::clicked, [=](void)->void{
qDebug() << "PushButton Pressed!" ;
});
this->setGeometry(100, 100, 800, 600);
}
Widget::~Widget()
{
}
void Widget::mousePressEvent(QMouseEvent *event)
{
int xPt = event->pos().x();
int yPt = event->pos().y();
qDebug() << "QWidget " << xPt << ", " << yPt;
return QWidget::mousePressEvent(event);
}
点击按钮后的运行结果:
MousePressed 144 , 77
QWidget 157 , 277
PushButton Pressed!
QPushButton::mousePressEvent(event)默认会接收鼠标事件,按钮处理MousePress事件后,调用event->ignore()函数事件被忽略向下传递到Widget类中,Widget类处理mousePress事件。