QT 事件处理 KeyPressEvent 和 定时器时间 Timer

1. 按键事件响应, 两种方法,一种直接处理Event,过滤出KeyPress,另一种直接处理KeyPressEvent。

bool Dialog::event(QEvent *e)
{
    if( e->type() == QEvent::KeyPress )
    {
        QKeyEvent *keyEvent = static_cast<QKeyEvent *>(e);
        if( keyEvent->key() == Qt::Key_0 )
            printf("press 0 key 
");
    }
    return QWidget::event(e);
}

void Dialog::keyPressEvent(QKeyEvent *event)
{
    switch ( event->key() )
    {
        case Qt::Key_0 :
            printf("press 0 key 
");
    }
}


2. 定时器使用的几种方法

Timer_test::Timer_test(QWidget *parent)
    : QWidget(parent)
{
    QTimer::singleShot(1000, this, SLOT(timeout1()));   //方法一:单次触发

    QTimer *timer = new QTimer(this);  //方法二:循环触发,信号槽机制
    connect(timer, SIGNAL(timeout()), this, SLOT(timeout1()) );
    timer->start(1000);

    timerID = startTimer(300);  //方法三:复写timerEvent方法,需检验定时器ID
    
}

void Timer_test::timeout1()  //头文件中定义为槽函数
{
    printf("Timeout1
");
}

void Timer_test::timerEvent(QTimerEvent *event)
{
    if( event->timerId() == timerID )
    {
        printf("Timeout2
");
    }
    else
    {
        QWidget::timerEvent(event);
    }
}

3. 创建事件过滤器

a. 通过目标对象调用installEventFilter方法来注册监视对象。

b. 在监视对象的eventFilter()函数中处理目标对象的事件。


 

原文地址:https://www.cnblogs.com/xj626852095/p/3648221.html