zoukankan      html  css  js  c++  java
  • qt 中创建一个工作线程(例子)

    当一个事件需要很长的处理时间,就创建一个工作线程,防止主界面卡死。

    1.新建一个QT的gui项目,里面包含main.cpp,mainwindow.h,mainwindow.cpp,mainwindow.ui文件

    2.新建一个头文件thread.h,派生一个线程类,重新写一个线程的入口函数。

    #ifndef THREAD_H
    #define THREAD_H
    class MyThread:public QThread
    {
        Q_OBJECT
    public:
        MyThread(QObject *parent);

    void run();//线程入口函数(工作线程的主函数) } #endif // THREAD_H

    3.新建thread.cpp,定义run()函数

    #include"thread.h"
    #include<sstream>
    #include<iostream>
    using namespace std;
    MyThread::MyThread(QObject *parent)
        :QThread(parent)
    {
    }
    MyThread::~MyThread()
    {
    
    }void MyThread::run()
    {
        cout<<"开始执行线程"<<endl;
        QThread::msleep(10000);
        cout<<"线程执行完毕"<<endl;
    }

    4.在mainwindow.h中导入thread.h文件,并声明线程

    #ifndef MAINWINDOW_H
    #define MAINWINDOW_H
    
    #include <QMainWindow>
    #include"thread.h"
    
    namespace Ui {
    class MainWindow;
    }
    
    class MainWindow : public QMainWindow
    {
        Q_OBJECT
    
    public:
        explicit MainWindow(QWidget *parent = 0);
        ~MainWindow();
    
    private:
        Ui::MainWindow *ui;
        MyThread *task;//声明线程
    };
    
    #endif // MAINWINDOW_H

    4.在mainwindow.cpp文件的构造函数中实例化线程并启动线程。

    #include "mainwindow.h"
    #include "ui_mainwindow.h"
    #include "thread.h"
    
    MainWindow::MainWindow(QWidget *parent) :
        QMainWindow(parent),
        ui(new Ui::MainWindow)
    {
        ui->setupUi(this);
        task=new MyThread(NULL);
        task->start();
    }
    
    MainWindow::~MainWindow()
    {
        delete ui;
    }

    结果:

  • 相关阅读:
    答题活动小程序V3.0
    在线答题小程序关于完形填空题的设计
    如何搭建在线答题小程序
    考研政治刷题小程序我来了
    JVM中的枚举
    IO Stream byte[]
    成长经验系列之七-方法-跳出背了忘忘了背的循环
    JVM之GC Roots
    深入理解Java虚拟机-第三版-第二章JVM内存区域笔记
    JVM之DirectByteBuffer
  • 原文地址:https://www.cnblogs.com/fuhang/p/9888553.html
Copyright © 2011-2022 走看看