我是OOP和python的新手。我正在尝试使用新的样式信号和插槽从Qthread向Qt GUI主窗口发出信号。
这是主题。在GUI中点击RUN按钮后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
如果evertyhing是这样写的,那就有效。 然而,如果我想在Main中使用新样式进行连接:
self.optimThread.signalUpdateMessageDialog.connect(self.updateMessageDialog)
它说:
self.optimThread.signalUpdateMessageDialog.connect(self.updateMessageDialog) AttributeError:'str'对象没有属性'connect'
我感谢您的建议(与主题相关并与风格相关),并为不制作MWE而道歉。
答案 0 :(得分:1)
您的示例的结构或多或少是正确的:但您将旧式信号槽语法与新风格混合在一起。
信号定义应如下所示:
class OptimThread(QtCore.QThread):
signalUpdateMessageDialog = QtCore.pyqtSignal(int, str)
信号应该像这样发出:
self.signalUpdateMessageDialog.emit(
time.time() - start, 'Initialising...')
这就是信号的连接方式:
self.optimThread.signalUpdateMessageDialog.connect(
self.updateMessageDialog)
使用新式语法,绝不需要使用SIGNAL()
或SLOT()
,也无需指定C ++签名。
有关详细信息,请参阅New-style Signal and Slot Support中的PyQt4 reference。