Qt小组件 - 6 异步运行函数

WorkerThread异步运行自定义函数线程。若使用QThreadPool用来加载一些简单的函数还可以(例: 加载图片等),但是如果做http请求就不好做进程监控,事件提交

python 复制代码
# coding: utf-8
import sys

import requests
from PySide6.QtCore import QCoreApplication
from PySide6.QtCore import QThread, Signal


class WorkerThread(QThread):
    result = Signal(object)  # 返回结果信息信号
    failed = Signal(object)  # 返回失败信息信号
    messageSignal = Signal(object)  # 返回提示信息信号

    def __init__(self, parent=None):
        super().__init__(parent)
        self.func = None
        self.args = None
        self.kwargs = None

    def setTask(self, func, *args, **kwargs):
        self.func = func
        self.args = args
        self.kwargs = kwargs
        if not self.isRunning():
            self.start()

    def run(self):
        try:
            result = self.func(*self.args, **self.kwargs, messageSignal=self.messageSignal)
            self.result.emit(result)
        except Exception as e:
            self.failed.emit(e)


def post_baidu(messageSignal:Signal):
    messageSignal.emit('正在访问百度')
    response = requests.get('https://www.baidu.com')
    messageSignal.emit('访问百度成功')
    messageSignal.emit('判断百度是否正常')
    response.raise_for_status()
    messageSignal.emit('设置返回内容编码')
    response.encoding = 'utf-8'
    messageSignal.emit('返回百度首页内容')
    return response.text


if __name__ == '__main__':
    app = QCoreApplication(sys.argv)
    worker = WorkerThread()
    worker.started.connect(lambda: print('thread start'))
    worker.result.connect(lambda result: print(result))
    worker.failed.connect(lambda e: print(e))
    worker.messageSignal.connect(lambda message: print(message))
    worker.finished.connect(lambda: (app.quit(), print('thread finished')))
    worker.setTask(post_baidu)
    sys.exit(app.exec())

结果

python 复制代码
thread start
正在访问百度
访问百度成功
判断百度是否正常
设置返回内容编码
返回百度首页内容
<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>百度一下,你就知道</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>新闻</a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');
                </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>关于百度</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使用百度前必读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>

thread finished
相关推荐
西阳未落44 分钟前
C++基础(21)——内存管理
开发语言·c++·面试
编程武士1 小时前
从50ms到30ms:YOLOv10部署中图像预处理的性能优化实践
人工智能·python·yolo·性能优化
我的xiaodoujiao1 小时前
Windows系统Web UI自动化测试学习系列2--环境搭建--Python-PyCharm-Selenium
开发语言·python·测试工具
callJJ1 小时前
从 0 开始理解 Spring 的核心思想 —— IoC 和 DI(2)
java·开发语言·后端·spring·ioc·di
hsjkdhs3 小时前
万字详解C++之构造函数析构函数
开发语言·c++
Lin_Aries_04213 小时前
容器化简单的 Java 应用程序
java·linux·运维·开发语言·docker·容器·rpc
傻啦嘿哟4 小时前
Python SQLite模块:轻量级数据库的实战指南
数据库·python·sqlite
Q_Q5110082854 小时前
python+django/flask+uniapp基于微信小程序的瑜伽体验课预约系统
spring boot·python·django·flask·uni-app·node.js·php
XueminXu4 小时前
Python读取MongoDB的JSON字典和列表对象转为字符串
python·mongodb·json·pymongo·mongoclient·isinstance·json.dumps
techdashen4 小时前
12分钟讲解Python核心理念
开发语言·python