Using QTimer in main() (not in a class)?

  • Hi,

    What I want to achieve is a timer instance created within my main function, that on timeout calls another function within main.cpp .

    Normally the syntax of connecting the right signal and slot would be something like this:


    which normally would be fine, but the app I am making does not have a MainWindow and this is happening within the main function (its a simple app and I don't need to use the MainWindow setup). So unless theres a special way to use it it seems that I cannot connect the timer signal to the slot this way as I don't have a class instance to give the connect function, and I can't use "this" since again, its not a class instance.

    In the wiki I noticed a newer way to use connect mentioned here:

    connect(sender, &Sender::valueChanged, someFunction);

    which would allow me to just connect a signal to a function like a desire. So i tried:

        QTimer timer;
        QObject::connect(&timer, &QTimer::timeout, slotUpdate());

    but then I get:

    main.cpp:40: error: C2665: 'QObject::connect': none of the 3 overloads could convert all the argument types

    So, I'm a little stuck on how to pull this off. Anyone know how to do this ? ><

    Thanks in advance.

  • Hi! There's just a typo in your connect statement :-)

    #include <QApplication>
    #include <QDebug>
    #include <QTimer>
    void someFunction()
        qDebug() << "Some function";
    int main(int argc, char *argv[])
        QApplication a(argc, argv);
        QTimer timer;
        QObject::connect(&timer, &QTimer::timeout, someFunction);
        QObject::connect(&timer, &QTimer::timeout, []() { qDebug() << "Lambda"; });
        return a.exec();

  • Woops...

    That did the trick, thanks!

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.