Qt coding

  • I like C# for its very clear syntax. Could you please point me out how to write this piece of C# code in Qt to achieve best readability of the code:

    Timer timer = new Timer();
    timer.Elapsed += (sender, e) => { Console.WriteLine("Elapsed");};
    timer.Interval = 100;

    I like this code in C# because only 4 lines of code are sufficient to start timer and do some action when the timer elapses. Also I like that you can see all the functionality on one place (anonymous method). I hope something similar is achievable in Qt and C++.

  • QTimer has a good example of this in their documentation:


    There's no anonymous function call, but the syntax is still pretty clear.

  • Moderators

    One note: Qt is not a programming language! Qt is a C++ framework (similar to what .Net framework is) and as such is usually used with C++ as programming language. But you can use Qt with other programming languages as well, for example Python.

    C++ supports lambda functions since C++11 standard.

  • @elveatles So this seems to be minimal syntax, right?

    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(elapsed()));

    // then somewhere there is elapsed method:

    void elapsed( void) {
    qDebug() << "Elapsed"

    // Then in .h file I also need to declare elapsed().

    void elapsed( void);

  • Yeah, That's the closest Qt translation.

  • @jsulm Sorry not to be very precise.

  • // with c++11

    auto timer = new QTimer;
    connect(timer, &QTimer::timeout, []{qDebug() << "Elapsed";});

Log in to reply

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