Python 线程和 gui 应用程序之间的新样式信号和槽

Python new style signals and slot between thread and gui app

我是 OOP 的新手 python。我正在尝试使用新式信号和插槽从 Qthread 向 Qt GUI main window 发出信号。

这是话题。在 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和app部分是这样的(我省略了其他可能不相关的代码)。

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' object has no attribute 'connect'

感谢您的建议(与主题和风格相关),并为没有制作 MWE 表示歉意。

您的示例的结构或多或少是正确的:但是您将旧式信号槽语法与新式混合在一起。

信号定义应如下所示:

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 in the PyQt4 reference