问题描述
所以我写一个程序,显示一个单词的每个字母1秒,字母之间有1秒的间隔。 (这是1级的拼写练习)。我目前正在使用睡眠功能暂停程序1秒钟,然后再更新。之后,它显示单词一秒,然后删除它。
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 currently using the sleep function to "pause" the program for 1 second before it "updates" again. After that it displays the word for a second and then removes it. I repaint before the sleep function, else it does not seem to update in time.
这是基本的功能:
QString word = "apple";
QThread thread;
for(int i = 0; i < word.size(); i++)
{
ui->label1->setText(word[i]);
ui->label1->repaint();
thread.sleep(1);
ui->label1->setText("");
thread.sleep(1);
}
ui->label1->setText(word);
ui->label1->repaint();
thread.sleep(1);
ui->label1->setText("");
这很好,除了程序停止响应(即使我可以看到正确的输出仍然显示)直到整个函数完成执行,然后它再次工作正常。有没有另一种方式,我可以完成这个目标,而不使用睡眠?我对Qt很新。
This works fine, except the program stops responding (even though I can see the correct output is still displaying) until the whole function is done executing then it works fine again. Is there another way I can accomplish this goal without using sleep? I am quite new to Qt.
我更新了。我做了一个新类,将处理的定时器,但它似乎没有实际连接信号和插槽。这是.h文件:
Update I made. I made a new class that will handle the timer, but it does not seem to actually connect the signal and slot. Here is the .h file:
#ifndef TIMERDISPLAY_H
#define TIMERDISPLAY_H
#include <QTimer>
#include <QObject>
class TimerDisplay:public QObject
{
Q_OBJECT
public:
TimerDisplay();
public slots:
void expired();
private:
QTimer timer;
};
#endif // TIMERDISPLAY_H
和.cpp文件:
#include "timerdisplay.h"
#include <QDebug>
TimerDisplay::TimerDisplay()
{
connect(&timer, SIGNAL(timeout()), this, SLOT(expired()));
timer.setSingleShot(false);
timer.setInterval(1000);
timer.start();
}
void TimerDisplay::expired()
{
qDebug()<<"timer expired";
}
推荐答案
使用或如果您需要更高的精度。
Use QTimer or QElapsedTimer if you need more precision.
#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
main.pro
TEMPLATE = app
TARGET = main
QT = core
CONFIG += c++11
SOURCES += main.cpp
构建并运行
Build and Run
qmake && make && ./main
输出
Output
apple
这篇关于在Qt / C ++中替换睡眠函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!