pyqt 多线程使用
1.通过类成员定义信号对象(这里的类我是放在了qt-ui转化后的py文件中xxxxxui.py)
import traceback
import pymysql
from PyQt5 import Qtcore, QtGui, Qtwidgets
from PyQt5 import pyqtSignal, QMutex
class cachethread(Qtcore.QThread):
_singnal = pyqtSignal(list)
def __init__(self,currentpage, 传参值1,.....):
super(cachethread, self).__init__() #注意使用类名
self.database_con() #l数据库函数
self.参数1 = 传参值1
......
def database_con(self):
self._translate = QtCore.QCoreApplication.translate
conf = configparser.ConfigParser()
self.coon = pymysql(host=xxxx,port=xxxx,user=xxxx,password=xxxx,database=xxxx)
self.cur = self.coon.cursor()
def run(self):
try:
逻辑
self._signal.emit(结果)
except:
print(traceback.format_exc()#查看报错
2.UI转化文件绑定函数按钮(xxxxxui.py):
self.pushButton_1.clicked.connect(Mainwindow.函数1)
3.主界面py文件引入多线程(main.py):
form xxxx import * #这里xxxx指你的ui.py文件名称,下方需要用到
class my_mainwindow(QMainWindow, Ui_MainWindow): #Ui_MainWindow是上面qt-ui转化后的py文件中的类
def __init__(self):
super().__init__()
self.setupUi(self) #设置界面
#sys.excepthook = self.catch_exceptions 捕获异常函数,其他博客我会介绍
......
#在你需要执行的地方加入多线程,这个函数我是绑定在ui转化的py文件的按钮中,也就是第二步
def 函数1(self):
self.thread = CacheThread(self.currentpage,......) #引用函数
self.thread._signal.connect(self.changeedit)
self.thread.start()
def changeedit(self, result):
self.cach1 = result
if __name__=="__main__":
app = QApplication(sys.argv)
window = login_window()
Ui_Main = my_mainwindow()#生成主窗口,也就是上方的类
window.show()
sys.exit(app.exec())
错误的地方欢迎大家指正,不懂的或者想要源码的朋友可以留言私信。