コード内にスリープがある場合、子スレッドで実行されないと、メインスレッドがスタックします。
子スレッドの .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;
}