How to set push-button to keyboard interrupt in PyQt

后端 未结 2 1885
傲寒
傲寒 2021-01-27 08:48

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

相关标签:
2条回答
  • 2021-01-27 09:10

    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...
    
    0 讨论(0)
  • 2021-01-27 09:16

    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
    
    0 讨论(0)
提交回复
热议问题