在學習使用qt5的時候,發現要使用多執行緒處理多工,按照等很多網上的方法,測試一下,發現我寫的程式執行就崩潰。
不斷測試,發現乙個現象:
子執行緒的初始化要在視窗初始的同時進行程式**如下:ui_mainwindow 視窗是qt desinger生成的
#-*- coding: utf-8 -*-
#form implementation generated from reading ui file 'd:\pywork\qtpy\threadtest\main.ui'##
created by: pyqt5 ui code generator 5.11.3##
warning! all changes made in this file will be lost!
from pyqt5 import
qtcore, qtwidgets
class
ui_mainwindow(object):
defsetupui(self, mainwindow):
mainwindow.setobjectname(
"mainwindow")
mainwindow.resize(465, 262)
self.centralwidget =qtwidgets.qwidget(mainwindow)
self.centralwidget.setobjectname(
"centralwidget")
self.textedit =qtwidgets.qtextedit(self.centralwidget)
self.textedit.setgeometry(qtcore.qrect(40, 20, 281, 171))
self.textedit.setobjectname(
"textedit")
self.pushbutton =qtwidgets.qpushbutton(self.centralwidget)
self.pushbutton.setgeometry(qtcore.qrect(360, 30, 75, 23))
self.pushbutton.setobjectname(
"pushbutton")
mainwindow.setcentralwidget(self.centralwidget)
self.retranslateui(mainwindow)
qtcore.qmetaobject.connectslotsbyname(mainwindow)
defretranslateui(self, mainwindow):
mainwindow.setwindowtitle(_translate(
"mainwindow
", "
mainwindow"))
self.pushbutton.settext(_translate(
"mainwindow
", "
start
"))
qthread實現類:
#-*- coding: utf-8 -*-
from pyqt5.qtcore import *
class
myqthread(qthread):
senttext =pyqtsignal(str)
def__init__
(self,text): #text是傳遞引數
super(myqthread, self).
__init__
() self.text = text + "
in child thread
"def
run(self):
for i in range(2000000000):
pass
#迴圈完畢後發出訊號
self.senttext.emit(self.text)
呼叫的主類:
#-*- coding: utf-8 -*-
"""module implementing mainwindow.
"""from pyqt5.qtcore import
pyqtslot
from pyqt5.qtwidgets import
from myqthread import
myqthread
from ui_main import
ui_mainwindow
class
mainwindow(qmainwindow, ui_mainwindow):
"""class documentation goes here.
"""def
__init__(self, parent=none):
"""constructor
@param parent reference to the parent widget
@type qwidget
"""super(mainwindow, self).
__init__
(parent)
self.setupui(self)
#在這裡初始化沒有問題
self.myqthread = myqthread("
hello")
self.myqthread.senttext.connect(self.handlemessage)
@pyqtslot()
defon_pushbutton_clicked(self):
"""最開始是在這裡初始化的
myqthread = myqthread("hello")myqthread.senttext.connect(self.handlemessage)
myqthread.start()
"""self.myqthread.start()
defhandlemessage(self, text):
self.textedit.setplaintext(self.textedit.toplaintext()+"
\n" +text)
if__name__ == "
__main__":
import
sys mainwindow =mainwindow()
mainwindow.show()
提醒自已注意
QThread的使用總結
bradley t.hughes 認為 qthread 應該被看做是作業系統執行緒的介面或控制點,而不應該包含需要在新執行緒中執行的 需要執行的 應該放到乙個qobject的子類中,然後將該子類的物件movetothread到新執行緒中。public slots void emitsig signa...
QThread類的使用
概述 ifndef myclass h define myclass h include include class myclass public qthread endif myclass h myclass.cpp檔案 include myclass.h include myclass mycl...
鎖死視窗的程式
這個程式會使視窗無法被滑鼠移動或更改大小 滑稽 可以拿來搞同學電腦。然而切換視窗上下關係的操作沒有鎖死 include include 手寫乙個存視窗的雙向鍊錶 struct node head void insert hwnd hwnd 插入乙個視窗 void remove node p 移除乙個...