Programmatically Toggle a Python PyQt QPushbutton

2019-06-28 00:52发布

问题:

Is it possible to programmatically toggle a QPushButton? I have a checkable QPushButton that a user presses to start a process. When the process is done, how can the button's state be changed to unchecked?

runBtn = QPushButton('Run')
runBtn.setCheckable(True)
runBtn.clicked.connect(runProcess)

def runProcess():
    time.sleep(5)
    runBtn.uncheck()    # how should this be done?

回答1:

this should to the trick.

runBtn.setChecked(False)

although that's not ideal behaviour. toggle buttons should be used for turning things on and off, not indicating that something is in progress. if something is taking time you should change the cursor to a wait cursor and better still show a progress bar/dialog.



回答2:

It should just be a matter of calling runBtn.setChecked(False) once your function has finished running.

As @hluk points out in the comment on this answer, anything that takes a long time to do will block the interface and isn't really a great idea. It would be better to split it off into a thread in that case. This is probably means a lot more learning on your part, but could be worth it in the long run. Anyway, should you decide to go the thread route, you might also want to use setEnabled(bool) to disable user input through the button while the thread is running.



回答3:

You can use QpushButton and style sheet with it. here is code

if(process==running):
     button.setStyleSheet(ENABLE_STYLESHEET )
else
     button.setStyleSheet(DISABLE_STYLESHEET )

and you can define the style sheets as below

ENABLE_STYLESHEET = """
    QPushButton {
        border: 1px solid #007a94;
        border-radius: 6px;
        color:#ffffff;
        background-color: #007a94;
        min-width: 80px;
        }
    QPushButton:pressed {
        background-color: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
                                  stop: 0 #008aa6, stop: 1 #008aa6);
        }

    QPushButton:flat {
        border: none;
        }
"""    
DISABLE_STYLESHEET = """
    QPushButton {
       border: 1px solid #808080;
       border-radius: 6px;
       color:#ffffff;
       background-color: #808080;
       min-width: 80px;
       }
   QPushButton:flat {
       border: none;
       }

"""