PYQT5开启多个线程和窗口,多线程与多窗口的交互实例


Posted in Python onDecember 13, 2019

每点击一次按钮,弹出一个对话框(子窗口),同时开启一个子线程来执行任务并更新对话框内容,关闭对话框则关闭对应子线程

1. 建立一个简单的主界面和一个自定义对话框

PYQT5开启多个线程和窗口,多线程与多窗口的交互实例

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
 def setupUi(self, MainWindow):
  MainWindow.setObjectName("MainWindow")
  MainWindow.resize(327, 303)
  self.centralwidget = QtWidgets.QWidget(MainWindow)
  self.centralwidget.setObjectName("centralwidget")
  self.gridLayout = QtWidgets.QGridLayout(self.centralwidget)
  self.gridLayout.setObjectName("gridLayout")
  spacerItem = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
  self.gridLayout.addItem(spacerItem, 0, 0, 1, 1)
  self.pushButton = QtWidgets.QPushButton(self.centralwidget)
  self.pushButton.setObjectName("pushButton")
  self.gridLayout.addWidget(self.pushButton, 0, 1, 1, 1)
  spacerItem1 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
  self.gridLayout.addItem(spacerItem1, 0, 2, 1, 1)
  MainWindow.setCentralWidget(self.centralwidget)
  self.menubar = QtWidgets.QMenuBar(MainWindow)
  self.menubar.setGeometry(QtCore.QRect(0, 0, 327, 23))
  self.menubar.setObjectName("menubar")
  MainWindow.setMenuBar(self.menubar)
  self.statusbar = QtWidgets.QStatusBar(MainWindow)
  self.statusbar.setObjectName("statusbar")
  MainWindow.setStatusBar(self.statusbar)

  self.retranslateUi(MainWindow)
  self.pushButton.clicked.connect(MainWindow.open_dialog)
  QtCore.QMetaObject.connectSlotsByName(MainWindow)

 def retranslateUi(self, MainWindow):
  _translate = QtCore.QCoreApplication.translate
  MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
  self.pushButton.setText(_translate("MainWindow", "多线程弹窗"))


class Ui_Dialog(object):
 def setupUi(self, Dialog):
  Dialog.setObjectName("Dialog")
  Dialog.resize(369, 128)
  self.gridLayout = QtWidgets.QGridLayout(Dialog)
  self.gridLayout.setObjectName("gridLayout")
  self.buttonBox = QtWidgets.QDialogButtonBox(Dialog)
  self.buttonBox.setOrientation(QtCore.Qt.Horizontal)
  self.buttonBox.setStandardButtons(QtWidgets.QDialogButtonBox.Cancel|QtWidgets.QDialogButtonBox.Ok)
  self.buttonBox.setObjectName("buttonBox")
  self.gridLayout.addWidget(self.buttonBox, 1, 0, 1, 1)
  self.progressBar = QtWidgets.QProgressBar(Dialog)
  self.progressBar.setProperty("value", 24)
  self.progressBar.setObjectName("progressBar")
  self.gridLayout.addWidget(self.progressBar, 0, 0, 1, 1)

  self.retranslateUi(Dialog)
  self.buttonBox.accepted.connect(Dialog.accept)
  self.buttonBox.rejected.connect(Dialog.reject)
  QtCore.QMetaObject.connectSlotsByName(Dialog)

 def retranslateUi(self, Dialog):
  _translate = QtCore.QCoreApplication.translate
  Dialog.setWindowTitle(_translate("Dialog", "Dialog"))

2. 每点击一次按钮,打开一个弹窗

class DialogWindow(QDialog, Ui_Dialog):
 def __init__(self, parent=None):
  super(DialogWindow, self).__init__(parent)
  self.setupUi(self)


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
 def __init__(self, parent=None):
  super(MainWindow, self).__init__(parent)
  self.setupUi(self)

 def open_dialog(self):
  dialog = DialogWindow(self)
  dialog.show()


if __name__ == "__main__":
 app = QtWidgets.QApplication(sys.argv)
 mainWindow = MainWindow()
 mainWindow.show()
 sys.exit(app.exec_())

3. 打开弹窗的同时,打开一个子线程,更新对话框中的进度条

PYQT5开启多个线程和窗口,多线程与多窗口的交互实例

在子线程定义信号,关联对话框更新进度条的槽函数

class DialogWindow(QDialog, Ui_Dialog):
 def __init__(self, parent=None):
  super(DialogWindow, self).__init__(parent)
  self.setupUi(self)

 def update_progressbar(self, p_int):
  self.progressBar.setValue(p_int) # 更新进度条


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
 def __init__(self, parent=None):
  super(MainWindow, self).__init__(parent)
  self.setupUi(self)
  self.count = 0

 def open_dialog(self):
  dialog = DialogWindow(self)
  dialog.show()
  self.thread = RunThread(self.count)
  self.count += 1
  self.thread.update_pb.connect(dialog.update_progressbar) # 关联
  self.thread.start()


class RunThread(QThread):
 update_pb = pyqtSignal(int) # 定义更新进度条的信号

 def __init__(self, count):
  super().__init__()
  self.count = count

 def run(self):
  for i in range(100):
   print('thread%s' % self.count, i, QThread().currentThreadId())
   self.update_pb.emit(i)
   time.sleep(1)
  pass


if __name__ == "__main__":
 app = QtWidgets.QApplication(sys.argv)
 mainWindow = MainWindow()
 mainWindow.show()
 sys.exit(app.exec_())

4. 关闭对话框,则关闭对应子线程

在对话框中添加自定义信号,并重写关闭事件,在关闭窗口时发送关闭子线程的信号

class DialogWindow(QDialog, Ui_Dialog):
 stop_thread = pyqtSignal() # 定义关闭子线程的信号

 def __init__(self, parent=None):
  super(DialogWindow, self).__init__(parent)
  self.setupUi(self)

 def update_progressbar(self, p_int):
  self.progressBar.setValue(p_int)

 def closeEvent(self, event):
  self.stop_thread.emit()
  pass


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
 def __init__(self, parent=None):
  super(MainWindow, self).__init__(parent)
  self.setupUi(self)
  self.count = 0

 def open_dialog(self):
  dialog = DialogWindow(self)
  dialog.show()
  self.thread = RunThread(self.count)
  self.count += 1
  self.thread.update_pb.connect(dialog.update_progressbar)
  dialog.stop_thread.connect(self.thread.terminate)
  self.thread.start()


class RunThread(QThread):
 update_pb = pyqtSignal(int)

 def __init__(self, count):
  super().__init__()
  self.count = count

 def run(self):
  for i in range(1, 101):
   print('thread_%s' % self.count, i, QThread().currentThreadId())
   self.update_pb.emit(i)
   time.sleep(1)
  pass


if __name__ == "__main__":
 app = QtWidgets.QApplication(sys.argv)
 mainWindow = MainWindow()
 mainWindow.show()
 sys.exit(app.exec_())

5. 使用线程池QThreadPool管理子线程

使用QThreadPool, 线程需要继承QRunnable,而QRunnable只是namespace,没有继承QT的信号机制,

所以需要另外继承QObject来使用信号,我这里直接在线程中使用封装的信号向外部传递信息

class DialogWindow(QDialog, Ui_Dialog):
 stop_thread = pyqtSignal() # 定义关闭子线程的信号

 def __init__(self, parent=None):
  super(DialogWindow, self).__init__(parent)
  self.setupUi(self)

 def update_progressbar(self, p_int):
  self.progressBar.setValue(p_int)

 def closeEvent(self, event):
  self.stop_thread.emit()
  pass


class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
 def __init__(self, parent=None):
  super(MainWindow, self).__init__(parent)
  self.setupUi(self)
  self.count = 0
  self.pool = QThreadPool()
  self.pool.globalInstance()
  self.pool.setMaxThreadCount(10) # 设置最大线程数

 def open_dialog(self):
  dialog = DialogWindow(self)
  dialog.show()
  thread = RunThread(self.count)
  self.count += 1
  thread.signal.update_pb.connect(dialog.update_progressbar)
  # dialog.stop_thread.connect(thread.stop)
  # self.thread.start()
  self.pool.start(thread) # 线程池分配一个线程运行该任务


class Signal(QObject):
 update_pb = pyqtSignal(int)


class RunThread(QRunnable):
 def __init__(self, count):
  super().__init__()
  self.count = count
  self.signal = Signal() # 信号

 def run(self):
  for i in range(1, 101):
   print('thread_%s' % self.count, i, QThread().currentThreadId())
   self.signal.update_pb.emit(i)
   time.sleep(1)


if __name__ == "__main__":
 app = QtWidgets.QApplication(sys.argv)
 mainWindow = MainWindow()
 mainWindow.show()
 sys.exit(app.exec_())

QThreadPool没有释放正在运行的线程的方法

以上这篇PYQT5开启多个线程和窗口,多线程与多窗口的交互实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持三水点靠木。

Python 相关文章推荐
从零学python系列之从文件读取和保存数据
May 23 Python
Python使用Supervisor来管理进程的方法
May 28 Python
使用Python编写基于DHT协议的BT资源爬虫
Mar 19 Python
python实现逻辑回归的方法示例
May 02 Python
Python 获得13位unix时间戳的方法
Oct 20 Python
浅谈pandas用groupby后对层级索引levels的处理方法
Nov 06 Python
解决PyCharm的Python.exe已经停止工作的问题
Nov 29 Python
Matplotlib自定义坐标轴刻度的实现示例
Jun 18 Python
python模拟点击玩游戏的实例讲解
Nov 26 Python
windows下python 3.9 Numpy scipy和matlabplot的安装教程详解
Nov 28 Python
用Python实现定时备份Mongodb数据并上传到FTP服务器
Jan 27 Python
matplotlib如何设置坐标轴刻度的个数及标签的方法总结
Jun 11 Python
浅谈PyQt5中异步刷新UI和Python多线程总结
Dec 13 #Python
python编写微信公众号首图思路详解
Dec 13 #Python
selenium+python实现自动登陆QQ邮箱并发送邮件功能
Dec 13 #Python
python中设置超时跳过,超时退出的方式
Dec 13 #Python
python opencv实现gif图片分解的示例代码
Dec 13 #Python
python多进程并发demo实例解析
Dec 13 #Python
使用Matplotlib 绘制精美的数学图形例子
Dec 13 #Python
You might like
PHP小程序自动提交到自助友情连接
2009/11/24 PHP
用PHP实现 上一篇、下一篇的代码
2012/09/29 PHP
基于MySQL到MongoDB简易对照表的详解
2013/06/03 PHP
PHP生成plist数据的方法
2015/06/16 PHP
Linux系统中为php添加pcntl扩展
2016/08/28 PHP
PHP有序表查找之二分查找(折半查找)算法示例
2018/02/09 PHP
php递归函数怎么用才有效
2018/02/24 PHP
PHP常量define和const的区别详解
2019/05/18 PHP
tp5.1 框架join方法用法实例分析
2020/05/26 PHP
javascript下拉框选项单击事件的例子分享
2015/03/04 Javascript
javascript实现检验的各种规则
2015/07/31 Javascript
跟我学习javascript的定时器
2015/11/19 Javascript
JS组件中bootstrap multiselect两大组件较量
2016/01/26 Javascript
JS闭包、作用域链、垃圾回收、内存泄露相关知识小结
2016/05/16 Javascript
原生js三级联动的简单实现代码
2016/06/07 Javascript
简单学习vue指令directive
2016/11/03 Javascript
JS如何设置iOS中微信浏览器的title
2016/11/22 Javascript
BootStrap点击保存后实现模态框自动关闭的思路(模态框)
2017/09/26 Javascript
angular.js和vue.js中实现函数去抖示例(debounce)
2018/01/18 Javascript
JavaScript惰性求值的一种实现方法示例
2019/01/11 Javascript
Vue实现根据hash高亮选项卡
2019/05/27 Javascript
Webpack5正式发布,有哪些新特性
2020/10/12 Javascript
解决js中的setInterval清空定时器不管用问题
2020/11/17 Javascript
Python找出9个连续的空闲端口
2016/02/01 Python
OpenCV实现人脸识别
2017/04/07 Python
Python学习入门之区块链详解
2017/07/25 Python
python+VTK环境搭建及第一个简单程序代码
2017/12/13 Python
基于logstash实现日志文件同步elasticsearch
2020/08/06 Python
美国女鞋品牌:naturalizer(娜然)
2016/08/01 全球购物
大整数数相乘的问题
2012/07/22 面试题
ktv总经理岗位职责
2014/02/17 职场文书
2014教师年度思想工作总结
2014/11/10 职场文书
安全员岗位职责范本
2015/04/11 职场文书
工作时间调整通知
2015/04/24 职场文书
如何将JavaScript将数组转为树形结构
2021/06/02 Javascript
Python Pandas pandas.read_sql函数实例用法
2021/06/21 Python