所以我正在编写一个程序,显示一个单词的每个字母 1 秒,字母之间有 1 秒的间隔。(这是一年级的拼写练习)。我目前正在使用睡眠功能将程序“暂停”1 秒钟,然后再次“更新”。之后,它会显示该单词一秒钟,然后将其删除。我在睡眠功能之前重绘,否则它似乎没有及时更新。
这是基本功能:
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 很陌生。
我做的更新。我创建了一个新类来处理计时器,但它似乎并没有真正连接信号和插槽。这是.h文件:
#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";
}