Question

I'm standing in front of a small (maybe not) problem. I have one function which parses XML file (very big xml ~1Gb) so it takes many time (5-6 mins to finish the func). I don't want to use it in GUI-thread because of known issues (mainwindow freezes and nothing happened, so user thinks everything goes wrong). I've tried to solve this problem by using

QtConcurrent::run

But one more problem appeared: if user press X (close button in top right corner) main GUI-thread goes down, but child-thread which was generated my QtConcurrent::run continue his work and I can kill him only by task manager.

I've decided to use QThread instead of QtConcurrent::run6 but I don't understand how can I run MainWindow class function:

void MainWindow::parseXML()

I've tried to create smth like this:

class pThread : public QThread
{
    Q_OBJECT
private:
    void run();
};

void pThread::run(){
    MainWindow::parseXML();
}

But when I'm trying to compile it error appears:

cannot call member function 'void MainWindow::parseXML()' without object

Moreover, I don't know if it possible to update GUI-thread through this method (parseXML function changes statusBar)

What should I do?

Was it helpful?

Solution

The recommended ways to work with threads in Qt is not to inherit from QThread class, see the documentation here and you should be able to do it after that.

And yes it is possible to update the mainwindow from the thread, just code the signals and slots for that functionality, into mainwindow class code a slot that updates the progress and into the class that does the work (the xml parsing you need - there is no reason that functionality should be into the mainwindow class anyway) you code the signal that emit the progress and connect it with mainwindow's slot with Qt::QueuedConnection (note that the default auto-connection will become queued if the objects are in separate threads).

OTHER TIPS

Another option is to use start a QRunnable with QThreadPool. you may want to check documentation. Be ware to wait the spawned threads with QThreadPool::waitForDone().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top