Home > Mobile >  How do I make python script wait for pyqt button selection before continuing?
How do I make python script wait for pyqt button selection before continuing?

Time:07-29

I'm trying to figure out how to insert a pyqt5 button into a python script and pause the script so it waits for the button press before it continues.

class MainWindow(QtWidgets.QMainWindow):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
                
        self.ui.button.clicked.connect(pyfile.dothething)
        self.ui.button2.clicked.connect(pyfile.dotheotherthing)

def do_the_stuff():
    do some stuff
    wait for button press
    do_the_stuff()
    

the do_the_stuff() is going to ignore the button since normal python is not event based. How do I insert an event based wait function in the normal python script so it waits until the pyqt button is pressed?

CodePudding user response:

You could add state to your normal code to enable the flow control. For example:

class NormalCode:
    def __init__(self):
        self.state = 0

    def do_the_stuff(self):
        do some stuff
        while self.state == 0:
            # Prevent hammering the CPU
            time.sleep(0.1)
        do_the_stuff()

Then your button click can simply change the state:

def on_button_clicked(self):
    self.normal_code.state = 1

This should be fairly clean to implement as the normal code still doesn't need to know that the Qt layer exists.

  • Related