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

    结果:

  • 相关阅读:
    基础架构:一条SQL查询语句是如何执行的?
    常用的字符串转换日期格式
    JSONObject.fromObject(map)(JSON与JAVA数据的转换)
    ModelAndView的介绍
    Springmvc常用注解
    @PathVariable注解
    @ModelAttribute运用详解
    struts2将servlet对象注入到Action中
    为什么要继承ActionSupport?
    mysql中like用法
  • 原文地址:https://www.cnblogs.com/fuhang/p/9888553.html
Copyright © 2011-2022 走看看