Weird Behavior for QStackedWidget



  • I want to use a Stacked Widget to switch between three different widgets depending on an event that is happening. To test this, I'm creating a StackedWidget, and then changing which widget is "active" every few seconds.

    Here is main:

    int main(int argc, char **argv)
    {
        QApplication app(argc, argv);
    
        view = new MainWindow();
        view->showImg1();
        view->show();       
        QThread::sleep(3);
    
        view->showImg2();
        QThread::sleep(3);
    
        view->showImg3();
    }
    

    And here is the .cpp for MainWindow

    MainWindow::MainWindow(QWidget *parent) : QStackedWidget(parent)
    {
        img1View = new QLabel();
        img2View = new QLabel();
        img3View = new QLabel();
    
        img1View->setPixmap("/home/1.jpg");
        img2View->setPixmap("/home/2.jpg");
        img3View->setPixmap("/home/3.jpg");
    
        this->addWidget(img1View);
        this->addWidget(img2View);
        this->addWidget(img3View);
    }
    
    MainWindow::showImg1()
    {
        this->setCurrentWidget(img1View);
        qDebug() << "Index: " << this->currentIndex();
    }
    
    MainWindow::showImg2()
    {
        this->setCurrentWidget(img2View);
        qDebug() << "Index: " << this->currentIndex();
    }
    
    MainWindow::showImg3()
    {
        this->setCurrentWidget(img3View);
        qDebug() << "Index: " << this->currentIndex();
    }
    

    So the expected behavior is to have a window open on the first image, and to cycle to the second image after 3 seconds and to the final image after 3 seconds.

    What is happening is that none of the images show except for the very last one. But the qDebug messages show up as expected and with the correct index. This leads me to think that all of the images are on the last widget, and the last image is hiding the others. How can I fix this?


  • Lifetime Qt Champion

    Hi and welcome to devnet,

    Don't use QThread::sleep. What happens is that you are currently blocking your application startup hence the reason you see only the last image. show will only have an effect once app.exec() has been called.

    Use QTimer::singleShot. One with 3000 and another with 6000. That will allow your application to start correctly and then change your widget as wanted.



  • @SGaist Thanks!


  • Lifetime Qt Champion

    You're welcome !

    If you have it running properly now, please mark that thread as solved using the "Topic Tools" button so that other forum users may know a solution has been found :)


Log in to reply
 

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