如何在PyQt中将按钮设置为键盘中断
在终端运行程序时,我们可以通过按 'Ctrl+c' 来停止程序,这时会显示一个消息叫 'KeyboardInterrupt'。那么,有没有办法在 PyQt 中通过点击一个按钮来实现同样的效果呢?
2 个回答
0
在我的脚本中,为了中断一个无限循环,我使用了 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
1
如果你的程序正在运行一个循环,你可以定期调用 processEvents,这样可以给图形界面留出时间来更新(这也能让你点击一个按钮来关闭应用程序):
count = 0
while True:
count += 1
if not count % 50:
QtGui.qApp.processEvents()
# do stuff...