PDA

View Full Version : How to exit in a QDialog constructor



ms77
2nd December 2009, 08:44
Hi All,

I want to know how to close a Dialog in its constructor. (without using QTimer:singlshoot).


Thanks in advance to all.

spirit
2nd December 2009, 09:21
you can use QMetaObject::invokeMethod with Qt::QueuedConnection, i.e.


MyDgl::MyDlg(QWidget *parent)
: QDialog(parent)
{
...
QMetaObject::invokeMethod(this, "close", Qt::QueuedConnection);
}

ms77
2nd December 2009, 09:42
Thanks.

I test it, it works, but we see the dialog in short laps of time before it is closed.
Do you know how to bypass this "cosmetic" issue ?

wysota
2nd December 2009, 09:44
Until you show the dialog, it is hidden. So simply don't show it at all if you don't want to.

Coises
2nd December 2009, 14:46
I want to know how to close a Dialog in its constructor. (without using QTimer:singlshoot).

I think there’s a slight misunderstanding implied by your question.

A constructor constructs an object of the specified type — short of throwing an exception (not the way to go here!) it will always construct an object — but a constructed QDialog object doesn’t do anything until you call exec(), open() or show() on it.

One of those functions is normally called by the same code that calls the constructor. If that’s the case in your program, then what you want to do is not “close the dialog in its constructor” but supply a return value (if the caller uses it) and keep the caller from ever calling QDialog::exec(), QDialog::open () or QWidget::show().

If the calling code just constructs the dialog and then calls exec(), write another member function and call it instead of exec():


int execConditional() {return doNotOpenThisDialog ? valueWhenNotOpened : exec();}

If you do something more involved, such as using a modeless dialog, you might need to emit a signal or two when bypassing display of the dialog.

The one case I can imagine where this could get quite complicated is if you must pass your constructed object to other code which knows only that it is a QDialog, but has no information about your sub-class. Since the exec(), open() and show() slots are not virtual, you can’t just override them if they’re going to be called on the underlying QDialog object.

But if you’re not doing something like that — if all the code that interacts with your dialog knows what dialog it is, not just that it’s some sort of dialog — then use the straightforward method and just have the code call separate member functions that wrap exec(), open() and/or show() to avoid displaying the dialog when it’s not desired.