标签:slots 理解 connect 技术 ret tns ted bsp null
说一下我自己的理解,所谓的多线程,其实对CPU使用时间的划分,就好比原本一间商店一个人运行,当你买东西的时候,总是不得不等待,因为一个人肯定有些忙不过来。
但是如果换成两个能力差一点的人,可能他们干的慢了一点,但是起码每次你在窗口买东西的时候,总会有人回答记录你的问题,我觉得这就是线程的意义-》让用户不用太久。
QT里面的线程主要有两种用法,可以参考博客:
本博客主要参考这个博客:关于QT主线程和工作线程更新界面的问题。
1-建立工程
Thread2_uiCount
2-ui界面
3-程序
Thread2_uiCount.cpp
#include "Thread2_uiCount.h" #include "mythread.h" Thread2_uiCount::Thread2_uiCount(QWidget *parent) : QMainWindow(parent) { ui.setupUi(this); thread = new ThreadTest(this); thread->setObj(this); connect(ui.pushButton, SIGNAL(clicked()), this, SLOT(slotBtnStartThread())); connect(this, SIGNAL(sigCount()), this, SLOT(slotCount())); } void Thread2_uiCount::slotBtnStartThread() { if(thread != nullptr) { thread->start(); } } void Thread2_uiCount::runInThread() { emit sigCount(); } void Thread2_uiCount::slotCount() { cnt++; ui.label->setText(QStringLiteral("当前计数:%1").arg(cnt)); } void Thread2_uiCount::closeEvent(QCloseEvent* event) { if (thread->isRunning()) { thread->terminate(); thread->quit(); } }
Thread2_uiCount.h
#pragma once #include <QtWidgets/QMainWindow> #include "ui_Thread2_uiCount.h" class ThreadTest; class QCloseEvent; class Thread2_uiCount : public QMainWindow { Q_OBJECT public: Thread2_uiCount(QWidget *parent = Q_NULLPTR); void runInThread(); void closeEvent(QCloseEvent* event); signals: void sigCount();//这个信号并没有被定义 private slots: void slotBtnStartThread(); void slotCount(); private: Ui::Thread2_uiCountClass ui; ThreadTest* thread = nullptr; int cnt = 0; };
mythread.h
#ifndef _MYTHREAD_HPP #define _MYTHREAD_HPP #include <qthread.h> #include "Thread2_uiCount.h" //class Thread2_uiCount; class ThreadTest :public QThread { Q_OBJECT public: ThreadTest(QObject* parent); void setObj(Thread2_uiCount* obj); protected: void run(); private: Thread2_uiCount* guiMain = nullptr; }; #endif
mythread.cpp
#include "mythread.h" #include "Thread2_uiCount.h" ThreadTest::ThreadTest(QObject* parent) :QThread(parent) {} void ThreadTest::setObj(Thread2_uiCount* obj) { guiMain = obj; } void ThreadTest::run() { while (true) { msleep(1); guiMain->runInThread(); } }
标签:slots 理解 connect 技术 ret tns ted bsp null
原文地址:https://www.cnblogs.com/fantianliang/p/12430876.html