c++ – How do I Sleep in Qt?

Question:

2 seconds after the first picture, the second one should appear. How do I pause the program? I tried a lot of things. Either the program hangs, or it just doesn't work.

void Widget::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    QPainter painter(this);
    painter.setPen(QPen(Qt::black, 1, Qt::SolidLine, Qt::FlatCap));

    if(ui->startButton->isChecked()){
        painter.setBrush(QBrush(Qt::red, Qt::SolidPattern));
        painter.drawRect(20,30, 180, 120);
        // здесь должна быть пауза
        painter.setBrush(QBrush(Qt::green, Qt::SolidPattern));
        painter.drawEllipse(100, 150, 180, 200);
    } 
    else if(ui->pauseButton->isChecked()){
    } 
    else if(ui->cleanButton->isChecked()){
    }
}

void Widget::on_startButton_clicked()
{
    repaint();
}

void Widget::on_pauseButton_clicked()
{
    repaint();
}

void Widget::on_cleanButton_clicked()
{
    repaint();
}

Answer:

You can fall asleep in three ways using the static functions of QThread :

void QThread::msleep(unsigned long msecs);
void QThread::sleep (unsigned long  secs);
void QThread::usleep(unsigned long usecs);

But in your case, this is not the best idea. Because rendering is done in the main thread of the application, and while it sleeps, processing of events, messages, etc. in this thread will not be performed. That is, in fact, the entire application will stand for 3 seconds, which is a bit too much.

Timers are better suited for your task. Qt has a very handy QTimer . The second option, if the van needs to constantly do something at regular intervals, then you can use the "built-in" timers in QObject . These timers are created / deleted using the startTimer / killTimer functions , processed in the QObject::timerEvent virtual function.

And in order not to freeze for repainting, use update() instead of repaint() .

Scroll to Top