Wait/sleep 100ms during QPixmap in QLabel slideshow



  • Hi again :)

    I want to create an image slideshow, by waiting 100ms between the displayed pics. The pictures are displayed as QPixmap's in a QLabel. The slideshow should start when I'm clicking on the pushButton.

    std::vector<QPixmap> pics;
    //.......
    
    void MainWindow::on_pushButton_clicked()
    {
            for(const QPixmap& x: pics){
                ui->label->setPixmap(x);
                //wait 100ms between each pic
            }
    }
    

    I've tried using QThread::msleep(100); but this freezes the program 100*nr. of pics ms and displays the last image only.


  • Qt Champions 2016

    Hi
    You could use a timer and a slot and do it sort of reverse

    in constructor
    QTimer *timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(update()));
    timer->start(1000);
    ..

    // this is called every second. adjust if need to be faster/slower
    void MainWindow::update()
    {
    if (currentimage <pics.size() )
    ui->label->setPixmap( pics[ currentimage++ ] );

    }



  • Thanks, I'll try this method. However, is there no simpler way to do it ? Such as a single function call. Why doesn't msleep work in this case ?


  • Qt Champions 2016

    @cpper
    well you pause the GUI thread with msleep.

    The reason you dont see each image is that the for loop
    don't allow events to be processed.

    You can use QApplication::processEvents();
    in the loop and it will sort of work - but you will still make the
    GUI a big laggy as long for loops in gui thread is just not a good idea.



  • @mrjj
    It's clear now.

    Since I want to keep everything in the clicked() function (and not call update() slot) I used both QTimer and QEventLoop:

    
    void MainWindow::on_pushButton_clicked()
    {
        QTimer timer(this);
        QEventLoop loop;
        timer.setInterval(100);
        QObject::connect(&timer, &QTimer::timeout,&loop,&QEventLoop::quit);
    
        for(const QPixmap& x: pics){
            ui->label->setPixmap(x);
            timer.start();
            loop.exec();
        }
    
    
    
    }
    

    It works as I wished now. But would it be better to use pointer to QTimer and QEventLoop in such situations ?


  • Qt Champions 2016

    @cpper
    ok. super.
    Nope, in this case using non pointers is very correct since
    there is no need for pointers here. :)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.