Substitute for sleep function in Qt/C++

后端 未结 3 1892
生来不讨喜
生来不讨喜 2021-01-26 01:43

So I am writing a program that displays each letter of a word for 1 second with a 1 second interval between the letters. (It\'s for a spelling exercise for grade 1). I am curren

3条回答
  •  Happy的楠姐
    2021-01-26 02:26

    Use QTimer or QElapsedTimer if you need more precision.

    main.cpp

    #include 
    #include 
    #include 
    #include 
    #include 
    
    int main(int argc, char **argv)
    {
        QCoreApplication application(argc, argv);
        QTimer timer;
        QTextStream textStream(stdout);
        QString word = "apple";
        int i = 0;
        QObject::connect(&timer, &QTimer::timeout, [&textStream, word, &i] () {
            if (i < word.size()) {
                textStream << word.at(i) << flush;
                ++i;
            }
        });
        timer.start(1000);
        return application.exec();
    }
    

    main.pro

    TEMPLATE = app
    TARGET = main
    QT = core
    CONFIG += c++11
    SOURCES += main.cpp
    

    Build and Run

    qmake && make && ./main
    

    Output

    apple
    

提交回复
热议问题