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;
    }

    结果:

  • 相关阅读:
    6.7-CU微程序设计
    6.6-CU组合逻辑设计
    6.5-CU的功能
    6.4-微操作命令的分析
    6.3-时序产生器
    6.2-指令的执行
    6.1-CPU的组成与功能
    5.3-指令格式设计
    【Java循环使用 + JS循环】
    JSON转换集合,报错exepct '[', but {, pos 1, json或者syntax error, expect {, actual [, pos 0
  • 原文地址:https://www.cnblogs.com/fuhang/p/9888553.html
Copyright © 2011-2022 走看看