为什么我继承自QWidget的类死活接收不到鼠标事件?
准爵 2018-08-23 07:36:56 想写一个弧线形的滑条,没从Slider继承,直接继承的Widget,重写了paint事件,结果不管是MousePressEvent还是MouseMoveEvent都接收不到,直接重写事件、重写event、事件过滤器三种方法都试了都不行,在父窗口写的过滤器也不行,只能拿到paint事件,鼠标的任何事件都收不到
#include "RotateSlider.h"
#include <QPainter>
#include <QEvent>
#include <math.h>
CRotateSlider::CRotateSlider(QWidget *parent)
: QWidget(parent)
{
min = 0;
max = 270;
cur = 1;
R = this->rect().width() / 2;
m_Center = this->rect().center();
m_PrePos.setX(this->rect().center().x() - 10);
m_PrePos.setY(this->rect().center().y() - 10);
this->installEventFilter(this);
//this->grabMouse();
}
CRotateSlider::~CRotateSlider()
{
}
void CRotateSlider::mousePressEvent(QMouseEvent *ev)
{
m_PrePos = ev->pos();
this->repaint();
}
void CRotateSlider::mouseMoveEvent(QMouseEvent *ev)
{
m_NowPos = ev->pos();
double thyta = atan((m_PrePos.x() - m_Center.x()) / (m_PrePos.y() - m_Center.y())) - atan((m_NowPos.x() - m_Center.x()) / (m_NowPos.y() - m_Center.y()));
this->cur = (int)thyta;
this->repaint();
}
bool CRotateSlider::eventFilter(QObject *watched, QEvent *ev)
{
if (watched == this) {
if (ev->type() == QEvent::MouseButtonPress||ev->type() == QEvent::MouseButtonDblClick)
{
QMouseEvent *mouseEv = (QMouseEvent *)ev;
m_PrePos = mouseEv->pos();
this->repaint();
}
else if (ev->type() == QEvent::MouseMove)
{
QMouseEvent *mouseEv = (QMouseEvent *)ev;
m_PrePos = mouseEv->pos();
double thyta = atan((m_PrePos.x() - m_Center.x()) / (m_PrePos.y() - m_Center.y())) - atan((m_NowPos.x() - m_Center.x()) / (m_NowPos.y() - m_Center.y()));
this->cur = (int)thyta;
this->repaint();
}
else if (ev->type() == QEvent::KeyPress)
{
cur++;
}
else if (ev->type() == QEvent::Paint)
{
QPainter p(this);
QRect rect = this->rect();
int startAngle = 225 * 16;
int spanAngle = -(cur - min) % 360 * 16;
p.setRenderHint(QPainter::Antialiasing, true);
p.setPen(QPen(QColor("#00ff00")));
p.drawArc(rect, startAngle, spanAngle);
int dy = (rect.center().y() - m_PrePos.y()) * 6 / R;
int dx = (rect.center().x() - m_PrePos.x()) * 6 / R;
p.setPen(QPen(QColor("#ff0000")));
p.drawLine(m_PrePos.x() - dx, m_PrePos.y() - dy, m_PrePos.x() + dx, m_PrePos.y() + dy);
}
}
return QWidget::eventFilter(watched, ev);
}