Reputation: 11
I have a button called "start" and when I click the button, it becomes "Pause", when I click it again, it doesn't revert back to "start" it just stays as is and I need to be able to have it go back to the original text. How do I go about this? Right now I have this
def button_click(self):
self.start_button.setText("Pause")
This changes the start button to pause but I don't know how to go from pause to start.
Upvotes: -1
Views: 478
Reputation: 48489
Once you set a property on an object, it doesn't "remember" its previous state, unless you provide that feature in some way.
A simple solution, at least for boolean-like objects, would be to store the current state, and toggle between them.
self.start_button = QPushButton('Start')
self.start_state = False
# ...
def button_click(self):
self.start_state = not self.start_state
if self.start_state:
self.start_button.setText("Pause")
else:
self.start_button.setText("Start")
An alternative could be to use a checkable button instead, which is also more clear from the UX perspective as the pressed/unpressed state is much more visible to the eye than a string (imagine using "Start"/"Stop", which are very similar).
Since the clicked
also sends the checked state automatically, you can add the argument to the function you already have and check that instead.
self.start_button = QPushButton('Start')
self.start_button.setCheckable(True)
# ...
def button_click(self, state):
if state:
self.start_button.setText("Pause")
else:
self.start_button.setText("Start")
Note that for this it's usually preferred to use the toggled
signal instead, since it also reacts to setChecked()
and toggle()
functions.
Upvotes: 1
Reputation: 421
I don't think there's a nice fancy way to do this. Probably just do the following:
def button_click(self):
if self.start_button.text() == "Pause":
self.start_button.setText("start")
elif self.start_button.text() == "start":
self.start_button.setText("Pause")
Upvotes: 0