问题描述
我是OOP和python的新手.我正在尝试使用新样式的信号和插槽将信号从Qthread发射到Qt GUI主窗口.
I am newbie to OOP and python. I am trying to emit signal from Qthread to Qt GUI main window using new style signals and slots.
这是线程.在内部,单击GUI中的运行"按钮后3秒钟,我将在GUI中发出用于更新消息对话框的信号.我不确定继承是否定义正确,或者信号是否定义正确.
This is the thread. Inside I will emit signals for updating message dialog in GUI after clicking RUN button in GUI and 3 seconds after that. I am not sure if the inheritance is defined OK or is the signal defined in the right manner.
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...')
主类和应用程序部分是这样的(我省略了其他可能无关的代码).
The main class and the app part is like this (I omitted the other probably unrelevant code).
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中使用新样式进行连接:
If evertyhing is written like this, It works.Yet if I want to use new style for connecting in Main:
self.optimThread.signalUpdateMessageDialog.connect(self.updateMessageDialog)
它说:
感谢您的建议(与主题和风格有关),并为没有制作MWE表示歉意.
I appreciate your advices (related to the subject and related to the style) and apologize for not making an MWE.
推荐答案
示例的结构或多或少是正确的:但是您正在将旧样式的信号槽语法与新样式混合在一起.
The structure of your example is more or less right: but you are mixing up the old-style signal-slot syntax with the new-style.
信号定义应如下所示:
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 ++签名.
With the new-style syntax, there is never any need to use SIGNAL()
or SLOT()
, and it is never necessary to specify the C++ signature.
有关更多详细信息,请参阅以下网页中的新型信号和插槽支持. PyQt4参考.
For further details, see New-style Signal and Slot Support in the PyQt4 reference.
这篇关于Python新样式信号以及线程和gui应用之间的插槽的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!