#include "widget.h"
#include "ui_widget.h"
#include <QTimer>
#include <QDebug>
#include <QMouseEvent>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
//启动定时器
this->id1 = startTimer(1000); //参数1 间隔 单位:毫秒
this->id2 = startTimer(2000);
//定时器第二种使用方式 推荐这种方法
QTimer * timer = new QTimer(this);
//启动定时器
timer->start(500);
connect(timer,&QTimer::timeout,[=](){
static int num4 = 1;
ui->label_4->setText(QString::number(num4++));
});
//点击暂停按钮,停止定时器
connect(ui->pushButton,&QPushButton::clicked,[=](){
timer->stop();
});
//给 label_1安装事件过滤器
//步骤1 安装事件过滤器
ui->label->installEventFilter(this);
//步骤2 重写 eventfilter事件
}
bool Widget::eventFilter(QObject *obj, QEvent *e)
{
if(obj == ui->label)
{
if(e->type() == QEvent::MouseButtonPress)
{
QMouseEvent *ev = static_cast<QMouseEvent *>(e);
QString str = QString("事件过滤器中,鼠标按下了 x = %1 y = %2 globalX = %3 global Y = %4" ).arg(
ev->x()).arg(ev->y()).arg(ev->globalX()).arg(ev->globalY());
qDebug() << str ;
return true;
}
}
//其他默认处理
return QWidget::eventFilter(obj,e);
}
Widget::~Widget()
{
delete ui;
}
//重写定时器事件
void Widget::timerEvent(QTimerEvent *e)
{
if(e->timerId() == id1)
{
// label_2 每隔1s +1
static int num = 1;
ui->label_2->setText(QString::number(num++));
}
if(e->timerId() == id2)
{
// label_3 每隔2s +1
static int num2 = 1;
ui->label_3->setText(QString::number(num2++));
}
}
Qt教程:事件过滤器
最新推荐文章于 2023-06-24 07:15:28 发布