qt中的线程套路

来源:互联网 发布:硅胶点胶机编程视频 编辑:程序博客网 时间:2024/05/06 07:39

qt的线程还是非常优雅的,当然我们可以使用系统自带的函数接口创建线程,但是跨平台移植似乎就是问题。

qt的线程是可以支持跨平台的移植的。

qt的线程非常简单,就是继承QThread然后重写run方法,run函数就是我们的线程主体,对于重写其实本质就是一个回调接口了。

好了注意重点:在主函数实例化然后调用start方法就开始运行线程了,千万不要调用函数调用的急眼了,把run函数也调用了。


头文件

#ifndef THREAD_H#define THREAD_H#include<QThread>#include<QDebug.h>class mythread:public QThread{public:protected:void run(){    while(1)    {        qDebug("test");    }}};#endif // THREAD_H

main函数

#include "mainwindow.h"#include <QApplication>#include <QFile>#include "thread.h"QString getQssContent(){    QFile styleSheet(":/style.ss");    if (!styleSheet.open(QIODevice::ReadOnly))    {        qDebug("Can't open the style sheet file.");        return "";    }    return styleSheet.readAll();}int main(int argc, char *argv[]){    QApplication a(argc, argv);    MainWindow w;    w.show();   mythread th_id; //  th_id.run();**********注意哦,不要调用run,不知道当时是为什么脑残,调用了run //  调试的我怀疑人生.   th_id.start();//运行线程    a.setStyleSheet(getQssContent());    return a.exec();}


界面和耗时操作独立起来!




原创粉丝点击