Problem related to timer?
-
In the code given below the mousepress slot is not called at all. what may be the problem behind it?
@
#ifndef BUTTON_H
#define BUTTON_H#include <QtGui>
class button:public QPushButton
{
Q_OBJECTpublic:
button(QWidget *parent = 0);
void animate_button();public slots:
void mousepress();};
#endif // BUTTON_H
#include <QtGui>
#include "ofi_vc_gui_button.h"button::button(QWidget *parent): QPushButton(parent)
{
qDebug ()<<"button constructor";
QPalette pal;
pal.setColor(QPalette::ButtonText,QColor(0,255,255));
setPalette (pal);
setText ("hello");
}void button::animate_button (bool t)
{
QTimer timer;
connect (&timer, SIGNAL(timeout()), this, SLOT(mousepress()));
timer.start (1000);
qDebug ()<<"timer called";
}void button::mousepress ()
{
qDebug ()<<"mouse pressed";
}#include <QtGui/QApplication>
#include "ofi_vc_gui_button.h"int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QMainWindow window;
button *b1 = new button(&window);
b1->animate_button ();#if defined(Q_WS_S60)
window.showMaximized();
#else
window.show();
#endifreturn a.exec();
}
@
-
In your code, timer is a local variable in button::animate_button (bool t), and will be destroyed after the function ended.
You should declare it on the heap instead:
@
void button::animate_button (bool t)
{
QTimer *timer = new QTimer(this);
connect(timer, SIGNAL(timeout()),
this, SLOT(mousepress()));
timer->start (1000);
qDebug ()<<"timer called";
}
@