为什么我继承自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);
}
...全文
1259 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
准爵 2018-10-10
  • 打赏
  • 举报
回复
是5楼说的问题,被上一层的一个窗口拦截了事件,然后它没有发到这一层
彩阳 2018-10-03
  • 打赏
  • 举报
回复
有时候就是没有定义slots关键字导致收不到信号,还有很多小陷阱。
芒果黑 2018-09-25
  • 打赏
  • 举报
回复
可能是CRotateSlider上面有一层东西挡住了才收不到,比如一个pushbutton
  • 打赏
  • 举报
回复
看码时,想到的,不会是槽函数声明时,
忘记使用slot关键字,
希望老司机不会出这类低级错误
  • 打赏
  • 举报
回复
这个有点高深,
不如查查控件类,比如qbutton,
是怎么继承的
gushansanren 2018-09-20
  • 打赏
  • 举报
回复
注意public 和protected的区别,
准爵 2018-08-23
  • 打赏
  • 举报
回复
我在这个类里面试着塞了一个QWidget,它可以接收到鼠标事件,但是外面这个RotateSlider还是怎么点都接收不到

16,216

社区成员

发帖
与我相关
我的任务
社区描述
Qt 是一个跨平台应用程序框架。通过使用 Qt,您可以一次性开发应用程序和用户界面,然后将其部署到多个桌面和嵌入式操作系统,而无需重复编写源代码。
社区管理员
  • Qt
  • 亭台六七座
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧