PDA

View Full Version : sleep () in Qt



saifulkhan
1st February 2013, 00:43
8663

Dear Qt Community,

Request your help. We show a random character (A, B, C, ...) in a scene. When the user presses the key then a black window appears and stays for 200 msec. Thereafter another character appears in the screen and the user can make selection by pressing a key again. This process keeps repeating.


If I use the following code to sleep, then the GUI freezes. We can not see the black window.


class Sleep : public QThread
{
public:
static void sleep(unsigned long secs) {
QThread::sleep(secs);
}
static void msleep(unsigned long msecs) {
QThread::msleep(msecs);
}
static void usleep(unsigned long usecs) {
QThread::usleep(usecs);
}
};

The following code does not freeze the GUI, but it keeps taking the events when the window is blank. But when the window is blank we do not want any keypress event to be processed.



QTime dieTime = QTime::currentTime().addSecs(2);
while( QTime::currentTime() < dieTime )
QCoreApplication::processEvents(QEventLoop::AllEve nts, 100);

wysota
1st February 2013, 01:35
You don't need any sleeping. Use a timer or QSequentialAnimationGroup. Or even the state machine framework.

Santosh Reddy
1st February 2013, 10:37
You could do this with simple timer (no need of threads / sleeps), here is a working example


#include <QWidget>
#include <QPainter>
#include <QKeyEvent>
#include <QPaintEvent>
#include <QTextOption>
#include <QApplication>

class Widget : public QWidget
{
Q_OBJECT

public:
Widget()
: text(QString("Press Key To Start :)"))
, textOption(Qt::AlignCenter)
, timer(0)
{
setFixedSize(200, 200);
}
virtual ~Widget() {}

protected:
void paintEvent(QPaintEvent * event)
{
if(timer == 0)
QPainter(this).drawText(event->rect(), text, textOption);
else
QPainter(this).fillRect(event->rect(), QBrush(QColor(Qt::darkGray)));
}

void keyPressEvent(QKeyEvent * event)
{
if(timer == 0)
{
if((event->key() >= Qt::Key_A) and (event->key() <= Qt::Key_Z))
text = QString('A' + event->key() - Qt::Key_A);
else
text.clear();

timer = startTimer(2000); // 2 Seconds
update();
}
}

void timerEvent(QTimerEvent * event)
{
if(timer == event->timerId())
{
timer = 0;
update();
}
killTimer(event->timerId());
}

private:
QString text;
QTextOption textOption;
int timer;
};

int main(int argc, char *argv[])
{
QApplication app(argc, argv);
Widget w;
w.show();
return app.exec();
}

#include "Main.moc"