如何在PyQt中设置按钮到键盘中断

时间:2014-04-12 07:17:17

标签: python pyqt qpushbutton keyboardinterrupt

在通过终端运行程序时,我们可以通过按Ctrl + c'来停止程序。它会将消息显示为' KeyboardInterrupt' 。那么,有没有办法通过单击PyQt中的按钮来完成理智的事情。

2 个答案:

答案 0 :(得分:1)

如果您的程序正在运行循环,您可以定期调用processEvents以允许gui时间更新(这应该允许您单击按钮以关闭应用程序):

    count = 0
    while True:
         count += 1
         if not count % 50:
             QtGui.qApp.processEvents()
         # do stuff...

答案 1 :(得分:0)

在中断无限循环的脚本中,我还使用了QtGui.qApp.processEvents(),效果很好。无限循环可从串行端口写入和读取数据,用户可以通过按钮(1.condition)来中断循环。

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