简体   繁体   中英

How to disable a QPushButton?

I've got a Push Button in my program which after clicking it doing much calculation. I want to disable it during this time when the calculatings are performed to not permit the program to crashes but my method didn't work.

void MainWindow::on_pushButton_clicked()
{    
ui->pushButton->setEnabled(false);

for( ) { CALCULATION }

ui->pushButton->setEnabled(true);
}

Function setEnabled(false); won't diable the Push Button and I can click on it how many times I want.

Your computation is done in the main thread, so your ui is blocked until the computation is completed. The ui will not be refreshed during the computation and you set back the button at the end of the computation. So there are no changes in the ui during the computation.

The problem with this code lies in the design of a message loop. While handling one message (in this case the button clicked handler), no other messages are handled, including those that repaint widgets to reflect changes to their state. Now, in your function, you disable the button and enable it again before it could be updated.

Note that doing lengthy calculation is UI message handlers is a bad idea, because it locks the whole UI. Instead, use an asynchronous model like a worker thread or do the calculation in steps using a timer. Then, you can also see the button getting disabled.

Although the above answers are quite right about not running heavy tasks on ui handlers because the other ui handlers will freeze I have a one liner that I wouldn't suggest to use:

void MainWindow::on_pushButton_clicked()
{    
ui->pushButton->setEnabled(false);
ui->pushButton->repaint(); 

for( ) { CALCULATION }

ui->pushButton->setEnabled(true);
}

The repaint() method forces the ui thread to prioritize repainting the pushButton before doing the heavy calculation.

Now for something more correct you could try this example that utilizes Qthread (qt thread on button push example)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM