简体   繁体   English

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

[英]How to set push-button to keyboard interrupt in PyQt

While running program through the terminal we can stop the program by pressing 'Ctrl+c' and it will show the message as 'KeyboardInterrupt' . 通过终端运行程序时,我们可以通过按“ Ctrl + c”来停止程序,它将显示为“ KeyboardInterrupt”消息。 So, is there any way to do the sane thing by clicking the push-button in PyQt. 因此,有什么方法可以通过单击PyQt中的按钮来执行理智的事情。

If your program is running a loop, you can call processEvents periodically to allow the gui time to update (which should allow you to click a button to close the application): 如果程序正在运行循环,则可以定期调用processEvents以允许gui时间更新(这应允许您单击按钮以关闭应用程序):

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

In my script to interrupt an infinite loop I also used QtGui.qApp.processEvents() and it worked out fine. 在中断无限循环的脚本中,我还使用了QtGui.qApp.processEvents() ,效果很好。 The infinite loop writes to and reads data from a serial port and the user can interrupt the loop with a push button (1.condition). 无限循环可从串行端口写入和读取数据,用户可以通过按钮(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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM