通过终端运行程序时,我们可以通过按下"Ctrl+c"来停止程序,它将显示消息"KeyboardInterrupt"。那么,有没有什么方法可以通过点击PyQt中的按钮来做正确的事情呢。
如果您的程序正在运行循环,您可以定期调用processEvents以允许gui有时间更新(这应该允许您单击按钮关闭应用程序):
count = 0
while True:
count += 1
if not count % 50:
QtGui.qApp.processEvents()
# do stuff...
在我的脚本中,为了中断一个无限循环,我还使用了QtGui.qApp.processEvents()
,结果很好。无限循环从串行端口写入和读取数据,用户可以通过按钮(1.条件)中断循环
def Move_Right(self):
# move the slide right
cmdPack = struct.pack(cmdStruct, Address, Rotate_Right, 0, Motor5, Speed5)
dataByte = bytearray(cmdPack)
checksumInt = sum(dataByte[:]) % 256
msgPack = struct.pack(msgStruct, Address, Rotate_Right, 0, Motor5, Speed5, checksumInt)
ser0.flushOutput() # Clear output buffer
ser0.write(msgPack)
# read the switch status
cmdPack = struct.pack(cmdStruct, Address, Command.GAP, 10, Motor5, 0)
dataByte = bytearray(cmdPack)
checksumInt = sum(dataByte[:]) % 256
msgPack = struct.pack(msgStruct, Address, Command.GAP, 10, Motor5, 0, checksumInt)
ser0.flushOutput() # Clear output buffer
# check the switch status with an infinite write/read loop with two break out conditions
while True:
QtGui.qApp.processEvents() # 1. condition: interrupt with push button
ser0.write(msgPack)
reply = ser0.read(9)
answer = struct.unpack('>BBBBlB', reply)
value = answer[4]
command = answer[3]
if (command == 6) and (value == 1): # 2. condition: interrupt with limit switch
print 'end of line'
Stop_Motor5()
break