Qt 5 : update QProgressBar during QThread work via signal

后端 未结 2 719
无人及你
无人及你 2020-12-16 08:51

I\'m trying to update a QProgressDialog (owned by a QMainWindow class) along the execution of a QThread who process some time consuming operations. The thread emit some sign

2条回答
  •  無奈伤痛
    2020-12-16 09:23

    Absolutely wrong using of QThread). See what is the correct way to implement a QThread... (example please...). You need to learn thread's basics.

    Your mistakes:
    1. Create a static thread object in a local scope;
    2. Wait for its finish in the main thread;
    3. Don't start the thread;
    4. Direct call method doHeavyCaclulations() in the main thread;
    5. emit signal without working event loop for its deliver...

    For your purpose you need:
    Don't inherit QThread. Just create simple Work class with the necessary function:

    class Work: public QObject
    {
        Q_OBJECT
    
    public:
        Work(){};
        virtual ~Work(){};
    
    public slots:
        void doHeavyCaclulations() { /* do what you need and emit progress signal */ };
    
    signals: 
        void progress(int);                
    }
    
    // Then:
    void QApp::doSomeWork()
    {
        //...
        QThread* thread = new QThread(parent);
        Work* worker = new Work; // Do not set a parent. The object cannot be moved if it has a parent. 
        worker->moveToThread(thread);
    
        connect(thread, SIGNAL(finished()), worker, SLOT(deleteLater()));
        connect(thread, SIGNAL(started()), worker, SLOT(doHeavyCaclulations()));
        connect(worker, SIGNAL(progress(int)), &progressDialog, SLOT(setValue(int)));
    
        thread->start();        
        //...
    }
    

提交回复
热议问题