有没有办法从对话框启动一个新线程并在qt的主窗口中使用它?
Is there a way to start a new thread from dialog and use it in mainwindow in qt?
我有一个下载 torrent 文件的功能。我需要在与 GUI 线程不同的线程中下载 torrent,所以我使用 QtConcurrent::run 在另一个线程中开始下载,但我在对话框中开始下载,下载开始后对话框立即关闭,并且(我是 qt 的新手,所以我认为)关闭对话框,对话框对象被删除并且对话框 QFuture 和 QFutureWatcher 也被删除,并且由于 QFutureWatcher 不再存在,它不会发出完成信号.谁能告诉我如何解决这个问题以及我上面写的是否属实?
这是我用来开始下载的代码:
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();
}
GUI在QT中只有一个线程。请参阅 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.
但是你可以有一个单独的class下载然后从QThread继承它。
您可以使用 QObject::moveToThread()
.
将工作对象移动到线程来使用它们
对话框被删除是因为它超出了范围,因为它是在堆栈上实例化的。使用堆。
DownloadDialog* ddl_dial = new DownloadDialog(this);
ddl_dial->exec();
不要忘记在某些时候删除它以避免内存泄漏。
我有一个下载 torrent 文件的功能。我需要在与 GUI 线程不同的线程中下载 torrent,所以我使用 QtConcurrent::run 在另一个线程中开始下载,但我在对话框中开始下载,下载开始后对话框立即关闭,并且(我是 qt 的新手,所以我认为)关闭对话框,对话框对象被删除并且对话框 QFuture 和 QFutureWatcher 也被删除,并且由于 QFutureWatcher 不再存在,它不会发出完成信号.谁能告诉我如何解决这个问题以及我上面写的是否属实?
这是我用来开始下载的代码:
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();
}
GUI在QT中只有一个线程。请参阅 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.
但是你可以有一个单独的class下载然后从QThread继承它。
您可以使用 QObject::moveToThread()
.
对话框被删除是因为它超出了范围,因为它是在堆栈上实例化的。使用堆。
DownloadDialog* ddl_dial = new DownloadDialog(this);
ddl_dial->exec();
不要忘记在某些时候删除它以避免内存泄漏。