How to set push-button to keyboard interrupt in PyQt

谁说胖子不能爱 提交于 2019-12-04 06:26:16

问题


While running program through the terminal we can stop the program by pressing 'Ctrl+c' and it will show the message as 'KeyboardInterrupt' . So, is there any way to do the sane thing by clicking the push-button in PyQt.


回答1:


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):

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



回答2:


In my script to interrupt an infinite loop I also used QtGui.qApp.processEvents() and it worked out fine. 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).

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


来源:https://stackoverflow.com/questions/23027447/how-to-set-push-button-to-keyboard-interrupt-in-pyqt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!