Flare Cat
Flare Cat

Reputation: 601

Qt: How to close a dialog window opened with exec()?

I'm making a c++ application in Qt, and need to programmatically close a dialog window (opened with this->exec();) via code after a certain function finishes executing.

I'm using Qt 5.6.

Thanks in advance!

Here is an example of my code, that doesn't work (Worker is the dialog Class):

void MainWindow::on_pushButton_2_clicked()
{
    //When Start button clicked:
    Worker worker;
    worker.exec();
    //worker.run(1);
    worker.accept();
}

So when pushButton_2 is clicked, I want a dialog to open that gives out the current progress, and when that is done, I want it to close.

Upvotes: 0

Views: 9374

Answers (3)

Flare Cat
Flare Cat

Reputation: 601

As I've just learned, the issue is caused by the gui not updating automatically.

Here is a link to a SO question that fixes this issue.

Upvotes: 0

jpo38
jpo38

Reputation: 21564

Edit:

Now you posted more code....

worker.exec();
worker.accept(); // or worker.close();

exec() starts QDialog events processing loop and will return only when completed (after accept(), reject() or done(int) is called). So worker.accept() will not be reached (you should see that if using your debugger). It must be called by worker itself after a user action (button click by instance).

What you meant to do is:

worker.show();
QThread::sleep(2); // wait for 2 seconds
worker.accept();

Then, worker.accept() will be executed at some point. Dialog is shown, but it's modal.


Old post (before edit):

You can call accept() to do as if user clicked OK or reject() to do as if user clicked Cancel.

Note that those are slots, so you can fire them by connecting a signal to them (signal to be emitted when you function finishes executing for instance).

Example:

void MyDialog::doSomethingAndClose()
{
    // do your stuff here
    accept(); // will close the dialog
}

or:

void MyDialog::doSomethingAndClose()
{
    // do your stuff here
    emit weAreDone();
}

If you earlier connected (in MyDialog constructor for instance):

connect( this, SIGNAL(weAreDone()), this, SLOT(accept()) );

Upvotes: 4

tty6
tty6

Reputation: 1233

Just connect your custom signal with QDialog::done(int) and emit signal after your function finishes executing.

Upvotes: 0

Related Questions