Search code examples
c++qtmodal-dialogqt5qprogressdialog

how to make a modal QProgressDialog in QT?


I am calling QProgressDialog from a thread and am unable to make it as a modal window even though I set the setModal to true. I want mainwindow to be blocked when QProgressDialog is in action.

following is my piece of code.

GenericFunc.h
QProgressDialog *progressBarDialog;

GenericFunc.cpp

     void GenericFunc::testSlot()
    {
        int numTasks = 4500;
        progressBarDialog = new QProgressDialog("Task in progress.", "Cancel", 0, numTasks);
        progressBarDialog->setWindowModality(Qt::WindowModal);
        progressBarDialog->setModal(true);
        progressBarDialog->exec();
    }

Solution

  • QProgressDialog class is a GUI class. You cannot instantiate that in the worker thread.

    http://doc.qt.io/qt-5/thread-basics.html#gui-thread-and-worker-thread

    GUI Thread and Worker Thread

    As mentioned, each program has one thread when it is started. This thread is called the "main thread" (also known as the "GUI thread" in Qt applications). The Qt GUI must run in this thread. All widgets and several related classes, for example QPixmap, don't work in secondary threads. A secondary thread is commonly referred to as a "worker thread" because it is used to offload processing work from the main thread.

    Use signal slots to pass the progress data from worker thread to gui thread.

    Another issue is that you set this to WindowModal, but this progressBarDialog doesn't have any parent, so it is not going to block any parent window(s) chain.

    http://doc.qt.io/qt-5/qt.html#WindowModality-enum