代码中有sleep的话,如果不放到子线程中执行,会将主线程卡死。
子线程的.h文件
#ifndef THREAD_H
#define THREAD_H
#include <QObject>
#include <QThread>
class Thread : public QThread
{
Q_OBJECT
public:
Thread();
void run() override;
};
#endif // THREAD_H
子线程的.cpp文件
#include "thread.h"
Thread::Thread()
{
}
void Thread::run()
{
Sleep(100);//耗时操作
}
调用的地方的.h文件
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "thread.h"
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
Thread th;
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
调用的地方的.cpp文件
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
th.start();//启动子线程
}
MainWindow::~MainWindow()
{
delete ui;
}