Substitute for sleep function in Qt/C++

后端 未结 3 1860
生来不讨喜
生来不讨喜 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条回答
  • 2021-01-26 02:13

    I still don't know what the problem is, but I found a make-shift solution. In my program I include one class (eg class1) into my mainwindow.cpp and from that class I include the timer class. I solved the problem by removing the timer class and adding all those functions to class1. Doesn't make sense to me, but it works.

    0 讨论(0)
  • 2021-01-26 02:26

    Use QTimer or QElapsedTimer if you need more precision.

    main.cpp

    #include <QTimer>
    #include <QCoreApplication>
    #include <QString>
    #include <QTextStream>
    #include <QDebug>
    
    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
    
    0 讨论(0)
  • 2021-01-26 02:30

    This is happening, because you're blocking the thread. In most cases you're interested in using event loop.

    You can use timer and increment a counter in a slot function. Every QObject has support for timer. You can start it using int QObject::startTimer(int interval) and it will call virtual void timerEvent(QTimerEvent *event) every interval miliseconds (it's a virtual method - reimplement it).

    You can also use QTimer and connect QTimer::timeout() signal to accomplish the same thing.

    Inside timer handler increment a counter and print the character.

    It's a good idea to put your hands on finite state machine concept. FSMs are a great tool for solving similar problems problems. In fact, using a timer callback you create a state machine, but very simple one.

    0 讨论(0)
提交回复
热议问题