在QT中实现超时

时间:2013-07-01 07:04:59

标签: qt

我正试图在QT中实现超时。我想执行以下任务,所以我需要超时。 在应用程序中我实现了菜单。如果我从菜单中选择了选项,它将执行相关屏幕。如果我在15秒之前没有收到任何按键事件,此屏幕应在15秒后超时。以下是我的代码:

bool cMeasurementUnit::eventFilter(QObject *obj, QEvent *event)
{
    QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event);
    if(event->type() == QEvent::KeyPress)
    {
        if((keyEvent ->key()) == Qt::Key_Tab)
        {
            if(m_pWidgetFirstTabFocus->hasFocus())
            {
                m_pWidgetFirstTabFocus->setStyleSheet(QString::fromUtf8("background-color: rgb(255, 255, 255);"));
            }
            m_pWidgetFirstTabFocus = m_pWidgetFirstTabFocus->nextInFocusChain() ;
            while((m_pWidgetFirstTabFocus->focusPolicy()) == Qt::NoFocus)
            {
                m_pWidgetFirstTabFocus = m_pWidgetFirstTabFocus->nextInFocusChain() ;
                if(m_pWidgetFirstTabFocus == this)
                {
                    m_pWidgetFirstTabFocus = MEASUREMENT_UNIT_FIRST_TAB;
                }
            }
            m_pWidgetFirstTabFocus->setStyleSheet(QString::fromUtf8("background-color: rgb(207, 207, 207);"));
        }
        else if((keyEvent ->key()) == Qt::Key_Return)
        {
            SaveChannelUnit();
            return true ;
        }
        else if((keyEvent ->key()) == Qt::Key_Up)
        {
            if (((QComboBox *)m_pWidgetFirstTabFocus)->currentIndex() == 0)
            {
                ((QComboBox *)m_pWidgetFirstTabFocus)->setCurrentIndex((((QComboBox *)m_pWidgetFirstTabFocus)->count() - 1)) ;
                return true ;
            }
        }
        else if((keyEvent ->key()) == Qt::Key_Left)
        {
            return true;
        }
    }
    return QObject::eventFilter(obj, event);
}

我尝试使用QTimer :: singleShot(15000,这,SLOT(DeleteClass()))实现; 但它不起作用。关于这个问题,请帮帮我。我在上面的代码if(event-&gt; type()== QEvent :: KeyPress)语句中实现了QTimer :: singleShot,这样每当我按一个键它就会重新初始化QTimer :: singleShot和类cMeasurementUnit的屏幕不会超时,否则会在15秒后超时。以下是DeleteClass的代码,是否正确?如果没有,请告诉我正确的方法吗?提前致谢

void cMeasurementUnit::DeleteClass()
{
    DPRINTF("IN FUNCTION %s\n",__FUNCTION__);
    delete this;
}

1 个答案:

答案 0 :(得分:2)

您可以使用QTimer定期运行检查,QElapsedTimer计算不活动时间。

在标题中:

QElapsedTimer elapsed_timer;

在初始化中:

elapsed_timer.start();
QTimer* timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(timeout()));
timer->start(1000); // number of milliseconds between checks
// install event filter for target widget, etc.

timeout位置:

if (elapsed_timer.elapsed() > 15000) { // timeout interval in msec
  //perform close actions, e.g. widget->close()
}

在事件过滤器中:如果收到适当的键事件,则应执行以下代码:

elapsed_timer.restart();
相关问题