[問題] PyQt5 使用QObject的時候出現null object

看板Python作者 (雨四光)時間12年前 (2013/12/18 16:27), 編輯推噓0(002)
留言2則, 1人參與, 最新討論串1/1
我希望程式可以同時去多個網站抓線上字典, 然後抓完的thread可以signal我的main thread去更新GUI 程式大略如下: class Searcher(QObject): update=pyqtSignal(str, str) def __init__(self, dictionary, word): super(Searcher, self).__init__() self.dictionary=dictionary self.word=word def run(self): self.update.emit(self.dictionary, self.word) class MyMainWindow(QMainWindow, Ui_MainWindow, QObject): #發送搜尋的訊號 signal=pyqtSignal() def __init__(self, parent=None): super(MyMainWindow, self).__init__() self.setupUi(self) #兩本字典 self.dictList=['Yahoo dictionary', 'Webster dictionary'] #所以產生兩個Qthread self.searchThreads=[] for dictionary in self.dictList: self.searchThreads.append(QThread()) def click(self): word=self.lineEdit.text() #產生兩個Searcher object self.searchers=[] for dictionary in self.dictList: self.searchers.append(Searcher(dictionary, word)) for index , searcher in enumerate(self.searchers): #讓每個searcher可以通知gui更新 searcher.update.connect(self.renew) #移到thread裡執行 searcher.moveToThread(self.searchThreads[index]) self.searchThreads[index].start() #讓main thread可以發signal通知searcher執行 self.signal.connect(searcher.run) #通知thread裡面的searcher開始執行 self.signal.emit() //////////// 當我搜尋第一個單字的時候完全沒有問題 但是當我搜尋第二個單字的時候 會出現兩個下面這種錯誤 self.update.emit(self.dictionary, self.word) AttributeError: 'NoneType' object has no attribute 'update' 後來try except了一下 發現會有兩個空的Searcher(null object)執行到run 之後再有兩個正常的Searcher執行run 除了第一次正常以外,之後每次都會這樣 不知道問題出在哪裡? 題外話,我本來最一開始寫的是 Searcher(QThread): 可是有文章說You're doing it wrong 所以才改成繼承QObject -- 儘管生命的起源只是一種化學反應 儘管人類的存在只是記憶數據的影子 儘管靈魂並不存在,精神只是神經細胞的火花    儘管世上沒有神,人一定要靠一己之力在這殘酷的世界中掙扎求存   我還是...... 我還是...... 要以意識之名命令你───「活下去」 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.114.202.111

12/19 14:53, , 1F
在清空 self.searchers 之前先把舊的 disconnect
12/19 14:53, 1F

12/19 14:54, , 2F
這程式還有很多其他可以吐槽的地方, 不過我懶得管了...
12/19 14:54, 2F
文章代碼(AID): #1IiLoB7p (Python)
文章代碼(AID): #1IiLoB7p (Python)