我在下面写代码:
class QWidgetUI(QWidget):
def __init__(self):
super().__init__()
self.IDinput = QLineEdit(self)
self.searchBtn = QPushButton("",self)
像下面的东西一样制作多线程代码:
def __init__(self, parent=None):
super(self.__class__, self).__init__(parent)
self.gui = QWidgetUI()
self.worker = Worker()
self.workerThread = QThread()
self.worker.moveToThread(self.workerThread)
self.workerThread.start()
self.connectSignal()
self.gui.show()
def connectSignal(self):
self.gui.searchBtn.clicked.connect(self.worker.conductCrolling)
conductCrolling是这样的:
class Worker(QObject):
def __init__(self, parent = None):
super(self.__class__, self).__init__(parent)
@pyqtSlot()
def conductCrolling(self):
j = 0
searchingHtml = urlopen('https://www.twitter.com/{}/media'.format(self.gui.IDinput.text()))
在第一个代码中,self.gui.IDinput.text()
具有我输入的正确值。
但是在第三个代码中,为什么第8行的self.gui.IDinput.text()
没有任何值?
答案 0 :(得分:0)
您不应该从另一个线程访问GUI,也不能使用您的代码访问GUI,因为在行为ConductCrolling函数中,self是指Worker类的对象,并且显然Worker没有gui属性。解决方案是在调用conductCrolling函数时将其作为参数传递给文本,为此,您可以使用partial和QTimer:
from functools import partial
# ...
def __init__(self, parent=None):
super(self.__class__, self).__init__(parent)
self.gui = QWidgetUI()
self.worker = Worker()
self.workerThread = QThread()
self.worker.moveToThread(self.workerThread)
self.workerThread.start()
self.connectSignal()
self.gui.show()
def connectSignal(self):
self.gui.searchBtn.clicked.connect(self.launchTask) # change connection
def launchTask(self):
wrapper = partial(self.worker.conductCrolling, self.gui.IDinput.text()) # add text
QTimer.singleShot(0, wrapper) # invoked conductCrolling function
class Worker(QObject):
@pyqtSlot(str) # <---- add str
def conductCrolling(self, text): # <--- add text
# use text
searchingHtml = urlopen('https://www.twitter.com/{}/media'.format(text))