首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用widget连接Qtimer

使用widget连接Qtimer
EN

Stack Overflow用户
提问于 2019-02-22 03:34:34
回答 1查看 300关注 0票数 0

我想使用一个QTimer对象来控制指示灯的状态。创建继承QWidgetQLed类来控制发光二极管指示器。下面是它的两个相关的主要功能:

代码语言:javascript
复制
void QLed::setLEDFlashing(bool value)
{
    ledStatus = value; //Boolean value to accept a user-defined LED status
    m_value = ledStatus; //m_value is used in painting LED (with QtSvgRenderer)

    QTimer ledTimer;
    ledTimer.setInterval(300);
    if(!ledTimer.isActive())
    {
        ledTimer.start();
    }

    //Here is the connection between the timer and this (i.e., QLed*) object
    connect(&ledTimer, SIGNAL(timeout()), this, SLOT(setLEDFlashingTimerHandler()));
}

//I want to use this function to make LED keep flashing
void QLed::setLEDFlashingTimerHandler() 
{
    //qDebug()<<"setLEDFlashingTimerHandler()";
    if (ledStatus)
    {
        m_value = TRUE;
        ledStatus = FALSE;
    }
    else
    {
        m_value = FALSE;
        ledStatus =TRUE;
    }
}

//This is to paint the LED widget
void QLed::paintEvent(QPaintEvent *)
{
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);

    //based on m_value, different svg file is loaded
    if(m_value)
        ledShapeAndColor.append(colors[m_onColor]);
    else
        ledShapeAndColor.append(colors[m_offColor]);

    renderer->load(ledShapeAndColor);
    renderer->render(&painter);

    //qDebug()<<"paintEvent m_value="<<m_value;
}

mainwindow.ui中,我添加了一个名为ledQLabel对象,并将其提升为QLed,在mainwindow.cpp

代码语言:javascript
复制
ui->led->setLEDFlashing(TRUE);

上述代码不会导致LED指示灯闪烁。实际上,由于某种原因,ledTimersetLEDFlashingTimerHandler之间的连接没有生效,m_valuepaintEvent中没有更新。有人能帮我调试代码吗?谢谢!

编辑:

我用QTimer *ledTimer代替QTimer ledTimer解决了连接问题。但是,绘画仍然不能像预期的那样工作,因为m_value没有在该函数中更新,或者该函数只在第一次调用?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-02-22 04:52:56

在您的函数QLed::setLEDFlashing中,您创建了一个QTimer的本地实例,该实例将在函数结束时销毁。

您应该将QTimer声明为类的属性,或者在QObject::startTimer中使用内部计时器

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54814882

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档