线程在QT中执行任务时如何使用GUI
How to use GUI while threads doing their jobs in QT?
作为一名自学者,我正在尝试用QT
理解c++中的QThread
逻辑。我写了一个简单的线程类,里面有for循环。然而,当线程在循环内部时,我不能使用MainWindow。为了尝试它,我打开QFileDialog
并选择一些文件。当我按下"Open
"按钮时,线程运行,FileDialog
不会关闭,直到线程完成他的工作。
线程在后台工作时,是否可以使用MainWindow?
这是我尝试的简单代码。。
void MainWindow::on_pushButton_clicked()
{
QFileDialog *lFileDialog = new QFileDialog(this, "Select Folder", "/.1/Projects/", "*");
QStringList selectedFileNames = lFileDialog->getOpenFileNames(this, "Select Images", "/home/mg/Desktop/", "", 0, 0);
if(!selectedFileNames.isEmpty())
{
MyThread mThread1;
mThread1.name = "thread1";
mThread1.run();
mThread1.wait();
}
}
void MyThread::run()
{
for (int var = 0; var < 100000; ++var)
{
qDebug() << this->name << var;
}
}
您不应该在单击处理程序的线程上wait()
!此外,您不需要自己调用线程的run
,只需启动线程即可。启动线程将调用run()
。
这是一个将线程用于阻塞代码的最小示例。主线程保持交互,并每秒输出tick...
,直到线程完成为止。当踏面完成时,它会干净地退出。
当我演示控制台应用程序时,它可以很容易地成为GUI应用程序,并且GUI线程在任何时候都不会被阻塞。
#include <QCoreApplication>
#include <QThread>
#include <QTimer>
#include <QTextStream>
#include <cstdio>
class MyThread : public QThread {
void run() Q_DECL_OVERRIDE {
sleep(10); // block for 10 seconds
}
public:
MyThread(QObject * parent = 0) : QThread(parent) {}
~MyThread() {
wait(); // important: It's illegal to destruct a running thread!
}
}
int main(int argc, char ** argv) {
QCoreApplication app(argc, argv);
QTextStream out(stdout);
MyThread thread;
QTimer timer;
timer.start(1000);
QObject::connect(&timer, &QTimer::timeout, [&out]{
out << "tick..." << endl;
}
app.connect(&thread, SIGNAL(finished()), SLOT(quit()));
thread.start();
return app.exec();
}
相关文章:
- 我不知道如何使用代码块win32 gui
- Qt GUI使用Qfiledialogbox和qlabel显示视频,这是我的代码
- 如何在C++代码之上使用标准的Xcode GUI
- 如何从 Linux 控制台使用 CMake 构建 Eclipse C++ 项目(没有可用的 GUI)
- 如何使用Visual Studio 2017和Qt开发GUI应用程序?
- 解决方法:QPixmap:在GUI线程之外使用pixmap是不安全的
- 当我使用 GUI 开发 QT 动态库时,如何查看我的 QT UI?
- 如何使用.UI文件在QT Creator中使用CMAKE制作GUI QT项目
- 如何在没有网络的情况下控制NodeMCU,但使用像Qt这样的GUI(通过wifi)?
- 是否可以同时使用 GUI 和 3D 图形库创建应用程序
- 您如何从已经运行的GUI应用程序中启动使用GUI的可执行文件
- 如何使用GUI将外部库和项目导入到我的C++项目中
- 从带有OpenGL代码的C 转换为使用GUI的QT应用程序
- 如何在visualstudio2010中为android应用程序使用GUI
- 为什么c#可以在android和iOS上使用GUI制作程序,而c++不能
- QThread:使用 GUI 反馈阻止进行并行执行
- 如何从 VC++ 调用托管 DLL(使用 GUI)
- 在Visual Studio 2012中使用GUI和数据库的Windows应用程序
- 如何在qt中使用gui对象名运行循环
- 线程在QT中执行任务时如何使用GUI