美文网首页
PyQt笔记——Qt中的线程QThread

PyQt笔记——Qt中的线程QThread

作者: Hemmelfort | 来源:发表于2018-12-24 11:55 被阅读12次

说Qt只是个图形库的人,终究还是太年轻了,虽然以前我也说过这样的话。

Qt中的线程可以在后台偷偷摸摸地做一些看不见的事情,比如处理网络连接,或者修改UI。用法也比较简单,最常见的是直接继承。

import time  # 为了制造延迟效果
from PyQt5 import QtWidgets, QtCore

# 老三样,创建一个应用窗口
app = QtWidgets.QApplication([])
dlg = QtWidgets.QDialog()
dlg.show()

class MyThread(QtCore.QThread):
    ''' 继承QThread类,并重写run方法。run方法里面是我们撒欢的地方。 '''
    def run(self):
        time.sleep(1)    # 设置一秒钟后,改标题
        dlg.setWindowTitle('hahahaha')

thread = MyThread()
thread.start()

app.exec_()
        

如果不方便继承,可以用types模块将外部函数添加到线程中:

import time
from PyQt5 import QtWidgets, QtCore

app = QtWidgets.QApplication([])
dlg = QtWidgets.QDialog()
dlg.show()

def changeTitle(self):
    # 注意这有个 self, 跟一般的类函数写法是一样的
    # 我们要假装这个函数就是thread中的函数
    time.sleep(1)
    dlg.setWindowTitle('hehehehe')

thread = QtCore.QThread()
#thread.run = changeTitle    # 这种方法是行不通的, 要用下面那种
import types
thread.run = types.MethodType(changeTitle, thread)   # 把外部函数强加给线程
thread.start()

app.exec_()

文中的代码直接复制粘贴运行就能看到效果。

相关文章

网友评论

      本文标题:PyQt笔记——Qt中的线程QThread

      本文链接:https://www.haomeiwen.com/subject/mesjkqtx.html