我想使用一个QTimer对象来控制指示灯的状态。创建继承QWidget的QLed类来控制发光二极管指示器。下面是它的两个相关的主要功能:
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中,我添加了一个名为led的QLabel对象,并将其提升为QLed,在mainwindow.cpp中
ui->led->setLEDFlashing(TRUE);上述代码不会导致LED指示灯闪烁。实际上,由于某种原因,ledTimer和setLEDFlashingTimerHandler之间的连接没有生效,m_value在paintEvent中没有更新。有人能帮我调试代码吗?谢谢!
编辑:
我用QTimer *ledTimer代替QTimer ledTimer解决了连接问题。但是,绘画仍然不能像预期的那样工作,因为m_value没有在该函数中更新,或者该函数只在第一次调用?
发布于 2019-02-22 04:52:56
在您的函数QLed::setLEDFlashing中,您创建了一个QTimer的本地实例,该实例将在函数结束时销毁。
您应该将QTimer声明为类的属性,或者在QObject::startTimer中使用内部计时器
https://stackoverflow.com/questions/54814882
复制相似问题