QDialog同时调用show()与exec()是否合规?有何弊端?父窗口可交互吗?
QDialog::show() + exec(): Is This Usage Valid, Are There Drawbacks, and Can I Interact With Parent Window During exec()?
Great question—let’s unpack this based on how Qt handles dialogs and event loops.
First, let’s fix a small syntax quirk in your code snippet (you used -> on a stack-allocated QDialog, which should use . instead):
QDialog my_qDialog(my_parent); my_qDialog.setModal(false); my_qDialog.hide(); // Unnecessary: New dialogs start hidden by default my_qDialog.show(); my_qDialog.exec();
1. Is this usage compliant?
Syntactically, yes—Qt won’t throw compile errors or crash when you run this. But it’s not aligned with Qt’s intended design for dialogs. The exec() method is built to handle both showing the dialog and starting a modal event loop on its own; calling show() beforehand is redundant and serves no practical purpose.
2. Are there any drawbacks?
Absolutely, a few key issues to note:
- Redundant operations:
exec()automatically callsshow()internally, so your explicitshow()does nothing useful. Thehide()call is also pointless, since newly createdQDialogs start in a hidden state. - Ambiguous intent: Mixing
setModal(false)(which marks the dialog as non-modal) withexec()(which is designed for modal behavior) makes your code confusing to other developers. It’s unclear whether you intended a modal or non-modal dialog. - Potential state conflicts: If you add code between
show()andexec()that modifies the dialog’s state (e.g., updating UI elements, changing window flags), you might clash withexec()’s internal initialization logic, leading to unexpected behavior.
3. Can I interact with the parent window during exec()?
This depends on how you’ve configured the dialog’s modality:
- Your
setModal(false)call is equivalent tosetWindowModality(Qt::NonModal), which means the dialog won’t block any other windows. When you callexec()after this, the event loop it starts won’t block interaction with the parent window—this matches what you observed. - That said,
exec()still blocks the current thread’s code execution until the dialog closes (which is why your code afterexec()only runs once the dialog is closed). This is a key distinction: non-modal modality lets you interact with other windows, butexec()still pauses the calling thread.
Recommended Best Practices
- If you want a non-modal dialog: Skip
exec()entirely. Just callshow(), and make sure the dialog’s lifecycle is managed correctly (e.g., usenewwith a parent, or keep it in a scope that doesn’t end immediately). - If you want a modal dialog: Call only
exec()—it will handle showing the dialog and blocking the appropriate windows automatically. No need forshow()orsetModal(false).
内容的提问来源于stack exchange,提问作者Igor
相关产品推荐
相关产品推荐

