Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable a QPushButton?

Tags:

c++

qt

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.

like image 402
withorlo Avatar asked May 05 '13 15:05

withorlo


2 Answers

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.

like image 189
nosleduc Avatar answered Nov 09 '22 21:11

nosleduc


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.

like image 31
Ulrich Eckhardt Avatar answered Nov 09 '22 21:11

Ulrich Eckhardt