Home > OS >  Is there a way to start a new thread from dialog and use it in mainwindow in qt?
Is there a way to start a new thread from dialog and use it in mainwindow in qt?

Time:04-24

I have a function that downloads a torrent file. I need to download the torrent in a separate thread from the GUI thread, so I used QtConcurrent::run to start the download in another thread, but I started the download in a dialog and the dialog closes immediatly after the download has started, and (I'm new to qt, so I think) closing the dialog, the dialog object gets deleted and with the dialog QFuture and QFutureWatcher are also deleted and, since QFutureWatcher doesn't exists anymore, it doesn't emit the finished signal. Can someone tell me how to fix this and if what I wrote above is true?

Here is the code i use to start the download:

mainwindow.cpp

void MainWindow::on_downloadButton_clicked {
  DownloadDialog ddl_dial;
  ddl_dial.exec();
}

downloaddiaolg.cpp

on_finishButton_clicked() {
  TorrentDDL tddl;
  QFutureWatcher<void> *watcher = new QFutureWatcher<void>;
  QFuture<void> tddl_thread = QtConcurrent::run(&TorrentDDL::download, 
  &tddl, magnet_str_url, file_path);
  watcher->setFuture(tddl_thread);
  close();
}

CodePudding user response:

GUI has one thread in QT. please see this

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.

But you can have a separate class for downloading and then inherit it from QThread.

You can use worker objects by moving them to the thread using QObject::moveToThread().

CodePudding user response:

Dialog gets deleted because it goes out of scope because it's instantiated on stack. Use heap.

DownloadDialog* ddl_dial = new DownloadDialog(this);
ddl_dial->exec();

Don't forget to delete it at some point to avoid memory leak.

  •  Tags:  
  • c qt
  • Related