我是 OOP 和 python 的新手。我正在尝试使用新样式的信号和插槽从 Qthread 向 Qt GUI 主窗口发出信号。
这就是线程。在单击 GUI 中的“运行”按钮后 3 秒后,我将在 GUI 中发出用于更新消息对话框的信号。我不确定继承是否定义正确或者信号是否以正确的方式定义。
class OptimThread (QtCore.QThread):
signalUpdateMessageDialog = QtCore.SIGNAL("updateMessageDialog(PyQt_PyObject,QString)")
def __init__(self):
QtCore.QThread.__init__(self)
def run(self):
start = time.time()
self.emit(self.signalUpdateMessageDialog, time.time() - start, 'Initialising...')
time.sleep(3)
self.emit(self.signalUpdateMessageDialog, time.time() - start, 'You waited 3 seconds...')
主类和应用程序部分是这样的(我省略了其他可能不相关的代码)。
class Main(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(Main, self).__init__(parent)
def updateMessageDialog(self, times, dialog):
hours = str(datetime.timedelta(seconds=int(times)))
self.MessageDialog.insertHtml('<tt>' + hours + ':</tt> ' + dialog + '<br>')
return
def clickRun(self):
self.optimThread = OptimThread()
self.connect(self.optimThread, QtCore.SIGNAL("updateMessageDialog(PyQt_PyObject,QString)"), self.updateMessageDialog)
#self.optimThread.signalUpdateMessageDialog.connect(self.updateMessageDialog)
self.optimThread.start()
if __name__ == '__main__':
app=QtGui.QApplication(sys.argv)
window=Main(None)
app.setActiveWindow(window)
window.show()
sys.exit(app.exec_()) # Exit from Python
如果一切都这样写,它就可以了。
然而,如果我想在 Main 中使用新的连接方式:
self.optimThread.signalUpdateMessageDialog.connect(self.updateMessageDialog)
它说:
self.optimThread.signalUpdateMessageDialog.connect(self.updateMessageDialog)
AttributeError:“str”对象没有属性“connect”
感谢您的建议(与主题和风格相关),并对没有制作 MWE 表示歉意。