adding a countdown timer in a QLabel
-
hello all ,
well , it's my first project using Qt and I want to add a coutdown timer for a game in QLabel but I can't find the problem there (use of undeclared identifier 'connect') . here is my main.cpp and thanks for your help :)void myTimerHandler(QLabel *time2){
qint32 counter=0;
QTimer *timer = new QTimer();
counter++;
time2->setText(QString("Time: %1 seconds").arg(counter));
if(counter == 3600){
time2->setText(QString("GAME OVER"));
timer->stop();
}
}void accessories(QWidget *baseWidget)
{
QLabel *player2 = new QLabel(baseWidget);
QLabel *name2 = new QLabel("Player 2", baseWidget);
//QLabel *time2 = new QLabel("00:00:00", baseWidget);
time2 = new QLabel("00:00:00", baseWidget);//qint32 counter = 0; //QTimer *timer = new QTimer(); qint32 counter=0; QTimer *timer = new QTimer(); connect(timer,SIGNAL(&QTimer::timeout()),SLOT(myTimerHandler(time2))); timer->start(1000); time2->setText(QString("Time: %1 seconds").arg(counter)); counter++; if(counter == 3600){ time2->setText(QString("GAME OVER")); timer->stop(); }
}
int main(int argc, char *argv[])
{
QApplication a(argc, argv);QWidget *myWidget = new QWidget(); myWidget->setGeometry(0,0,1370,700); accessories(myWidget);
myWidget->show();
return a.exec();
} -
Hi,
It looks like you are doing that connect from a "floating" method hence your issue. The connect method belongs to the QObject class.
-
@mayyy
You would have to useQObject::connect()
.connect()
is available in anyQObject
-derived class. You are not in one. In fact you are not in any class. You are writing C-style global functions. You will need to get C++/object-oriented to get far in Qt. -
thank you @SGaist and @JonB for your quick response , but even when I add QObject::connect() i get the same error .
@JonB yes it's a global function but it works just this part ( of the countdown timer), should I implement a class for this countdown timer ? and how can i instantiate it then in a QLabel ? -
@mayyy
Instead of just usingQWidget *myWidget = new QWidget()
, I would suggest creating your own subclass ofQWidget
(which itself inherits fromQObject
) and use that. Your functions can then be member functions, and probably the other widgets will be members too. You will be able to callconnect()
. Then things will begin to come together.If you are starting out in Qt, I strongly suggest you move away from
SIGNAL
/SLOT
macros and adopt new style syntax. -
Since you are a beginner, you should take the time to follow one or more of Qt's widgets tutorials in the documentation before going further. You'll get the ropes and avoid pitfalls doing so.