线程使用方法之moveToThread
2017-06-01 10:04
525 查看
widget.h
widget.cpp
main.cpp
注意点:程序结束会提示信息 QThread: Destroyed while thread is still running
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = 0); ~Widget(); private: Ui::Widget *ui; public slots: void slot(); }; class ThreadWorker : public QObject { Q_OBJECT public: ThreadWorker(QObject* parent=0); signals: void sig(); public slots: void slot(); }; #endif // WIDGET_H
widget.cpp
#include "widget.h" #include "ui_widget.h" #include <QThread> #include <QDebug> Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); qDebug() << "widget thread: " << thread()->currentThreadId(); } Widget::~Widget() { qDebug() << "~Widget()"; delete ui; } void Widget::slot() { qDebug() << "Widget::slot()" << ", widget thread: " << thread()->currentThreadId(); } ThreadWorker::ThreadWorker(QObject *parent) : QObject(parent) { } void ThreadWorker::slot() { qDebug() << "ThreadWorker::slot()" << ", ThreadWorker thread:" << QThread::currentThreadId(); emit sig(); }
main.cpp
#include "widget.h" #include <QApplication> #include <QDebug> #include <QThread> int main(int argc, char *argv[]) { QApplication a(argc, argv); qDebug() << "main thread: " << qApp->thread()->currentThreadId();; Widget w; w.show(); //方法2:moveToThread ThreadWorker threadWorker; QThread thread; threadWorker.moveToThread(&thread); QObject::connect(&threadWorker, SIGNAL(sig()), &w, SLOT(slot())); QObject::connect(&thread, SIGNAL(started()), &threadWorker, SLOT(slot()) ); QObject::connect(&thread, SIGNAL(finished()), &threadWorker, SLOT(deleteLater()) ); thread.start(); return a.exec(); }
注意点:程序结束会提示信息 QThread: Destroyed while thread is still running
相关文章推荐
- moveToThread的最简单用法(依葫芦画瓢即可)(使得线程也更偏向于信号槽的使用方法)
- moveToThread的最简单用法(依葫芦画瓢即可)(使得线程也更偏向于信号槽的使用方法)
- moveToThread的最简单用法(依葫芦画瓢即可)(使得线程也更偏向于信号槽的使用方法)
- 在Qt使用moveToThread() qt的线程
- 一种使用QThread线程的新方法QObject::moveToThread
- 一种使用QThread线程的新方法QObject::moveToThread
- 一种使用QThread线程的新方法QObject::moveToThread
- 一种使用QThread线程的新方法QObject::moveToThread
- 一种使用QThread线程的新方法QObject::moveToThread
- 一种使用QThread线程的新方法QObject::moveToThread
- Android Tthread 建立线程使用方法
- 理解QT线程中的moveToThread
- EF Core使用SQL调用返回其他类型的查询 ASP.NET Core 2.0 使用NLog实现日志记录 CSS 3D transforms cSharp:use Activator.CreateInstance with an Interface? SqlHelper DBHelper C# Thread.Abort方法真的让线程停止了吗? 注意!你的Thread.Abort方法真
- Thread 线程 join() 方法的使用方式
- 使用runOnUiThread解决Handler无法调用含用子线程方法的问题
- 在Qt使用moveToThread()
- python 8-1 如何使用多线程,Thread创建线程,执行函数赋值给target//类+函数放在run方法中执行
- 方法一、使用Handler和Thread(线程)实现定时器
- Android项目开发技巧–moveTaskToBack(boolean )方法的使用